Creating a config

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

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.

Creating a config

Make sure you have created a Game Servers deployment.

gcloud

You can create a Game Servers config in a deployment using the gcloud command-line tool.

To create a game server config:

  1. Copy this fleet specification into a file.

    - name: fleet-spec-1
      fleetSpec:
       replicas: 10
       scheduling: Packed
       strategy:
         type: RollingUpdate
         rollingUpdate:
           maxSurge: 25%
           maxUnavailable: 25%
       template:
         metadata:
           labels:
             gameName: udp-server
         spec:
           ports:
           - name: default
             portPolicy: Dynamic
             containerPort: 7654
             protocol: UDP
           health:
             initialDelaySeconds: 30
             periodSeconds: 60
           sdkServer:
             logLevel: Info
             grpcPort: 9357
             httpPort: 9358
           template:
             spec:
               containers:
               - name: dedicated
                 image: gcr.io/agones-images/udp-server:0.21
                 imagePullPolicy: Always
                 resources:
                   requests:
                     memory: 200Mi
                     cpu: 500m
                   limits:
                     memory: 200Mi
                     cpu: 500m
    
  2. Run the following command and replace the placeholder values, such as deploymentID and configID, with appropriate values:

    gcloud game servers configs create configID --deployment deploymentID --fleet-configs-file fleetSpecFile
    

    The variable placeholders correspond to the following descriptions:

  • configID is a unique identifier that you can specify for this config.
  • deploymentID is the unique identifier for the deployment.
  • fleetSpecFile is the path to the file with the Agones Fleet specification.

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"
)

// fleet is the spec portion of an agones Fleet.  It must be in JSON format.
// See https://agones.dev/site/docs/reference/fleet/ for more on fleets.
const fleet = `
{
   "replicas": 10,
   "scheduling": "Packed",
   "strategy": {
      "type": "RollingUpdate",
      "rollingUpdate": {
         "maxSurge": "25%",
         "maxUnavailable": "25%"
      }
   },
   "template": {
      "metadata": {
         "labels": {
            "gameName": "udp-server"
         }
      },
      "spec": {
         "ports": [
            {
               "name": "default",
               "portPolicy": "Dynamic",
               "containerPort": 2156,
               "protocol": "TCP"
            }
         ],
         "health": {
            "initialDelaySeconds": 30,
            "periodSeconds": 60
         },
         "sdkServer": {
            "logLevel": "Info",
            "grpcPort": 9357,
            "httpPort": 9358
         },
         "template": {
            "spec": {
               "containers": [
                  {
                     "name": "dedicated",
                     "image": "gcr.io/agones-images/udp-server:0.17",
                     "imagePullPolicy": "Always",
                     "resources": {
                        "requests": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        },
                        "limits": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
`

// createGameServerConfig creates a game server config.
func createGameServerConfig(w io.Writer, projectID, deploymentID, configID string) error {
	// projectID := "my-project"
	// deploymentID := "mydeployment"
	// configID := "mydeployment"
	ctx := context.Background()
	client, err := gaming.NewGameServerConfigsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerConfigsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.CreateGameServerConfigRequest{
		Parent:   fmt.Sprintf("projects/%s/locations/global/gameServerDeployments/%s", projectID, deploymentID),
		ConfigId: configID,
		GameServerConfig: &gamingpb.GameServerConfig{
			FleetConfigs: []*gamingpb.FleetConfig{
				&gamingpb.FleetConfig{
					Name:      "fleet-spec-1",
					FleetSpec: fleet,
				},
			},
			Description: "My Game Server Config",
		},
	}

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

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

Node.js

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

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

  const client = new GameServerConfigsServiceClient();

  async function createGameServerConfig() {
    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'Your Google Cloud Project ID';
    // const deploymentId = 'A unique ID for the Game Server Deployment';
    // const configId = 'A unique ID for the Game Server Config';
    // const fleetName = 'The fleet name to be stored in Agones';
    // fleet is the spec portion of an agones Fleet.  It must be in JSON format.
    // See https://agones.dev/site/docs/reference/fleet/ for more on fleets.
    const fleet = `
{
   "replicas": 10,
   "scheduling": "Packed",
   "strategy": {
      "type": "RollingUpdate",
      "rollingUpdate": {
         "maxSurge": "25%",
         "maxUnavailable": "25%"
      }
   },
   "template": {
      "metadata": {
         "labels": {
            "gameName": "udp-server"
         }
      },
      "spec": {
         "ports": [
            {
               "name": "default",
               "portPolicy": "Dynamic",
               "containerPort": 2156,
               "protocol": "TCP"
            }
         ],
         "health": {
            "initialDelaySeconds": 30,
            "periodSeconds": 60
         },
         "sdkServer": {
            "logLevel": "Info",
            "grpcPort": 9357,
            "httpPort": 9358
         },
         "template": {
            "spec": {
               "containers": [
                  {
                     "name": "dedicated",
                     "image": "gcr.io/agones-images/udp-server:0.17",
                     "imagePullPolicy": "Always",
                     "resources": {
                        "requests": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        },
                        "limits": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
`;
    const request = {
      parent: client.gameServerDeploymentPath(
        projectId,
        'global',
        deploymentId
      ),
      configId: configId,
      gameServerConfig: {
        fleetConfigs: [
          {
            name: fleetName,
            fleetSpec: fleet,
          },
        ],
        description: 'nodejs test config',
      },
    };

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

    console.log('Game Server Config created:');
    console.log(`\t Config name: ${result.name}`);
    console.log(`\t Config description: ${result.description}`);
  }

  createGameServerConfig();

Python

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


# FLEET_SPEC is the spec portion of an agones Fleet.  It must be in JSON format.
# See https://agones.dev/site/docs/reference/fleet/ for more on fleets.
FLEET_SPEC = """
{
   "replicas": 10,
   "scheduling": "Packed",
   "strategy": {
      "type": "RollingUpdate",
      "rollingUpdate": {
         "maxSurge": "25%",
         "maxUnavailable": "25%"
      }
   },
   "template": {
      "metadata": {
         "labels": {
            "gameName": "udp-server"
         }
      },
      "spec": {
         "ports": [
            {
               "name": "default",
               "portPolicy": "Dynamic",
               "containerPort": 2156,
               "protocol": "TCP"
            }
         ],
         "health": {
            "initialDelaySeconds": 30,
            "periodSeconds": 60
         },
         "sdkServer": {
            "logLevel": "Info",
            "grpcPort": 9357,
            "httpPort": 9358
         },
         "template": {
            "spec": {
               "containers": [
                  {
                     "name": "dedicated",
                     "image": "gcr.io/agones-images/udp-server:0.17",
                     "imagePullPolicy": "Always",
                     "resources": {
                        "requests": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        },
                        "limits": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
"""


def create_config(project_id, deployment_id, config_id):
    """Creates a game server config."""

    client = gaming.GameServerConfigsServiceClient()

    fleet_config = game_server_configs.FleetConfig(
        name="my-fleet-spec", fleet_spec=FLEET_SPEC,
    )

    # Location is hard coded as global, as game server configs can
    # only be created in global.  This is done for all operations on
    # game server configs.
    request = game_server_configs.CreateGameServerConfigRequest(
        parent=f"projects/{project_id}/locations/global/gameServerDeployments/{deployment_id}",
        config_id=config_id,
        game_server_config=game_server_configs.GameServerConfig(
            description="My Game Server Config", fleet_configs=[fleet_config],
        ),
    )

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

Listing configs

gcloud

You can list configs using the gcloud command-line tool.

To list all configs, run the following command:

gcloud game servers configs list

To list all configs in a deployment, run the following command and replace deploymentID with the parent deployment that you want to list the configs in:

gcloud game servers configs list --deployment=deploymentID

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"
)

// listGameServerConfigs lists the game server configs.
func listGameServerConfigs(w io.Writer, projectID, deploymentID string) error {
	// projectID := "my-project"
	// deploymentID := "mydeployment"
	ctx := context.Background()
	client, err := gaming.NewGameServerConfigsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerConfigsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.ListGameServerConfigsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global/gameServerDeployments/%s", projectID, deploymentID),
	}

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

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

	return nil
}

Node.js

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

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

const client = new GameServerConfigsServiceClient();

async function listGameServerConfigs() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const deploymentId = 'A unique ID for the Game Server Deployment';
  const request = {
    parent: client.gameServerDeploymentPath(
      projectId,
      'global',
      deploymentId
    ),
  };

  const [results] = await client.listGameServerConfigs(request);
  for (const config of results) {
    console.log(`Config name: ${config.name}`);
    console.log(`Config description: ${config.description}`);

    const createTime = config.createTime;
    const createDate = new Date(createTime.seconds * 1000);
    console.log(`Config created on: ${createDate.toLocaleDateString()}\n`);
  }
}

listGameServerConfigs();

Python

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

def list_configs(project_id, deployment_id):
    """Lists the existing game server deployments."""

    client = gaming.GameServerConfigsServiceClient()

    # Location is hard coded as global, as game server configs can
    # only be created in global.  This is done for all operations on
    # game server configs.
    response = client.list_game_server_configs(
        parent=f"projects/{project_id}/locations/global/gameServerDeployments/{deployment_id}"
    )

    for config in response.game_server_configs:
        print(f"Name: {config.name}")

    return response.game_server_configs

Viewing details about a config

gcloud

You can find details about a config, such as the creation time, using the gcloud command-line tool:

To view the details of a config, run the following command and replace the placeholder values, such as deploymentID and configID, with appropriate values:

gcloud game servers configs describe configID --deployment deploymentID

The output gives you the details of the config.

The variable placeholders correspond to the following descriptions:

  • configID is the unique identifier that you specified for this game server config.
  • deploymentID is a unique identifier for the parent deployment.

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"
)

// getGameServerConfig retrieves info on a game server config.
func getGameServerConfig(w io.Writer, projectID, deploymentID, configID string) error {
	// projectID := "my-project"
	// deploymentID := "mydeployment"
	// configID := "myconfig"
	ctx := context.Background()
	client, err := gaming.NewGameServerConfigsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerConfigsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.GetGameServerConfigRequest{
		Name: fmt.Sprintf("projects/%s/locations/global/gameServerDeployments/%s/configs/%s", projectID, deploymentID, configID),
	}

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

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

Node.js

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

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

const client = new GameServerConfigsServiceClient();

async function getGameServerConfig() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const deploymentId = 'A unique ID for the Game Server Deployment';
  // const configId = 'A unique ID for the Game Server Config';
  const request = {
    // The full resource name
    name: client.gameServerConfigPath(
      projectId,
      'global',
      deploymentId,
      configId
    ),
  };

  const [config] = await client.getGameServerConfig(request);
  console.log(`Config name: ${config.name}`);
  console.log(`Config description: ${config.description}`);

  const createTime = config.createTime;
  const createDate = new Date(createTime.seconds * 1000);
  console.log(`Config created on: ${createDate.toLocaleDateString()}\n`);
}

getGameServerConfig();

Python

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

def get_config(project_id, deployment_id, config_id):
    """Gets a game server config."""

    client = gaming.GameServerConfigsServiceClient()

    # Location is hard coded as global, as game server configs can
    # only be created in global.  This is done for all operations on
    # game server configs.
    request = game_server_configs.GetGameServerConfigRequest(
        name=f"projects/{project_id}/locations/global/gameServerDeployments/{deployment_id}/configs/{config_id}",
    )

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

What's next