Creating and Managing Service Accounts

This page explains how to create and manage service accounts using the Cloud Identity and Access Management API, the Google Cloud Platform Console, and the gcloud command-line tool.

When you create a new Cloud project, Google Cloud Platform (GCP) automatically creates one Compute Engine service account and one App Engine service account under that project. You can create up to 98 additional service accounts to your project to control access to your resources.

Before you begin

Required permissions

To allow a user to manage service accounts, grant one of the following roles:

  • Service Account User (roles/iam.serviceAccountUser): Grants permissions to get, list, or impersonate a service account.
  • Service Account Admin (roles/iam.serviceAccountAdmin): Includes Service Account User permissions and also grants permissions to create, update, delete, and set or get the Cloud IAM policy on a service account.

Cloud IAM primitive roles also contain permissions to manage service accounts. However, we recommend granting one of the predefined roles above to prevent unnecessary access to other GCP resources.

See the Service Account Roles topic for more information about roles related to service accounts.

Creating a service account

Creating a service account is similar to adding a member to your project, but the service account belongs to your applications rather than an individual end user.

In the examples below, [SA-NAME] is the name of the service account. This is a unique identifier; it will appear in the service account's email address, and you'll use it to update the service account with other APIs. It cannot be changed once created. [SA-DISPLAY-NAME] is a friendly name for the service account. [PROJECT-ID] is the ID of your Google Cloud Platform project.

To create a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor primitive role (roles/editor).

Console

  1. Open the Service Accounts page in the GCP Console.

    Open the Service Accounts page

  2. Click Select a project.

  3. Select your project and click Open.
  4. Click Create Service Account.
  5. Enter a service account name, select a role you wish to grant to the service account, and then click Save.

GCLOUD COMMAND

Execute the gcloud iam service-accounts create command to create a service account.

Command:

gcloud iam service-accounts create [SA-NAME]
    --display-name "[SA-DISPLAY-NAME]"

The output is the service account:

Created service account [SA-NAME].

REST API

Call serviceAccounts.create() to create a service account.

POST https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts

The request body should contain the properties for the service account.

{
    "accountId": "[SA-NAME]",
    "serviceAccount": {
        "displayName": "[SA-DISPLAY-NAME]",
    }
}

Response:

{
    "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
    "projectId": "PROJECT-ID",
    "uniqueId": "113948692397867021414",
    "email": "SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
    "displayName": "SA-DISPLAY-NAME",
    "etag": "BwUp3rVlzes=",
    "oauth2ClientId": "117249000288840666939"
}

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM C# API reference documentation .

public static ServiceAccount CreateServiceAccount(string projectId,
    string name, string displayName)
{
    var request = new CreateServiceAccountRequest
    {
        AccountId = name,
        ServiceAccount = new ServiceAccount
        {
            DisplayName = displayName
        }
    };

    ServiceAccount serviceAccount = s_iam.Projects.ServiceAccounts
        .Create(request, "projects/" + projectId).Execute();

    Console.WriteLine("Created service account: " + serviceAccount.Email);
    return serviceAccount;
}

Java

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Java API reference documentation .

public ServiceAccount createServiceAccount(String projectId, String name, String displayName)
    throws IOException {

  ServiceAccount serviceAccount = new ServiceAccount();
  serviceAccount.setDisplayName(displayName);
  CreateServiceAccountRequest request = new CreateServiceAccountRequest();
  request.setAccountId(name);
  request.setServiceAccount(serviceAccount);

  serviceAccount =
      service.projects().serviceAccounts().create("projects/" + projectId, request).execute();

  System.out.println("Created service account: " + serviceAccount.getEmail());
  return serviceAccount;
}

Python

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Python API reference documentation .

def create_service_account(project_id, name, display_name):
    """Creates a service account."""

    # pylint: disable=no-member
    service_account = service.projects().serviceAccounts().create(
        name='projects/' + project_id,
        body={
            'accountId': name,
            'serviceAccount': {
                'displayName': display_name
            }
        }).execute()

    print('Created service account: ' + service_account['email'])
    return service_account

After you create a service account, grant one or more roles to the service account so that it can act on your behalf.

Listing service accounts

When listing service accounts, you can specify parameters to limit the number of service accounts to include in the response. You can then use ListServiceAccountsResponse.next_page_token in a subsequent request to list the remaining service accounts.

Use this method to audit service accounts and keys, or to build custom tools for managing service accounts.

To list service accounts, at minimum the user must be granted the Service Account User role (roles/iam.serviceAccountUser) or the Viewer primitive role (roles/viewer).

Console

  1. Open the Service Accounts page in the GCP Console.

    Open the Service Accounts page

  2. Click Select a project.

  3. Select your project and click Open. All service accounts are listed in the Service Accounts page.

GCLOUD COMMAND

Execute the gcloud iam service-accounts list command to list all service accounts in a project.

Command:

gcloud iam service-accounts list

The output is the list of all service accounts in the project:

NAME                    EMAIL
SA-DISPLAY-NAME-1       SA-NAME-1@PROJECT-ID.iam.gserviceaccount.com
SA-DISPLAY-NAME-2       SA-NAME-2@PROJECT-ID.iam.gserviceaccount.com

REST API

Call the serviceAccounts.list() method.

Request:

GET https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts

Response:

{
    "accounts": [
    {
        "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME-1@PROJECT-ID.iam.gserviceaccount.com",
        "projectId": "PROJECT-ID",
        "uniqueId": "108979773878059201436",
        "email": "SA-NAME-1@PROJECT-ID.iam.gserviceaccount.com",
        "displayName": "SA-DISPLAY-NAME-1",
        "etag": "BwUpTsLVUkQ=",
        "oauth2ClientId": "102240834887833340852"
    },
    {
        "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME-2@PROJECT-ID.iam.gserviceaccount.com",
        "projectId": "PROJECT-ID",
        "uniqueId": "108979773878059201436",
        "email": "SA-NAME-2@PROJECT-ID.iam.gserviceaccount.com",
        "displayName": "SA-DISPLAY-NAME-2",
        "etag": "BwUpTsLVUkQ=",
        "oauth2ClientId": "102240834887833340852"
    }]
}

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM C# API reference documentation .

public static IList<ServiceAccount> ListServiceAccounts(string projectId)
{
    ListServiceAccountsResponse response = s_iam.Projects.ServiceAccounts
        .List("projects/" + projectId).Execute();
    IList<ServiceAccount> serviceAccounts = response.Accounts;

    foreach (ServiceAccount account in serviceAccounts)
    {
        Console.WriteLine("Name: " + account.Name);
        Console.WriteLine("Display Name: " + account.DisplayName);
        Console.WriteLine("Email: " + account.Email);
        Console.WriteLine();
    }
    return serviceAccounts;
}

Java

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Java API reference documentation .

public List<ServiceAccount> listServiceAccounts(String projectId) throws IOException {

  ListServiceAccountsResponse response =
      service.projects().serviceAccounts().list("projects/" + projectId).execute();
  List<ServiceAccount> serviceAccounts = response.getAccounts();

  for (ServiceAccount account : serviceAccounts) {
    System.out.println("Name: " + account.getName());
    System.out.println("Display Name: " + account.getDisplayName());
    System.out.println("Email: " + account.getEmail());
    System.out.println();
  }
  return serviceAccounts;
}

Python

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Python API reference documentation .

def list_service_accounts(project_id):
    """Lists all service accounts for the current project."""

    # pylint: disable=no-member
    service_accounts = service.projects().serviceAccounts().list(
        name='projects/' + project_id).execute()

    for account in service_accounts['accounts']:
        print('Name: ' + account['name'])
        print('Email: ' + account['email'])
        print(' ')
    return service_accounts

Renaming a service account

The display name of a service account is commonly used to capture additional information about the service account, such as the purpose of the service account or a contact person for the account.

To rename a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor primitive role (roles/editor).

Console

  1. Open the Service Accounts page in the GCP Console.

    Open the Service Accounts page

  2. Click Select a project.
  3. Select your project and click Open.
  4. Look for the service account you wish to rename, click the More more_vert button in that row, and then click Edit.
  5. Enter the new name and click Save.

GCLOUD COMMAND

Execute the gcloud iam service-accounts update command to update a service account.

Command:

gcloud iam service-accounts update
    [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com
    --display-name "[UPDATED-DISPLAY-NAME]"

The output is the renamed service account:

displayName: Updated display name
email: SA-NAME@PROJECT-ID.iam.gserviceaccount.com
etag: BwUqQpHDCw8=
name: projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com
oauth2ClientId: '112984177383228986143'
projectId: PROJECT-ID
uniqueId: '112984177383228986143'

REST API

Us the serviceAccounts.update() method.

Request:

PUT https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts/[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com

The request body must contain the new display name, the project ID, the unique ID of the service account, and the service account email.

{
    "displayName":"[UPDATED-DISPLAY-NAME]",
    "etag":"BwUpVKjgNtE=",
    "projectId":"[PROJECT-ID]",
    "uniqueId":"107522985251862639552",
    "email":"[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com",
}

Response:

{
    "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
    "projectId": "PROJECT-ID",
    "uniqueId": "107522985251862639552",
    "email": "SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
    "displayName": "Updated display name",
    "etag": "BwUqLK4bL9U=",
    "oauth2ClientId": "105236325228757713905"
}

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM C# API reference documentation .

public static ServiceAccount RenameServiceAccount(string email,
    string newDisplayName)
{
    // First, get a ServiceAccount using List() or Get()
    string resource = "projects/-/serviceAccounts/" + email;
    ServiceAccount serviceAccount = s_iam.Projects.ServiceAccounts
        .Get(resource).Execute();

    // Then you can update the display name
    serviceAccount.DisplayName = newDisplayName;
    serviceAccount = s_iam.Projects.ServiceAccounts.Update(
        serviceAccount, resource).Execute();

    Console.WriteLine($"Updated display name for {serviceAccount.Email} " +
        "to: " + serviceAccount.DisplayName);
    return serviceAccount;
}

Java

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Java API reference documentation .

public ServiceAccount renameServiceAccount(String email, String newDisplayName)
    throws IOException {

  // First, get a service account using List() or Get()
  ServiceAccount serviceAccount =
      service.projects().serviceAccounts().get("projects/-/serviceAccounts/" + email).execute();

  // Then you can update the display name
  serviceAccount.setDisplayName(newDisplayName);
  service.projects().serviceAccounts().update(serviceAccount.getName(), serviceAccount).execute();

  System.out.println(
      "Updated display name for " + serviceAccount.getName() + " to: " + newDisplayName);
  return serviceAccount;
}

Python

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Python API reference documentation .

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

    # First, get a service account using List() or Get()
    resource = 'projects/-/serviceAccounts/' + email
    # pylint: disable=no-member
    service_account = service.projects().serviceAccounts().get(
        name=resource).execute()

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

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

Deleting a service account

When you delete a service account, applications will no longer have access to Google Cloud Platform resources through that service account. If you delete the default App Engine and Compute Engine service accounts, the instances will no longer have access to resources in the project.

Delete with caution; make sure your critical applications no longer use a service account before deleting it. Additionally, role bindings for a deleted service account are not immediately removed; they are automatically purged from the system after a maximum of 60 days.

To delete a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor primitive role (roles/editor).

Console

  1. Open the Service Accounts page in the GCP Console.

    Open the Service Accounts page

  2. Click Select a project.

  3. Select your project and click Open.
  4. Select the service account(s) you wish to delete, and then click Delete delete.

GCLOUD COMMAND

Execute the gcloud iam service-accounts delete command to delete a service account.

Command:

gcloud iam service-accounts delete
  [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com

Output:

Deleted service account SA-NAME@PROJECT-ID.iam.gserviceaccount.com

REST API

Use the serviceAccounts.delete() method.

DELETE https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts/[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM C# API reference documentation .

public static void DeleteServiceAccount(string email)
{
    string resource = "projects/-/serviceAccounts/" + email;
    s_iam.Projects.ServiceAccounts.Delete(resource).Execute();

    Console.WriteLine("Deleted service account: " + email);
}

Java

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Java API reference documentation .

public void deleteServiceAccount(String email) throws IOException {

  service.projects().serviceAccounts().delete("projects/-/serviceAccounts/" + email).execute();

  System.out.println("Deleted service account: " + email);
}

Python

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Python API reference documentation .

def delete_service_account(email):
    """Deletes a service account."""

    # pylint: disable=no-member
    service.projects().serviceAccounts().delete(
        name='projects/-/serviceAccounts/' + email).execute()

    print('Deleted service account: ' + email)

After deleting a service account, avoid creating a new service account with the same name. This can result in unexpected behavior. For more information, see Deleting and recreating service accounts.

Next steps

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Identity and Access Management Documentation