Habilita una clave de cuenta de servicio

Se muestra cómo habilitar una clave de cuenta de servicio de IAM inhabilitada.

Explora más

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

Muestra de código

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.EnableServiceAccountKeyRequest;
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 EnableServiceAccountKey {

  public static void main(String[] args) {
    // TODO(Developer): Replace the below variables before running.
    String projectId = "gcloud-project-id";
    String serviceAccountName = "service-account-name";
    String serviceAccountKeyName = "service-account-key-name";

    enableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);
  }

  // Enables a service account key.
  public static void enableServiceAccountKey(String projectId, String serviceAccountName,
      String serviceAccountKeyName) {
    // Initialize the IAM service.
    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e);
      return;
    }

    // Construct the service account email.
    // You can modify the ".iam.gserviceaccount.com" to match the service account name in which
    // you want to enable the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#enabling
    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";

    try {
      EnableServiceAccountKeyRequest
          enableServiceAccountKeyRequest = new EnableServiceAccountKeyRequest();
      // Use the IAM service to enable the service account key.
      service
          .projects()
          .serviceAccounts()
          .keys()
          .enable(String
              .format("projects/%s/serviceAccounts/%s/keys/%s", projectId, serviceAccountEmail,
                  serviceAccountKeyName), enableServiceAccountKeyRequest)
          .execute();

      System.out.println("Enabled service account key: " + serviceAccountKeyName);
    } catch (IOException e) {
      System.out.println("Failed to enable service account key: \n" + e);
    }
  }

  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.
    return new Iam.Builder(
        GoogleNetHttpTransport.newTrustedTransport(),
        GsonFactory.getDefaultInstance(),
        new HttpCredentialsAdapter(credential))
        .setApplicationName("service-accounts")
        .build();
  }
}

¿Qué sigue?

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