Cambia el nombre de una cuenta de servicio

Se muestra cómo cambiar de nombre de una cuenta de servicio.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

C++

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM C++.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name, std::string const& display_name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::PatchServiceAccountRequest request;
  google::iam::admin::v1::ServiceAccount service_account;
  service_account.set_name(name);
  service_account.set_display_name(display_name);
  google::protobuf::FieldMask update_mask;
  *update_mask.add_paths() = "display_name";
  *request.mutable_service_account() = service_account;
  *request.mutable_update_mask() = update_mask;
  auto response = client.PatchServiceAccount(request);
  if (!response) throw std::move(response).status();
  std::cout << "ServiceAccount successfully updated: "
            << response->DebugString() << "\n";
}

C#

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM C#.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class ServiceAccounts
{
    public static ServiceAccount RenameServiceAccount(string email,
        string newDisplayName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        // First, get a ServiceAccount using List() or Get().
        string resource = "projects/-/serviceAccounts/" + email;
        var serviceAccount = service.Projects.ServiceAccounts.Get(resource)
            .Execute();
        // Then you can update the display name.
        serviceAccount.DisplayName = newDisplayName;
        serviceAccount = service.Projects.ServiceAccounts.Update(
            serviceAccount, resource).Execute();
        Console.WriteLine($"Updated display name for {serviceAccount.Email} " +
            "to: " + serviceAccount.DisplayName);
        return serviceAccount;
    }
}

Go

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Go.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// renameServiceAccount renames a service account.
func renameServiceAccount(w io.Writer, email, newDisplayName string) (*iam.ServiceAccount, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	// First, get a ServiceAccount using List() or Get().
	resource := "projects/-/serviceAccounts/" + email
	serviceAccount, err := service.Projects.ServiceAccounts.Get(resource).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Get: %w", err)
	}
	// Then you can update the display name.
	serviceAccount.DisplayName = newDisplayName
	serviceAccount, err = service.Projects.ServiceAccounts.Update(resource, serviceAccount).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Update: %w", err)
	}

	fmt.Fprintf(w, "Updated service account: %v", serviceAccount.Email)
	return serviceAccount, nil
}

Java

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Java.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.ServiceAccount;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class RenameServiceAccount {

  // Changes a service account's display name.
  public static void renameServiceAccount(String projectId, String serviceAccountName) {
    // String projectId = "my-project-id";
    // String serviceAccountName = "my-service-account-name";

    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return;
    }

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      // First, get a service account using List() or Get()
      ServiceAccount serviceAccount =
          service
              .projects()
              .serviceAccounts()
              .get("projects/-/serviceAccounts/" + serviceAccountEmail)
              .execute();

      // Then you can update the display name
      serviceAccount.setDisplayName("your-new-display-name");
      serviceAccount =
          service
              .projects()
              .serviceAccounts()
              .update(serviceAccount.getName(), serviceAccount)
              .execute();

      System.out.println(
          "Updated display name for "
              + serviceAccount.getName()
              + " to: "
              + serviceAccount.getDisplayName());
    } catch (IOException e) {
      System.out.println("Unable to rename service account: \n" + e.toString());
    }
  }

  private static Iam initService() throws GeneralSecurityException, IOException {
    // Use the Application Default Credentials strategy for authentication. For more info, see:
    // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Python.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import os

from google.oauth2 import service_account  # type: ignore
import googleapiclient.discovery  # type: ignore

def rename_service_account(email: str, new_display_name: str) -> dict:
    """Changes a service account's display name."""

    # First, get a service account using List() or Get()
    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )

    service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)

    resource = "projects/-/serviceAccounts/" + email

    my_service_account = (
        service.projects().serviceAccounts().get(name=resource).execute()
    )

    # Then you can update the display name
    my_service_account["displayName"] = new_display_name
    my_service_account = (
        service.projects()
        .serviceAccounts()
        .update(name=resource, body=my_service_account)
        .execute()
    )

    print(
        "Updated display name for {} to: {}".format(
            my_service_account["email"], my_service_account["displayName"]
        )
    )
    return my_service_account

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.