Registering a cluster

This page explains how to register, list, and view details of a Game Servers cluster in a realm.

Before you begin

Before you start, we recommend you familiarize yourself with key concepts in the Game Servers Overview. Make sure you have also performed the following tasks:

  • Ensure that you have enabled the Game Services API.
  • Enable Game Services API
  • Either choose a shell with Cloud SDK installed, or use an API client:
  • Cloud Shell

    To launch Cloud Shell, perform the following steps:

    1. Go to Google Cloud Console.

      Google Cloud Console

    2. From the upper-right corner of the console, click the Activate Cloud Shell button:

    A Cloud Shell session opens inside a frame lower on the console. You use this shell to run gcloud commands.

    Local shell

    To install gcloud, install the Cloud SDK, which includes the gcloud command-line tool.

    Verify that you have set desired default project for gcloud command-line tool (otherwise you need to specify flag --project explicitly for each command later):

    gcloud config list project
    

    If not you can run the following command to set a default project, replacing project-id with your desired project ID :

    gcloud config set project project-id
    

    Run the following command to verify your version of the Google Cloud SDK. Game Servers requires version 306.0.0 or higher of the SDK.

    gcloud version
    

    To update your installation, run the following command:

    gcloud components update
    

    Client Library

    Google Cloud Game Servers can be controlled programmatically using a client library. See Client Libraries Overview for instructions on using the library and authenticating.

Registering a cluster

Make sure you have created a Game Servers realm.

If you don't have a Google Kubernetes Engine (GKE) cluster with Agones installed, do the following:

  1. Create a Google Kubernetes Engine cluster. Make sure to enable the Kubernetes Engine API.
  2. Install Agones.
  3. Make sure your Agones and Kubernetes cluster versions are compliant, and you have installed Agones in the agones-system namespace.

Registering a game server cluster

gcloud

You can register a Game Servers cluster in a realm using the gcloud command-line tool.

Registering a global game server cluster

To register a global game server cluster:

  1. Run the following command and replace the placeholder values, such as realmID, with appropriate values:

    gcloud game servers clusters create gscID --realm=realmID --gke-cluster=gkeCluster --namespace=default --dry-run
    

    The output returns the targetState so that you can preview the new cluster before registering it.

  2. To register and create the global cluster, run the following command:

    gcloud game servers clusters create gscID --realm=realmID --gke-cluster gkeCluster --namespace=default --no-dry-run
    

Registering a regional game server cluster

To register a regional game server cluster:

  1. Run the following command and replace the placeholder values, such as realmID, with appropriate values:

    gcloud game servers clusters create gscID --realm=realmID --gke-cluster gkeCluster --location=region --namespace=default --dry-run
    

    The output returns the targetState so that you can preview the new cluster before creating it.

  2. To register and create the regional cluster, run the following command:

    gcloud game servers clusters create gscID --realm=realmID --gke-cluster gkeCluster --location=region --namespace=default --no-dry-run
    

If Game Servers can't validate the cluster you're trying to attach, you might see the following error:

Cannot connect to the provided Kubernetes cluster "projects/project/locations/location/clusters/gkeCluster, check the name and make sure that the cluster exists

If so, make sure gkeCluster is correctly formatted and that the cluster exists in project and at location.

The variable placeholders correspond to the following descriptions:

  • gscID is a unique identifier that you can specify for this cluster.
  • realmID is the unique identifier for the realm where you want to store the cluster.
  • gkeCluster is the fully-qualified resource path of a GKE cluster, such as projects/<projectId>/locations/<location>/clusters/<clusterId>.
  • region is the region for the cluster. Pick the same region as the parent realm.

Go

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.


import (
	"context"
	"fmt"
	"io"

	gaming "cloud.google.com/go/gaming/apiv1"
	gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1"
)

// createCluster registers a game server cluster.
func createCluster(w io.Writer, projectID, location, realmID, clusterID, gkeClusterName string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	// clusterID := "mycluster"
	// gkeClusterName := "projects/1234/locations/us-central1/clusters/gke-cluster"
	ctx := context.Background()
	client, err := gaming.NewGameServerClustersClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerClustersClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.CreateGameServerClusterRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/%s/realms/%s", projectID, location, realmID),
		GameServerClusterId: clusterID,
		GameServerCluster: &gamingpb.GameServerCluster{
			ConnectionInfo: &gamingpb.GameServerClusterConnectionInfo{
				Namespace: "default",
				ClusterReference: &gamingpb.GameServerClusterConnectionInfo_GkeClusterReference{
					GkeClusterReference: &gamingpb.GkeClusterReference{
						Cluster: gkeClusterName,
					},
				},
			},
			Description: "My Game Server Cluster",
		},
	}

	op, err := client.CreateGameServerCluster(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateGameServerCluster: %v", err)
	}
	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Cluster created: %v", resp.Name)
	return nil
}

Java

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.gaming.v1.CreateGameServerClusterRequest;
import com.google.cloud.gaming.v1.GameServerCluster;
import com.google.cloud.gaming.v1.GameServerClusterConnectionInfo;
import com.google.cloud.gaming.v1.GameServerClustersServiceClient;
import com.google.cloud.gaming.v1.GkeClusterReference;
import com.google.cloud.gaming.v1.OperationMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateCluster {

  public static void createGameServerCluster(
      String projectId, String regionId, String realmId, String clusterId, String gkeName)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // String realmId = "your-realm-id";
    // String clusterId = "your-game-server-cluster-id";
    // String gkeName = "projects/your-project-id/locations/us-central1/clusters/test";
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (GameServerClustersServiceClient client = GameServerClustersServiceClient.create()) {
      String parent =
          String.format("projects/%s/locations/%s/realms/%s", projectId, regionId, realmId);
      String clusterName = String.format("%s/gameServerClusters/%s", parent, clusterId);

      GameServerCluster gameServerCluster =
          GameServerCluster.newBuilder()
              .setName(clusterName)
              .setConnectionInfo(
                  GameServerClusterConnectionInfo.newBuilder()
                      .setGkeClusterReference(
                          GkeClusterReference.newBuilder().setCluster(gkeName).build())
                      .setNamespace("default"))
              .build();

      CreateGameServerClusterRequest request =
          CreateGameServerClusterRequest.newBuilder()
              .setParent(parent)
              .setGameServerClusterId(clusterId)
              .setGameServerCluster(gameServerCluster)
              .build();

      OperationFuture<GameServerCluster, OperationMetadata> call =
          client.createGameServerClusterAsync(request);

      GameServerCluster created = call.get(1, TimeUnit.MINUTES);
      System.out.println("Game Server Cluster created: " + created.getName());
    }
  }
}

Node.js

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.

const {
  GameServerClustersServiceClient,
} = require('@google-cloud/game-servers');

const client = new GameServerClustersServiceClient();

async function createGameServerCluster() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const location = 'A Compute Engine region, e.g. "us-central1"';
  // const realmId = 'The ID of the realm to locate this cluster in';
  // const gameClusterId = 'A unique ID for this Game Server Cluster';
  // const gkeClusterName= 'The full resource name of the GKE cluster to use';
  const request = {
    // Provide full resource name of a Game Server Realm
    parent: client.realmPath(projectId, location, realmId),
    gameServerClusterId: gameClusterId,
    gameServerCluster: {
      description: 'My Game Server Cluster',
      connectionInfo: {
        gkeClusterReference: {
          // Provide full resource name of a Kubernetes Engine cluster
          // In the form of 'projects/<project-id>/locations/<location>/clusters/<gke-cluster-name>'
          cluster: gkeClusterName,
        },
        namespace: 'default',
      },
    },
  };

  const [operation] = await client.createGameServerCluster(request);
  const [result] = await operation.promise();

  console.log('Game Server Cluster created:');
  console.log(`\tCluster name: ${result.name}`);
  console.log(`\tCluster description: ${result.description}`);
  console.log(
    `\tGKE cluster: ${result.connectionInfo.gkeClusterReference.cluster}`
  );
}

createGameServerCluster();

Python

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.

def create_cluster(project_id, location, realm_id, cluster_id, gke_cluster_name):
    """Creates a game server cluster."""

    client = gaming.GameServerClustersServiceClient()

    gke_cluster_reference = game_server_clusters.GkeClusterReference(
        cluster=gke_cluster_name,
    )
    request = game_server_clusters.CreateGameServerClusterRequest(
        parent=f"projects/{project_id}/locations/{location}/realms/{realm_id}",
        game_server_cluster_id=cluster_id,
        game_server_cluster=game_server_clusters.GameServerCluster(
            description="My Game Server Cluster",
            connection_info=game_server_clusters.GameServerClusterConnectionInfo(
                gke_cluster_reference=gke_cluster_reference,
                namespace="default",
            ),
        ),
    )

    operation = client.create_game_server_cluster(request)
    print(f"Create cluster operation: {operation.operation.name}")
    operation.result(timeout=120)

After you create a game server cluster, Game Servers creates Agones fleets and autoscalers as required. Game Servers doesn't alter manually-created Agones fleets.

Listing clusters

gcloud

You can list global or regional clusters using the gcloud command-line tool.

To list both global and regional clusters, run the following command:

gcloud game servers clusters list

To list only clusters in a region, run the following command and replace region with the region that you want to list the clusters in:

gcloud game servers clusters list --location=region

To list all clusters in a realm, run the following command and replace realmID with the parent realm and region with the region that you want to list the clusters in:

gcloud game servers clusters list --realm=realmID --location=region

Go

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.


import (
	"context"
	"fmt"
	"io"

	gaming "cloud.google.com/go/gaming/apiv1"
	"google.golang.org/api/iterator"
	gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1"
)

// listGameServerClusters lists the clusters registered with a realm.
func listGameServerClusters(w io.Writer, projectID, location, realmID string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	ctx := context.Background()
	client, err := gaming.NewGameServerClustersClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerClustersClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.ListGameServerClustersRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s/realms/%s", projectID, location, realmID),
	}

	it := client.ListGameServerClusters(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %v", err)
		}

		fmt.Fprintf(w, "Cluster listed: %v\n", resp.Name)
	}

	return nil
}

Java

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.


import com.google.cloud.gaming.v1.GameServerCluster;
import com.google.cloud.gaming.v1.GameServerClustersServiceClient;
import com.google.cloud.gaming.v1.GameServerClustersServiceClient.ListGameServerClustersPagedResponse;
import com.google.cloud.gaming.v1.ListGameServerClustersRequest;
import com.google.common.base.Strings;
import java.io.IOException;

public class ListClusters {

  public static void listGameServerClusters(String projectId, String regionId, String realmId)
      throws IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (GameServerClustersServiceClient client = GameServerClustersServiceClient.create()) {
      String parent =
          String.format("projects/%s/locations/%s/realms/%s", projectId, regionId, realmId);

      ListGameServerClustersPagedResponse response = client.listGameServerClusters(parent);
      for (GameServerCluster cluster : response.iterateAll()) {
        System.out.println("Game Server Cluster found: " + cluster.getName());
      }

      while (!Strings.isNullOrEmpty(response.getNextPageToken())) {
        ListGameServerClustersRequest request =
            ListGameServerClustersRequest.newBuilder()
                .setParent(parent)
                .setPageToken(response.getNextPageToken())
                .build();
        response = client.listGameServerClusters(request);
        for (GameServerCluster cluster : response.iterateAll()) {
          System.out.println("Game Server Cluster found: " + cluster.getName());
        }
      }
    }
  }
}

Node.js

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.

const {
  GameServerClustersServiceClient,
} = require('@google-cloud/game-servers');

const client = new GameServerClustersServiceClient();

async function listGameServerClusters() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const location = 'A Compute Engine region, e.g. "us-central1"';
  // const realmId = 'The ID of the realm to locate this cluster in';
  const request = {
    // Provide full resource name of a Game Server Realm
    parent: client.realmPath(projectId, location, realmId),
  };

  const results = await client.listGameServerClusters(request);
  const [clusters] = results;

  for (const cluster of clusters) {
    console.log('Game Server Cluster:');
    console.log(`\tCluster name: ${cluster.name}`);
    console.log(`\tCluster description: ${cluster.description}`);
    console.log(
      `\tGKE cluster: ${cluster.connectionInfo.gkeClusterReference.cluster}`
    );
  }
}

listGameServerClusters();

Python

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.

def list_clusters(project_id, location, realm_id):
    """Lists the existing game server clusters."""

    client = gaming.GameServerClustersServiceClient()

    response = client.list_game_server_clusters(
        parent=f"projects/{project_id}/locations/{location}/realms/{realm_id}"
    )

    for cluster in response.game_server_clusters:
        print(f"Name: {cluster.name}")

    return response.game_server_clusters

Viewing details about a cluster

gcloud

You find details about a cluster, such as the creation time or GKE cluster details, using the gcloud command-line tool:

To view the details of a cluster, run the following command and replace the placeholder values, such as realmID, with appropriate values:

gcloud game servers clusters describe gscID --realm realmID --location=region

The output gives you the details of the cluster.

The variable placeholders correspond to the following descriptions:

  • gscID is the unique identifier that you specified for this game server cluster.
  • realmID is a unique identifier for the realm where your cluster is stored.
  • region is the region for the cluster. Pick the same region as the parent realm.

Go

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.


import (
	"context"
	"fmt"
	"io"

	gaming "cloud.google.com/go/gaming/apiv1"
	gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1"
)

// getGameServerCluster retrieves info on a game server cluster.
func getGameServerCluster(w io.Writer, projectID, location, realmID, clusterID string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	// clusterID := "mycluster"
	ctx := context.Background()
	client, err := gaming.NewGameServerClustersClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerClustersClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.GetGameServerClusterRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/realms/%s/gameServerClusters/%s", projectID, location, realmID, clusterID),
	}

	resp, err := client.GetGameServerCluster(ctx, req)
	if err != nil {
		return fmt.Errorf("GetGameServerCluster: %v", err)
	}

	fmt.Fprintf(w, "Cluster retrieved: %v", resp.Name)
	return nil
}

Java

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.


import com.google.cloud.gaming.v1.GameServerCluster;
import com.google.cloud.gaming.v1.GameServerClustersServiceClient;
import java.io.IOException;

public class GetCluster {

  public static void getGameServerCluster(
      String projectId, String regionId, String realmId, String clusterId) throws IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // String realmId = "your-realm-id";
    // String clusterId = "your-game-server-cluster-id";
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (GameServerClustersServiceClient client = GameServerClustersServiceClient.create()) {
      String parent =
          String.format("projects/%s/locations/%s/realms/%s", projectId, regionId, realmId);
      String clusterName = String.format("%s/gameServerClusters/%s", parent, clusterId);

      GameServerCluster cluster = client.getGameServerCluster(clusterName);

      System.out.println("Game Server Cluster found: " + cluster.getName());
    }
  }
}

Node.js

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.

const {
  GameServerClustersServiceClient,
} = require('@google-cloud/game-servers');

const client = new GameServerClustersServiceClient();

async function getGameServerCluster() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const location = 'A Compute Engine region, e.g. "us-central1"';
  // const realmId = 'The ID of the realm to locate this cluster in';
  // const gameClusterId = 'The unique ID for this Game Server Cluster';
  const request = {
    // Provide full resource name of a Game Server Realm
    name: client.gameServerClusterPath(
      projectId,
      location,
      realmId,
      gameClusterId
    ),
  };

  const [cluster] = await client.getGameServerCluster(request);

  console.log('Game Server Cluster:');
  console.log(`\tCluster name: ${cluster.name}`);
  console.log(`\tCluster description: ${cluster.description}`);
  console.log(
    `\tGKE cluster: ${cluster.connectionInfo.gkeClusterReference.cluster}`
  );
}

getGameServerCluster();

Python

To learn how to install and use the client library for Game Servers, see the Game Servers Client Libraries.

def get_cluster(project_id, location, realm_id, cluster_id):
    """Gets a game server cluster."""

    client = gaming.GameServerClustersServiceClient()

    request = game_server_clusters.GetGameServerClusterRequest(
        name=f"projects/{project_id}/locations/{location}/realms/{realm_id}/gameServerClusters/{cluster_id}",
    )

    response = client.get_game_server_cluster(request)
    print(f"Get cluster response:\n{response}")
    return response

Troubleshooting

IAM permissions error

If the permissions aren't set correctly, you'll see the following error:

Cannot connect to the provided Kubernetes cluster "projects/projectId/locations/location/clusters/gkeCluster", make sure that "service-projectNumber@gcp-sa-gameservices.iam.gserviceaccount.com" has been granted the required permissions to access the cluster

If this occurs, complete the step in this section for setting IAM permissions.

When you create Game Servers resources in a Google Cloud project, Game Servers also creates a Game Servers Google-managed service account that takes the form serviceAccount:service-projectNumber@gcp-sa-gameservices.iam.gserviceaccount.com. This service account is automatically granted the predefined Game Servers roles/gameservices.serviceAgent role. This role gives the Google-managed service account the necessary permissions to manage the GKE cluster you're registering. If you revoke it, you will see the above error message.

The following command shows the syntax for granting the service account the Game Servers roles/gameservices.serviceAgent role:

gcloud projects add-iam-policy-binding projectId --role roles/gameservices.serviceAgent --member serviceAccount:service-projectNumber@gcp-sa-gameservices.iam.gserviceaccount.com

where:

  • projectId is the ID of the project. You can get projectId by running gcloud config get-value project.
  • projectNumber can be retrieved by running gcloud projects describe projectId.

What's next

Learn how to delete a cluster.