Dienstkonto erstellen

Zeigt das Erstellen eines Dienstkontos.

Weitere Informationen

Eine ausführliche Dokumentation, die dieses Codebeispiel enthält, finden Sie hier:

Codebeispiel

C++

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur C++ API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& project_id, std::string const& account_id,
   std::string const& display_name, std::string const& description) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::ServiceAccount service_account;
  service_account.set_display_name(display_name);
  service_account.set_description(description);
  auto response = client.CreateServiceAccount("projects/" + project_id,
                                              account_id, service_account);
  if (!response) throw std::move(response).status();
  std::cout << "ServiceAccount successfully created: "
            << response->DebugString() << "\n";
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur C# API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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 CreateServiceAccount(string projectId,
        string name, string displayName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new CreateServiceAccountRequest
        {
            AccountId = name,
            ServiceAccount = new ServiceAccount
            {
                DisplayName = displayName
            }
        };
        var serviceAccount = service.Projects.ServiceAccounts.Create(
            request, "projects/" + projectId).Execute();
        Console.WriteLine("Created service account: " + serviceAccount.Email);
        return serviceAccount;
    }
}

Go

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur Go API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"

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

// createServiceAccount creates a service account.
func createServiceAccount(w io.Writer, projectID, name, displayName string) (*iam.ServiceAccount, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	request := &iam.CreateServiceAccountRequest{
		AccountId: name,
		ServiceAccount: &iam.ServiceAccount{
			DisplayName: displayName,
		},
	}
	account, err := service.Projects.ServiceAccounts.Create("projects/"+projectID, request).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Create: %w", err)
	}
	fmt.Fprintf(w, "Created service account: %v", account)
	return account, nil
}

Java

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur Java API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.CreateServiceAccountRequest;
import com.google.iam.admin.v1.ProjectName;
import com.google.iam.admin.v1.ServiceAccount;
import java.io.IOException;

public class CreateServiceAccount {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    String projectId = "your-project-id";
    String serviceAccountName = "my-service-account-name";

    createServiceAccount(projectId, serviceAccountName);
  }

  // Creates a service account.
  public static ServiceAccount createServiceAccount(String projectId, String serviceAccountName)
          throws IOException {
    ServiceAccount serviceAccount = ServiceAccount
            .newBuilder()
            .setDisplayName("your-display-name")
            .build();
    CreateServiceAccountRequest request = CreateServiceAccountRequest.newBuilder()
            .setName(ProjectName.of(projectId).toString())
            .setAccountId(serviceAccountName)
            .setServiceAccount(serviceAccount)
            .build();
    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    try (IAMClient iamClient = IAMClient.create()) {
      serviceAccount = iamClient.createServiceAccount(request);
      System.out.println("Created service account: " + serviceAccount.getEmail());
    }
    return serviceAccount;
  }
}

Python

Informationen zum Installieren und Verwenden der Clientbibliothek für IAM finden Sie unter IAM-Clientbibliotheken. Weitere Informationen finden Sie in der IAM-Referenzdokumentation zur Python API.

Richten Sie zur Authentifizierung bei IAM die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import os

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

def create_service_account(project_id: str, name: str, display_name: str) -> dict:
    """Creates a service account."""

    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)

    my_service_account = (
        service.projects()
        .serviceAccounts()
        .create(
            name="projects/" + project_id,
            body={"accountId": name, "serviceAccount": {"displayName": display_name}},
        )
        .execute()
    )

    print("Created service account: " + my_service_account["email"])
    return my_service_account

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie im Google Cloud-Beispielbrowser.