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
    

    curl / PowerShell

    To use the REST API with curl or Windows PowerShell, do the following:

    1. Create a service account.
    2. Download a private key as a JSON file.
    3. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

    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 public Google Kubernetes Engine cluster. Make sure to enable the Kubernetes Engine API.

    Note the following:

  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

Console

  1. In the Cloud Console, go to the Realms & Clusters page.

    Go to Game Servers

  2. Click Add Game Server Cluster.

  3. Select the realm the game server cluster will belong to from the Realms to choose from list. You can click the Create a Realm button to create a realm if needed.

  4. Click Continue.

  5. In the Game server cluster ID box, enter a unique identifier for this game server cluster.

  6. In the Kubernetes cluster list, select a Kubernetes cluster with Agones installed.

  7. Click Create.

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.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_ID: your Google Cloud project ID listed in the IAM Settings
  • REALM_LOCATION: the region for the realm, or global, in which to store this cluster
  • REALM_ID: the identifier for the realm in which to store this cluster
  • GS_CLUSTER_ID: a user-defined identifier for the cluster
  • GKE_CLUSTER_LOCATION: the region of the GKE cluster
  • GKE_CLUSTER_ID: the identifier for a GKE cluster

Request JSON body:

{
  "name": "projects/PROJECT_ID/locations/REALM_LOCATION/realms/REALM_ID/gameServerClusters/GS_CLUSTER_ID",
  "connectionInfo": {
    "namespace": "default",
    "gkeClusterReference": {
      "cluster": "projects/PROJECT_ID/locations/GKE_CLUSTER_LOCATION/clusters/GKE_CLUSTER_ID"
    }
  }
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_ID/locations/REALM_LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.gaming.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_ID/locations/REALM_LOCATION/realms/REALM_ID/gameServerClusters/GS_CLUSTER_ID",
    "verb": "create",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

Go

To learn how to install and use the client library for Game Servers, see 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 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 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 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

Console

  1. In the Cloud Console, go to the Realms & Clusters page.

    Go to Game Servers

  2. Expand a realm to see the game server clusters that belong to it.

  3. You can use the filter box to filter the realms and clusters list by different properties.

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

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_ID: your Google Cloud project ID listed in the IAM Settings
  • REALM_LOCATION: the region for the realm or global
  • REALM_ID: the user-defined identifier for the realm

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "gameServerClusters": [
    {
      "name": "projects/PROJECT_ID/locations/REALM_LOCATION/realms/REALM_ID/gameServerClusters/my-gs-cluster-1",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "connectionInfo": {
        "namespace": "default",
        "gkeClusterReference": {
          "cluster": "projects/PROJECT_ID/locations/GKE_CLUSTER_LOCATION/clusters/my-gke-cluster-1"
        }
      },
      "etag": "8mBC7IJJFvY40k-rBabOOaGR6sSRG3dP6pI-frTuu9Y",
      "clusterState": {
        "agonesVersionInstalled": "1.15.0",
        "kubernetesVersionInstalled": "1.18.20-gke.900",
        "installationState": "AGONES_KUBERNETES_VERSION_SUPPORTED",
        "provider": "gke"
      }
    },
    {
      "name": "projects/PROJECT_ID/locations/REALM_LOCATION/realms/REALM_ID/gameServerClusters/my-gs-cluster-2",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "connectionInfo": {
        "namespace": "default",
        "gkeClusterReference": {
          "cluster": "projects/PROJECT_ID/locations/GKE_CLUSTER_LOCATION/clusters/my-gke-cluster-2"
        }
      },
      "etag": "8mBC7IJJFvY40k-rBabOOaGR6sSRG3dP6pI-frTuu9Y",
      "clusterState": {
        "agonesVersionInstalled": "1.15.0",
        "kubernetesVersionInstalled": "1.18.20-gke.900",
        "installationState": "AGONES_KUBERNETES_VERSION_SUPPORTED",
        "provider": "gke"
      }
    }
  ]
}

Go

To learn how to install and use the client library for Game Servers, see 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),
		View:   gamingpb.GameServerClusterView_FULL,
	}

	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)
		fmt.Fprintf(w, "Cluster installed Agones version: %v\n", resp.ClusterState.AgonesVersionInstalled)
		fmt.Fprintf(w, "Cluster installed Kubernetes version: %v\n", resp.ClusterState.KubernetesVersionInstalled)
		fmt.Fprintf(w, "Cluster installation state: %v\n", resp.ClusterState.InstallationState)
	}

	return nil
}

Java

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


import com.google.cloud.gaming.v1.GameServerCluster;
import com.google.cloud.gaming.v1.GameServerClusterView;
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.cloud.gaming.v1.RealmName;
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()) {
      ListGameServerClustersRequest request =
          ListGameServerClustersRequest.newBuilder()
              .setParent(RealmName.of(projectId, regionId, realmId).toString())
              .setView(GameServerClusterView.FULL)
              .build();
      ListGameServerClustersPagedResponse response = client.listGameServerClusters(request);
      for (GameServerCluster cluster : response.iterateAll()) {
        System.out.println("Game Server Cluster found: " + cluster.getName());
        System.out.println(
            "Cluster installed Agones version: "
                + cluster.getClusterState().getAgonesVersionInstalled());
        System.out.println(
            "Cluster installed Kubernetes version: "
                + cluster.getClusterState().getKubernetesVersionInstalled());
        System.out.println(
            "Cluster installation state: " + cluster.getClusterState().getInstallationState());
      }

      while (!Strings.isNullOrEmpty(response.getNextPageToken())) {
        ListGameServerClustersRequest request2 =
            ListGameServerClustersRequest.newBuilder()
                .setParent(RealmName.of(projectId, regionId, realmId).toString())
                .setPageToken(response.getNextPageToken())
                .build();
        response = client.listGameServerClusters(request2);
        for (GameServerCluster cluster : response.iterateAll()) {
          System.out.println("Game Server Cluster found: " + cluster.getName());
          System.out.println(
              "Cluster installed Agones version: "
                  + cluster.getClusterState().getAgonesVersionInstalled());
          System.out.println(
              "Cluster installed Kubernetes version: "
                  + cluster.getClusterState().getKubernetesVersionInstalled());
          System.out.println(
              "Cluster installation state: " + cluster.getClusterState().getInstallationState());
        }
      }
    }
  }
}

Node.js

To learn how to install and use the client library for Game Servers, see 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),
    view: 'FULL',
  };

  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(
      `\tCluster installed Agones version: ${cluster.clusterState.agonesVersionInstalled}`
    );
    console.log(
      `\tCluster installed Kubernetes version: ${cluster.clusterState.kubernetesVersionInstalled}`
    );
    console.log(
      `\tCluster installation state: ${cluster.clusterState.installationState}`
    );
    console.log(
      `\tGKE cluster: ${cluster.connectionInfo.gkeClusterReference.cluster}`
    );
  }
}

listGameServerClusters();

Python

To learn how to install and use the client library for Game Servers, see 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

Console

  1. In the Cloud Console, go to the Realms & Clusters page.

    Go to Game Servers

  2. Expand a realm to see the game server clusters that belong to it.

  3. In the last table column for the realm, click the ellipses and select View details.

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.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_ID: your Google Cloud project ID listed in the IAM Settings
  • REALM_LOCATION: the region for the realm or global
  • REALM_ID: the user-defined identifier for the realm
  • GS_CLUSTER_ID: the user-defined identifier for the cluster

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_ID/locations/REALM_LOCATION/realms/REALM_ID/gameServerClusters/GS_CLUSTER_ID",
  "createTime": CREATE_TIME,
  "updateTime": UPDATE_TIME,
  "connectionInfo": {
    "namespace": "default",
    "gkeClusterReference": {
      "cluster": "projects/PROJECT_ID/locations/GKE_CLUSTER_LOCATION/clusters/MY_GKE_CLUSTER"
    }
  },
  "etag": "8mBC7IJJFvY40k-rBabOOaGR6sSRG3dP6pI-frTuu9Y",
  "clusterState": {
    "agonesVersionInstalled": "1.15.0",
    "kubernetesVersionInstalled": "1.18.20-gke.900",
    "installationState": "AGONES_KUBERNETES_VERSION_SUPPORTED",
    "provider": "gke"
  }
}

Go

To learn how to install and use the client library for Game Servers, see 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),
		View: gamingpb.GameServerClusterView_FULL,
	}

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

	fmt.Fprintf(w, "Cluster retrieved: %v\n", resp.Name)
	fmt.Fprintf(w, "Cluster installed Agones version: %v\n", resp.ClusterState.AgonesVersionInstalled)
	fmt.Fprintf(w, "Cluster installed Kubernetes version: %v\n", resp.ClusterState.KubernetesVersionInstalled)
	fmt.Fprintf(w, "Cluster installation state: %v\n", resp.ClusterState.InstallationState)
	return nil
}

Java

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


import com.google.cloud.gaming.v1.GameServerCluster;
import com.google.cloud.gaming.v1.GameServerClusterName;
import com.google.cloud.gaming.v1.GameServerClusterView;
import com.google.cloud.gaming.v1.GameServerClustersServiceClient;
import com.google.cloud.gaming.v1.GetGameServerClusterRequest;
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()) {
      GetGameServerClusterRequest request =
          GetGameServerClusterRequest.newBuilder()
              .setName(GameServerClusterName.of(projectId, regionId, realmId, clusterId).toString())
              .setView(GameServerClusterView.FULL)
              .build();
      GameServerCluster cluster = client.getGameServerCluster(request);

      System.out.println("Game Server Cluster found: " + cluster.getName());
      System.out.println(
          "Cluster installed Agones version: "
              + cluster.getClusterState().getAgonesVersionInstalled());
      System.out.println(
          "Cluster installed Kubernetes version: "
              + cluster.getClusterState().getKubernetesVersionInstalled());
      System.out.println(
          "Cluster installation state: " + cluster.getClusterState().getInstallationState());
    }
  }
}

Node.js

To learn how to install and use the client library for Game Servers, see 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
    ),
    view: 'FULL',
  };

  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(
    `\tCluster installed Agones version: ${cluster.clusterState.agonesVersionInstalled}`
  );
  console.log(
    `\tCluster installed Kubernetes version: ${cluster.clusterState.kubernetesVersionInstalled}`
  );
  console.log(
    `\tCluster installation state: ${cluster.clusterState.installationState}`
  );
  console.log(
    `\tGKE cluster: ${cluster.connectionInfo.gkeClusterReference.cluster}`
  );
}

getGameServerCluster();

Python

To learn how to install and use the client library for Game Servers, see 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.