Creazione di un deployment

In questa pagina viene spiegato come creare, elencare, descrivere e aggiornare i deployment di Game Servers. Un deployment gestisce una o più versioni software che puoi distribuire in una o tutte le reami. Per visualizzare un esempio end-to-end di come creare un deployment, aggiungere una configurazione e poi implementarla, vedi Configurazione del comportamento di scalabilità del cluster.

Prima di iniziare

Prima di iniziare, ti consigliamo di familiarizzare con i concetti principali nella panoramica dei server di gioco. Assicurati di aver eseguito anche le seguenti attività:

  • Assicurati di aver attivato l'API Game Services.
  • Abilita l'API Game Services
  • Scegli una shell con gcloud CLI installato o utilizza un client API:
  • Cloud Shell

    Per avviare Cloud Shell, esegui questi passaggi:

    1. Vai a Google Cloud Console.

      Google Cloud console

    2. Nell'angolo in alto a destra della console, fai clic sul pulsante Attiva Cloud Shell:

    Una sessione di Cloud Shell si apre all'interno di un frame inferiore nella console. Puoi utilizzare questa shell per eseguire comandi gcloud.

    Profilo locale

    Installa l'interfaccia a riga di comando gcloud.

    Verifica di avere impostato il progetto predefinito desiderato per l'interfaccia a riga di comando di Google Cloud, altrimenti dovrai specificare esplicitamente il flag --project per ogni comando in un secondo momento:

    gcloud config list project
    

    In caso contrario, puoi eseguire il comando seguente per impostare un progetto predefinito, sostituendo PROJECT_ID con l'ID progetto desiderato :

    gcloud config set project PROJECT_ID
    

    Esegui questo comando per verificare la tua versione dell'interfaccia a riga di comando di Google Cloud. Game Servers richiede la versione 306.0.0 o successiva dell'interfaccia a riga di comando gcloud.

    gcloud version
    

    Per aggiornare l'installazione, esegui questo comando:

    gcloud components update
    

    curl / PowerShell

    Per utilizzare l'API REST con curl o Windows PowerShell, procedi come segue:

    1. Creare un account di servizio.
    2. Scarica una chiave privata come file JSON.
    3. Imposta la variabile di ambiente GOOGLE_APPLICATION_CREDENTIALS sul percorso del file JSON che contiene la chiave dell'account di servizio. Questa variabile si applica solo alla sessione shell corrente, quindi se apri una nuova sessione, impostala di nuovo.

    Libreria client

    I server di gioco Google Cloud possono essere controllati a livello di programmazione mediante una libreria client. Consulta la Panoramica sulle librerie client per istruzioni sull'utilizzo della libreria e sull'autenticazione.

Creazione di un deployment

console

  1. In Google Cloud Console, vai alla pagina Deployment di giochi per server.

    Vai a Game Servers

  2. Fai clic su Create Deployment (Crea deployment).

  3. Nella casella Nome, inserisci un identificatore univoco per il deployment.

  4. (Facoltativo) Nella casella Descrizione, inserisci una descrizione per il deployment.

  5. Fai clic su Crea.

gcloud

Puoi creare un deployment utilizzando l'interfaccia a riga di comando di Google Cloud.

Per creare un deployment, esegui questo comando e sostituisci deploymentID con un valore appropriato:

gcloud game servers deployments create deploymentID

REST &CMD LINE

Prima di utilizzare uno qualsiasi dei dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: il tuo ID progetto Google Cloud elencato nelle impostazioni IAM
  • DEPLOYMENT_ID: un identificatore definito dall'utente per il deployment

Corpo JSON richiesta:

{
  "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/DEPLOYMENT_ID",
}

Per inviare la richiesta, espandi una delle seguenti opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

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

C#

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Gaming.V1;
using Google.LongRunning;
using System.Threading.Tasks;

public class CreateDeploymentSample
{
    public async Task<GameServerDeployment> CreateDeploymentAsync(
        string projectId, string deploymentId)
    {
        // Create the client.
        GameServerDeploymentsServiceClient client = await GameServerDeploymentsServiceClient.CreateAsync();

        GameServerDeployment deployment = new GameServerDeployment()
        {
            GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment(projectId, "global", deploymentId)
        };
        CreateGameServerDeploymentRequest request = new CreateGameServerDeploymentRequest
        {
            DeploymentId = deploymentId,
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, "global"),
            GameServerDeployment = deployment
        };

        // Make the request.
        Operation<GameServerDeployment, OperationMetadata> response = await client.CreateGameServerDeploymentAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

Go

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


import (
	"context"
	"fmt"
	"io"

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

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

	// Location is hard coded as global, as Game Server Deployments can only be
	// created in global.  This is done for all operations on Game Server
	// Deployments, as well as for its child resource types.
	req := &gamingpb.CreateGameServerDeploymentRequest{
		Parent:       fmt.Sprintf("projects/%s/locations/global", projectID),
		DeploymentId: deploymentID,
		GameServerDeployment: &gamingpb.GameServerDeployment{
			Description: "My Game Server Deployment",
		},
	}

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

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

Java

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.gaming.v1.CreateGameServerDeploymentRequest;
import com.google.cloud.gaming.v1.GameServerDeployment;
import com.google.cloud.gaming.v1.GameServerDeploymentsServiceClient;
import com.google.cloud.gaming.v1.OperationMetadata;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDeployment {
  public static void createGameServerDeployment(String projectId, String deploymentId)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // String projectId = "your-project-id";
    // String deploymentId = "your-game-server-deployment-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 (GameServerDeploymentsServiceClient client = GameServerDeploymentsServiceClient.create()) {

      // Build a spec as shown at https://agones.dev/site/docs/reference/gameserver/
      JsonObject container = new JsonObject();
      container.addProperty("name", "default");
      container.addProperty("image", "gcr.io/agones-images/default:1.0");

      JsonArray containers = new JsonArray();
      containers.add(container);

      JsonObject spec = new JsonObject();
      spec.add("containers", containers);

      JsonObject template = new JsonObject();
      template.add("spec", spec);

      JsonObject port = new JsonObject();
      port.addProperty("name", "default");

      JsonArray ports = new JsonArray();
      ports.add(port);

      JsonObject specObject = new JsonObject();
      specObject.add("ports", ports);
      specObject.add("template", template);

      String parent = String.format("projects/%s/locations/global", projectId);
      String deploymentName = String.format("%s/gameServerDeployments/%s", parent, deploymentId);

      GameServerDeployment gameServerDeployment =
          GameServerDeployment.newBuilder().setName(deploymentName).build();

      CreateGameServerDeploymentRequest request =
          CreateGameServerDeploymentRequest.newBuilder()
              .setParent(parent)
              .setDeploymentId(deploymentId)
              .setGameServerDeployment(gameServerDeployment)
              .build();

      OperationFuture<GameServerDeployment, OperationMetadata> call =
          client.createGameServerDeploymentAsync(request);

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

Node.js

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.

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

const client = new GameServerDeploymentsServiceClient();

async function createGameServerDeployment() {
  /**
   * 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: `projects/${projectId}/locations/global`,
    deploymentId: deploymentId,
    gameServerDeployment: {
      description: 'nodejs test deployment',
    },
  };

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

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

createGameServerDeployment();

Python

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.

def create_deployment(project_id, deployment_id):
    """Creates a game server deployment."""

    client = gaming.GameServerDeploymentsServiceClient()

    # Location is hard coded as global, as game server deployments can
    # only be created in global.  This is done for all operations on
    # game server deployments, as well as for its child resource types.
    request = game_server_deployments.CreateGameServerDeploymentRequest(
        parent=f"projects/{project_id}/locations/global",
        deployment_id=deployment_id,
        game_server_deployment=game_server_deployments.GameServerDeployment(
            description="My Game Server Deployment"
        ),
    )

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

Deployment delle schede

console

  1. In Google Cloud Console, vai alla pagina Deployment di giochi per server.

    Vai a Game Servers

  2. Puoi utilizzare la casella di filtro per filtrare l'elenco dei deployment in base alle diverse proprietà.

gcloud

Puoi elencare i deployment utilizzando l'interfaccia a riga di comando di Google Cloud.

Per elencare i deployment, esegui questo comando:

gcloud game servers deployments list

REST &CMD LINE

Prima di utilizzare uno qualsiasi dei dati della richiesta, effettua le seguenti sostituzioni:

Per inviare la richiesta, espandi una delle seguenti opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "gameServerDeployments": [
    {
      "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/my-deployment-1",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "etag": "RI8hTm3ZaMNZ3qRVeKVcxcN3W26_oR559JYofnFi69A"
    },
    {
      "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/my-deployment-2",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "etag": "az38kwIY4X3WdP2SA0fkTGib9hwVj7iXLFXAtIzMLpc"
    }
  ]
}

C#

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Gaming.V1;
using System.Collections.Generic;
using System.Linq;

public class ListDeploymentsSample
{
    public IList<GameServerDeployment> ListDeployments(
        string projectId)
    {
        // Create the client.
        GameServerDeploymentsServiceClient client = GameServerDeploymentsServiceClient.Create();

        ListGameServerDeploymentsRequest request = new ListGameServerDeploymentsRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, "global")
        };

        // Make the request.
        PagedEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = client.ListGameServerDeployments(request);

        // The returned sequence will lazily perform RPCs as it's being iterated over.
        return response.ToList();
    }
}

Go

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


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

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

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

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

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

	return nil
}

Java

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


import com.google.cloud.gaming.v1.GameServerDeployment;
import com.google.cloud.gaming.v1.GameServerDeploymentsServiceClient;
import com.google.cloud.gaming.v1.GameServerDeploymentsServiceClient.ListGameServerDeploymentsPagedResponse;
import com.google.cloud.gaming.v1.ListGameServerDeploymentsRequest;
import com.google.common.base.Strings;
import java.io.IOException;

public class ListDeployments {
  public static void listGameServerDeployments(String projectId) throws IOException {
    // String projectId = "your-project-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 (GameServerDeploymentsServiceClient client = GameServerDeploymentsServiceClient.create()) {
      String parent = String.format("projects/%s/locations/global", projectId);

      ListGameServerDeploymentsPagedResponse response = client.listGameServerDeployments(parent);
      for (GameServerDeployment deployment : response.iterateAll()) {
        System.out.println("Game Server Deployment found: " + deployment.getName());
      }

      while (!Strings.isNullOrEmpty(response.getNextPageToken())) {
        ListGameServerDeploymentsRequest request =
            ListGameServerDeploymentsRequest.newBuilder()
                .setParent(parent)
                .setPageToken(response.getNextPageToken())
                .build();
        response = client.listGameServerDeployments(request);
        for (GameServerDeployment deployment : response.iterateAll()) {
          System.out.println("Game Server Deployment found: " + deployment.getName());
        }
      }
    }
  }
}

Node.js

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.

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

const client = new GameServerDeploymentsServiceClient();

async function listGameServerDeployments() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  const request = {
    parent: `projects/${projectId}/locations/global`,
  };

  const [results] = await client.listGameServerDeployments(request);
  for (const deployment of results) {
    console.log(`Deployment name: ${deployment.name}`);
    console.log(`Deployment description: ${deployment.description}`);

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

listGameServerDeployments();

Python

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.

def list_deployments(project_id):
    """Lists the existing game server deployments."""

    client = gaming.GameServerDeploymentsServiceClient()

    # Location is hard coded as global, as game server deployments can
    # only be created in global.  This is done for all operations on
    # game server deployments, as well as for its child resource types.
    response = client.list_game_server_deployments(
        parent=f"projects/{project_id}/locations/global"
    )

    for deployment in response.game_server_deployments:
        print(f"Name: {deployment.name}")

    return response.game_server_deployments

Descrizione di un deployment

console

  1. In Google Cloud Console, vai alla pagina Deployment di giochi per server.

    Vai a Game Servers

  2. Puoi utilizzare la casella di filtro per filtrare l'elenco dei deployment in base alle diverse proprietà.

  3. Nell'ultima colonna della tabella, fai clic sui tre puntini () e seleziona List configs (Configura configurazioni). Da questa pagina puoi visualizzare le configurazioni attive e inattive del deployment.

  4. Per creare una nuova configurazione per il deployment, fai clic su Create Config (Crea configurazione). Per aggiornare l'implementazione, fai clic su Gestisci implementazione.

gcloud

Puoi ottenere dettagli su un deployment, ad esempio l'ora di creazione o l'ora di aggiornamento, utilizzando l'interfaccia a riga di comando di Google Cloud.

Per descrivere un deployment, esegui il comando seguente e sostituisci deploymentID con l'identificatore di un deployment creato in precedenza:

gcloud game servers deployments describe deploymentID

REST &CMD LINE

Prima di utilizzare uno qualsiasi dei dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: il tuo ID progetto Google Cloud elencato nelle impostazioni IAM
  • DEPLOYMENT_ID: l'identificatore definito dall'utente per il deployment

Per inviare la richiesta, espandi una delle seguenti opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/DEPLOYMENT_ID",
  "createTime": CREATE_TIME,
  "updateTime": UPDATE_TIME,
  "etag": "RI8hTm3ZaMNZ3qRVeKVcxcN3W26_oR559JYofnFi69A"
}

C#

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


using Google.Cloud.Gaming.V1;

public class GetDeploymentSample
{
    public GameServerDeployment GetDeployment(
        string projectId, string deploymentId)
    {
        // Create the client.
        GameServerDeploymentsServiceClient client = GameServerDeploymentsServiceClient.Create();

        GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest
        {
            GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment(projectId, "global", deploymentId)
        };

        // Make the request.
        GameServerDeployment response = client.GetGameServerDeployment(request);
        return response;
    }
}

Go

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

Java

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


import com.google.cloud.gaming.v1.GameServerDeployment;
import com.google.cloud.gaming.v1.GameServerDeploymentsServiceClient;
import java.io.IOException;

public class GetDeployment {
  public static void getGameServerDeployment(String projectId, String deploymentId)
      throws IOException {
    // String projectId = "your-project-id";
    // String deploymentId = "your-game-server-deployment-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 (GameServerDeploymentsServiceClient client = GameServerDeploymentsServiceClient.create()) {
      String deploymentName =
          String.format(
              "projects/%s/locations/global/gameServerDeployments/%s", projectId, deploymentId);

      GameServerDeployment deployment = client.getGameServerDeployment(deploymentName);

      System.out.println("Game Server Deployment found: " + deployment.getName());
    }
  }
}

Node.js

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.

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

const client = new GameServerDeploymentsServiceClient();

async function getGameServerDeployment() {
  /**
   * 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 = {
    // The full resource name
    name: client.gameServerDeploymentPath(projectId, 'global', deploymentId),
  };

  const [deployment] = await client.getGameServerDeployment(request);
  console.log(`Deployment name: ${deployment.name}`);
  console.log(`Deployment description: ${deployment.description}`);

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

getGameServerDeployment();

Python

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.

def get_deployment(project_id, deployment_id):
    """Gets a game server deployment."""

    client = gaming.GameServerDeploymentsServiceClient()

    # Location is hard coded as global, as game server deployments can
    # only be created in global.  This is done for all operations on
    # game server deployments, as well as for its child resource types.
    request = game_server_deployments.GetGameServerDeploymentRequest(
        name=f"projects/{project_id}/locations/global/gameServerDeployments/{deployment_id}",
    )

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

Aggiornamento di un deployment

gcloud

Per aggiornare un campo per un deployment, esegui il comando gcloud game servers deployments update dopo aver sostituito deploymentID per un deployment esistente. Il comando seguente aggiorna il campo della descrizione di un deployment.

gcloud game servers deployments update deploymentID --description="My updated description"

Per trovare i flag per altri campi del deployment, consulta la documentazione di riferimento di gcloud.

REST &CMD LINE

L'esempio seguente aggiorna il campo description. Per aggiornare altri campi, aggiungi i nomi dei campi al parametro di ricerca ?updateMask= e richiedi il corpo JSON.

Prima di utilizzare uno qualsiasi dei dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: il tuo ID progetto Google Cloud elencato nelle impostazioni IAM
  • DEPLOYMENT_ID: l'identificatore definito dall'utente per il deployment

Corpo JSON richiesta:

{
  "description": "My updated description"
}

Per inviare la richiesta, espandi una delle seguenti opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/PROJECT_ID/locations/global/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.gaming.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_ID/locations/global/gameServerDeployments/DEPLOYMENT_ID",
    "verb": "update",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

C#

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


using Google.Cloud.Gaming.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class UpdateDeploymentSample
{
    public async Task<GameServerDeployment> UpdateDeploymentAsync(
        string projectId, string deploymentId)
    {
        // Create the client.
        GameServerDeploymentsServiceClient client = await GameServerDeploymentsServiceClient.CreateAsync();

        GameServerDeployment deployment = new GameServerDeployment
        {
            GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment(projectId, "global", deploymentId)
        };
        deployment.Labels.Add("label-key-1", "label-value-1");
        deployment.Labels.Add("label-key-2", "label-value-2");

        UpdateGameServerDeploymentRequest request = new UpdateGameServerDeploymentRequest
        {
            GameServerDeployment = deployment,
            UpdateMask = new FieldMask { Paths = { "labels" } }
        };

        // Make the request.
        Operation<GameServerDeployment, OperationMetadata> response = await client.UpdateGameServerDeploymentAsync(request);
        Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result. This result will NOT contain the updated labels.
        // If you want to get the updated resource, use a GET request on the resource.
        return completedResponse.Result;
    }
}

Go

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


import (
	"context"
	"fmt"
	"io"

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

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

	req := &gamingpb.UpdateGameServerDeploymentRequest{
		GameServerDeployment: &gamingpb.GameServerDeployment{
			Name:        fmt.Sprintf("projects/%s/locations/global/gameServerDeployments/%s", projectID, deploymentID),
			Description: "My Updated Game Server Deployment",
			Labels: map[string]string{
				"label-key-1": "label-value-1",
			},
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"description", "labels",
			},
		},
	}

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

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

Java

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.gaming.v1.GameServerDeployment;
import com.google.cloud.gaming.v1.GameServerDeploymentsServiceClient;
import com.google.cloud.gaming.v1.OperationMetadata;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateDeployment {
  public static void updateGameServerDeployment(String projectId, String deploymentId)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // String projectId = "your-project-id";
    // String deploymentId = "your-game-server-deployment-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 (GameServerDeploymentsServiceClient client = GameServerDeploymentsServiceClient.create()) {
      String deploymentName =
          String.format(
              "projects/%s/locations/global/gameServerDeployments/%s", projectId, deploymentId);

      GameServerDeployment deployment =
          GameServerDeployment.newBuilder()
              .setName(deploymentName)
              .putLabels("key", "value")
              .build();

      FieldMask fieldMask = FieldMask.newBuilder().addPaths("labels").build();

      OperationFuture<GameServerDeployment, OperationMetadata> call =
          client.updateGameServerDeploymentAsync(deployment, fieldMask);

      GameServerDeployment updated = call.get(1, TimeUnit.MINUTES);
      System.out.println("Game Server Deployment updated: " + updated.getName());
    }
  }
}

Node.js

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.

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

const client = new GameServerDeploymentsServiceClient();

async function updateGameServerDeployment() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const deploymentId = 'The unique ID for the Game Server Deployment';
  const request = {
    gameServerDeployment: {
      name: client.gameServerDeploymentPath(
        projectId,
        'global',
        deploymentId
      ),
      labels: {
        'label-key-1': 'label-value-1',
      },
      description: 'My updated Game Server deployment',
    },
    updateMask: {
      paths: ['labels', 'description'],
    },
  };

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

  console.log(`Deployment updated: ${result.name}`);
}

updateGameServerDeployment();

Python

Per informazioni su come installare e utilizzare la libreria client per Game Servers, consulta la sezione Librerie client di Game Servers.

def update_deployment(project_id, deployment_id):
    """Updates a game server deployment."""

    client = gaming.GameServerDeploymentsServiceClient()

    # Location is hard coded as global, as game server deployments can
    # only be created in global.  This is done for all operations on
    # game server deployments, as well as for its child resource types.
    request = game_server_deployments.UpdateGameServerDeploymentRequest(
        game_server_deployment=game_server_deployments.GameServerDeployment(
            name=f"projects/{project_id}/locations/global/gameServerDeployments/{deployment_id}",
            labels={"label-key-1": "label-value-1", "label-key-2": "label-value-2"},
        ),
        update_mask=field_mask.FieldMask(paths=["labels"]),
    )

    operation = client.update_game_server_deployment(request)
    print(f"Update deployment operation: {operation.operation.name}")
    operation.result(timeout=120)

Passaggi successivi