Configure Workload Identity Federation with deployment pipelines

This guide describes how to use Workload Identity Federation to let deploymentpipelines authenticate to Google Cloud.

Depending on the CI/CD system you're using, your deployment pipelines might haveaccess to ambient, environment-specific credentials. For example:

  • Azure DevOps pipelines can use aMicrosoft Entra workload identity federation service connection to obtain an ID token that uniquely identifies the Azure DevOps project.
  • GitHub Actions workflows can obtain aGitHub OIDC token that uniquely identifies the workflow and its repository.
  • GitLab SaaS lets CI/CD jobs access anID token that uniquely identifies the job and its project, environment, and repository.
  • Terraform Cloud can provide anOIDC token to your your Terraform configuration that uniquely identifies the workspaceand environment.

You can configure your deployment pipelines to use these credentials to authenticate toGoogle Cloud by using Workload Identity Federation. This approacheliminates the maintenance and security burden associated withservice account keys.

Before you begin

Set up authentication

Select the tab for how you plan to use the samples on this page:

Console

When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

gcloud

In the Google Cloud console, activate Cloud Shell.

Activate Cloud Shell

At the bottom of the Google Cloud console, aCloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

Python

To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    Install the Google Cloud CLI.

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    If you're using a local shell, then create local authentication credentials for your user account:

    gcloudauthapplication-defaultlogin

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

Required roles

To get the permissions that you need to configure Workload Identity Federation, ask your administrator to grant you theWorkload Identity Pool Admin (roles/iam.workloadIdentityPoolAdmin) IAM role on the project. For more information about granting roles, seeManage access to projects, folders, and organizations.

You might also be able to get the required permissions throughcustom roles or otherpredefined roles.

Alternatively, the IAM Owner (roles/owner) basic role alsoincludes permissions to configure identity federation.You should not grant basic roles in a production environment, but you can grant them in adevelopment or test environment.

Prepare your external IdP

Azure DevOps

To let an Azure DevOps pipeline authenticate to Google Cloud, you firstconfigure a service connection for Azure Resource Manager. This connectionlets the pipeline obtain an ID token, which it can then exchange forGoogle Cloud credentials.

To create a service connection for Azure Resource Manager, do the following:

  1. In Azure DevOps, open your project and go toProject Settings.
  2. Go toPipelines> Service connections.
  3. ClickCreate service connection.
  4. SelectAzure Resource Manager.
  5. ClickNext.
  6. Configure the following settings:

    • Identity type:App registration (automatic)
    • Credential:Workload identity federation
    • Scope level:Subscription.

      You must select a subscription even if you're not planning to usethe service connection to access Azure resources.

    • Service connection name: Enter a name such asgoogle-cloud.

  7. ClickSave.

In a later step, you'll need the issuer and subject identifier of theservice connection. To look up these details, do the following:

  1. Click the service connection you just created.
  2. ClickManage App registration.
  3. SelectManage> Certificate & secrets> Federated credentials.
  4. Click the federated credential.
  5. On theEdit a credential page, find the following identifiers:

    • Issuer: uniquely identifies your Azure DevOps organization
    • Subject identifier: uniquely identifies the service connection

Azure DevOps automatically grants access on the subscription that you selectedas scope to the service principal associated with your new service connection.Because you're not planning to use the service connection to access Azureresources, you can revoke this access by doing the following:

  1. In the Azure portal, open the subscription that you selected as scope.
  2. Go toAccess control (IAM)> Role assignments.
  3. Find the role assignment for the service connection and remove it.

GitHub Actions

You don't need to make any configuration changes in your GitHub account.

After youconfigure a workload identity pool to trust yourGitHub repository, you can let workflows in that repository use theirGitHub OIDC token to obtain short-lived Google Cloud credentials.

GitLab SaaS

You don't need to make any configuration changes in your GitLab account.

After youconfigure a workload identity pool to trustyour GitLab group, you can enable Workload Identity Federation for individualCI/CD jobs.

Terraform Cloud

You don't need to make any configuration changes in your Terraform Cloud account.

After youconfigure a workload identity pool to trustTerraform Cloud, you can enable Workload Identity Federation for individualworkspaces.

Configure Workload Identity Federation

You must perform these steps for each GitHub organization, GitLab group,or Terraform Cloud organization.

To start configuring Workload Identity Federation, do the following:

    In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.

    Go to project selector

    It's best touse a dedicated project to manage workload identity pools and providers.

    Verify that billing is enabled for your Google Cloud project.

    Enable the IAM, Resource Manager, Service Account Credentials, and Security Token Service APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the APIs

Define an attribute mapping

The environment-specific credentials of your deployment pipeline can contain multiple attributes,and you must decide which attribute you want to use as subject identifier(google.subject) in Google Cloud.

Optionally, you canmap additional attributes.You can then refer to these additional attributes when you grant access toresources.

Azure DevOps

The Azure DevOps ID token includes asub claim that contains the subjectidentifier of your service connection. The subject identifier uses thefollowing format:

sc://ORGANIZATION/PROJECT/CONNECTION

Use the following attribute mapping to map this identifier togoogle.subject:

google.subject=assertion.sub

GitHub Actions

Your attribute mappings can use any of theclaims in the GitHub ActionsOIDC token. These token claim keys and their values are controlled byGitHub. At minimum, you should mapgoogle.subject toassertion.sub,which corresponds to the GitHub Actions OIDC token subject:

google.subject=assertion.sub

The value for the GitHub Actions OIDC token subjectcan vary depending on thesourceevent. Other claim attributes can include:

  • repository: Contains the owner and repository name–for example"google/guava".

  • repository_id: Contains the unique repository ID–for example"20300177".

  • repository_owner: Contains the owner, which can be a username or thename of a GitHub organization–for example"google".

  • repository_owner_id: Contains the unique owner ID–for example"1342004".

This list is a subset of the possible claims–see the GitHubdocumentation onexampleclaims for a complete list. Be sure to map any claims that youplan to use as attribute conditions or as part of a futureprincipalSetcondition.

Important: Using "name" fields likerepository andrepository_ownerincreases the chances ofcybersquatting andtyposquatting attacks. If you delete your GitHub repository or GitHub organization,someone may be able to claim that samename and establish anidentity. To protect against this situation, use the numeric*_id fieldsinstead, which are unique and can't be reused.

GitLab SaaS

Your attribute mappings can use theclaims embedded in the GitLab ID token as source attributes, including the following:

  • sub: the project name and Git reference—for example,project_path:groupname/projectname:ref_type:branch:ref:main.
  • namespace_id: the unique group ID.
  • project_id: the unique project ID.
  • user_id: the unique user ID.
  • environment: the environment that the job applies to.
  • ref_path: the Git reference—for examplerefs/heads/main.

The following attribute mapping setsgoogle.subject to thesub claimfrom the GitLab ID token. Because thesub claim containsboth the project name and Git reference, this mapping lets you control accessby repository and branch:

google.subject=assertion.sub

Controlling access by repository and branch can be useful if certain branches(for example,main) need different access to resources than otherbranches (for example, feature branches).

In some cases, it might be sufficient to only differentiate access by projector group. The following mapping therefore includes two additional attributesthat contain the GitLabproject_id andnamespace_id:

google.subject=assertion.subattribute.project_id=assertion.project_idattribute.namespace_id=assertion.namespace_id

Terraform Cloud

Your attribute mappings can use the claims embedded in the Terraform CloudOIDC token, including the following

  • terraform_organization_id: Contains the unique ID of the organization—forexampleorg-xxxxxxxxxxxxxxxx.
  • terraform_workspace_id: Contains theunique ID of the workspace—forexamplews-xxxxxxxxxxxxxxxx.
  • terraform_workspace_name: Contains thedisplay name of the workspace.
  • sub: Contains the display name of the organization, workspace, and phase—forexampleorganization:example-org:workspace:example-workspace:run_phase:apply.

The following attribute mapping setsgoogle.subject to theterraform_workspace_idclaim from the Terraform Cloud OIDC token:

google.subject=assertion.terraform_workspace_id

This mapping lets you control access to Google Cloud resources by workspace.

Define an attribute condition

Attribute conditions areCEL expressions that can check assertion attributes and target attributes. Ifthe attribute condition evaluates totrue for a given credential, thecredential is accepted. Otherwise, the credential is rejected. You must have anattribute mapping for all attribute condition fields.

Warning: GitHub, GitLab SaaS, and Terraform Cloud use a single issuer URL acrossall organizations and some of the claims embedded in OIDC tokens might notbe unique to your organization. To help protect againstspoofing threats,you must use an attribute condition that restricts access to tokens issued by yourGitHub organization, GitLab group, or Terraform Cloud organization.

Azure DevOps

Optionally, use an attribute condition to restrict access tocertain service connections. For example, the following condition limitsaccess to connections in a certain Azure DevOps project:

assertion.sub.startsWith('sc://ORGANIZATION/PROJECT/')

Replace the following:

  • ORGANIZATION: the name of your Azure DevOps organization.
  • PROJECT: the name of your Azure DevOps project.

GitHub Actions

Use the following attribute condition to restrict access to tokens issued by yourGitHub organization:

assertion.repository_owner=='ORGANIZATION'

ReplaceORGANIZATION with the name of your GitHuborganization.

Optionally, extend the attribute condition to restrict access to a subset of workflowsor branches. For example, the following condition limits accessto workflows that use the Git branchmain:

assertion.repository_owner=='ORGANIZATION' && assertion.ref=='refs/heads/main'

GitLab SaaS

Use the following attribute condition to restrict access to tokens issued by yourGitLabgroup

assertion.namespace_id=='GROUP_ID'

ReplaceGROUP_ID with the group ID that's shown onyour GitLab group's home page.

Optionally, extend the attribute condition to restrict access to a subset ofprojects, branches, or environments. For example, the following condition limits accessto jobs that use the environmentproduction:

assertion.namespace_id=='GROUP_ID' && assertion.environment=='production'

Terraform Cloud

Use the following attribute condition to restrict access to tokens issued by yourTerraform Cloud organization:

assertion.terraform_organization_id=='ORGANIZATION_ID'

ReplaceORGANIZATION_ID with the unique ID of yourorganization—for exampleorg-xxxxxxxxxxxxxxxx.Optionally, extend the attribute condition to restrict access to a subset of workflowsor branches. For example, the following attribute condition limits accessto a specific workspace:

assertion.terraform_organization_id=='ORGANIZATION_ID' && assertion.terraform_workspace_id=='WORKSPACE_ID'

Create the workload identity pool and provider

You've now collected all the information you need to create a workload identitypool and provider:

Console

  1. In the Google Cloud console, go to theNew workload provider and poolpage.

    Go to New workload provider and pool

  2. UnderCreate an identity pool, enter the following:

    • Name: Name for the pool. The name is also used as the pool ID.You can't change the pool ID later.
    • Description: Text that describes the purpose of the pool.
  3. ClickContinue.

  4. Configure provider settings:

    Azure DevOps

    • Select a provider:OpenID Connect (OIDC).
    • Provider name: the name of the Azure DevOps project, or acustom name.
    • Provider ID: the name of the Azure DevOps project, or acustom ID. You cannot change the provider ID later.
    • Issuer URL: the service connection issuer thatyou've looked up previously.
    • Audiences: SelectAllowed audiences and paste the following value

      api://AzureADTokenExchange

    GitHub Actions

    • Select a provider:OpenID Connect (OIDC).
    • Provider name: Name for the provider.
    • Provider ID: ID for the provider. You cannot change the provider ID later.
    • Issuer URL:https://token.actions.githubusercontent.com/
    • Audiences:Default audience

    GitLab SaaS

    • Select a provider:OpenID Connect (OIDC).
    • Provider name: Name for the provider.
    • Provider ID: ID for the provider. You cannot change the provider ID later.
    • Issuer URL:https://gitlab.com
    • Audiences:Default audience

    Terraform Cloud

    • Select a provider:OpenID Connect (OIDC).
    • Provider name: Name for the provider.
    • Provider ID: ID for the provider. You cannot change the provider ID later.
    • Issuer URL:https://app.terraform.io
    • Audiences:Default audience
  5. ClickContinue.

  6. UnderConfigure provider attributes, addtheattribute mappings that you've identified previously.

  7. UnderAttribute conditions, enter theattribute condition that you've identified previously.

  8. ClickSave to create the workload identity pool and provider.

gcloud

  1. Create a new workload identity pool:

    gcloud iam workload-identity-pools createPOOL_ID \    --location="global" \    --description="DESCRIPTION" \    --display-name="DISPLAY_NAME"

    Replace the following values:

    • POOL_ID: the unique ID for the pool
    • DISPLAY_NAME: the name of the pool
    • DESCRIPTION: the description of the pool. This descriptionappears when granting access to pool identities
  2. Add a workload identity pool provider:

    Azure DevOps

    gcloud iam workload-identity-pools providers create-oidcPROVIDER_ID \    --location="global" \    --workload-identity-pool="POOL_ID" \    --issuer-uri="ISSUER" \    --allowed-audiences="api://AzureADTokenExchange" \    --attribute-mapping="MAPPINGS" \    --attribute-condition="CONDITIONS"

    Replace the following values:

    GitHub Actions

    gcloud iam workload-identity-pools providers create-oidcPROVIDER_ID \    --location="global" \    --workload-identity-pool="POOL_ID" \    --issuer-uri="https://token.actions.githubusercontent.com/" \    --attribute-mapping="MAPPINGS" \    --attribute-condition="CONDITIONS"

    Replace the following values:

    GitLab SaaS

    gcloud iam workload-identity-pools providers create-oidcPROVIDER_ID \    --location="global" \    --workload-identity-pool="POOL_ID" \    --issuer-uri="https://gitlab.com" \    --attribute-mapping="MAPPINGS" \    --attribute-condition="CONDITIONS"

    Replace the following values:

    Terraform Cloud

    gcloud iam workload-identity-pools providers create-oidcPROVIDER_ID \    --location="global" \    --workload-identity-pool="POOL_ID" \    --issuer-uri="https://app.terraform.io" \    --attribute-mapping="MAPPINGS" \    --attribute-condition="CONDITIONS"

    Replace the following values:

Note: The prefixgcp- is reserved and can't be used in a pool or provider ID.

Update attribute condition on a workload identity provider

This section describes how you can update the attribute condition on an existingworkload identity pool provider to restrict access to tokens issued by yourGitHub organization, GitLab group, or Terraform Cloud organization.

To find the recommended attribute condition for your pipeline, seeDefine an attribute condition.

Console

  1. In the Google Cloud console, go to theWorkload Identity Poolspage.

    Go to Workload Identity Pools

  2. Find the workload identity pool that contains the provider, and then click theExpand node icon for thepool.

  3. Find the workload identity pool provider that you want to edit and clickEdit.

  4. InAttribute conditions, enter theattribute condition that you've identified previously.

  5. To update the workload identity pool and provider, clickSave.

gcloud

To update the workload identity pool provider, run the following command:

gcloud iam workload-identity-pools providers update-oidcPROVIDER_ID \    --location="global" \    --workload-identity-pool="POOL_ID" \    --attribute-condition="CONDITIONS"

Replace the following values:

Authenticate a deployment pipeline

You must perform these steps for each GitHub Actions workflow or TerraformCloud workspace.

Allow your external workload to access Google Cloud resources

To complete the instructions later in this guide, you must configure serviceaccount impersonation as described in this section.

To provide your workload with access to Google Cloud resources, werecommend that you grant direct resource access to the principal. In this case,the principal is the federated user. Some Google Cloud products haveGoogle Cloud API limitations.If your workload calls an API endpoint that has a limitation, you can insteaduse service account impersonation. In this case, the principal is theGoogle Cloud service account, which acts as the identity. You grant accessto the service account on the resource.

Direct resource access

You can grant access to a federated identity directly on resources by usingthe Google Cloud console or the gcloud CLI.

Console

To use the Google Cloud console to grant IAM rolesdirectly on a resource, you must go to the resource's page, and thengrant the role. The following example shows you how to goto the Cloud Storage page and grant the role Storage Object Viewer(roles/storage.objectViewer) to a federated identity directly on aCloud Storage bucket.

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket for which youwant to grant the role.

  3. Select thePermissions tab near the top of the page.

  4. Click theGrant access button.

    TheAdd principals dialog appears.

  5. In theNew principals field, enter one or more identitiesthat need access to your bucket.

    By subject

    principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT

    Replace the following:

    • PROJECT_NUMBER: the projectnumber
    • POOL_ID: the workloadpool ID
    • SUBJECT: the individualsubject mapped from your IdP—for example,administrator@example.com

    By group

    principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/group/GROUP

    Replace the following:

    • PROJECT_NUMBER: the projectnumber
    • WORKLOAD_POOL_ID: the workloadpool ID
    • GROUP: the groupmapped from your IdP—for example:administrator-group@example.com

    By attribute

    principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE

    Replace the following:

    • PROJECT_NUMBER: the projectnumber
    • WORKLOAD_POOL_ID: the workloadpool ID
    • ATTRIBUTE_NAME: one of theattributes that was mapped from your IdP
    • ATTRIBUTE_VALUE: the valueof the attribute
  6. Select a role (or roles) from theSelect a role drop-down menu.The roles you select appear in the pane with a short description ofthe permissions they grant.

  7. ClickSave.

gcloud

To use the gcloud CLI to grant IAM roles on aresource in a project, do the following:

  1. Obtain the project number of the project in which the resourceis defined.

    gcloud projects describe $(gcloud config get-value core/project) --format=value\(projectNumber\)
  2. Grant access to the resource.

    To use the gcloud CLI to grant the role Storage Object Viewer (roles/storage.objectViewer) to external identities that meet certain criteria, run the following command.

    By subject

    gcloud storage buckets add-iam-policy-bindingBUCKET_ID \    --role=roles/storage.objectViewer \    --member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT"

    By group

    gcloud storage buckets add-iam-policy-bindingBUCKET_ID \    --role=roles/storage.objectViewer \    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/group/GROUP"

    By attribute

    gcloud storage buckets add-iam-policy-bindingBUCKET_ID \    --role=roles/storage.objectViewer \    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE"

    Replace the following:

    • BUCKET_ID:the bucket on which to grant access
    • PROJECT_NUMBER: theproject number.of the project that contains the workload identity pool
    • POOL_ID: the pool ID of the workload identity pool
    • SUBJECT: the expected value for the attribute thatyou've mappedtogoogle.subject
    • GROUP: the expected value for the attribute thatyou've mappedtogoogle.groups
    • ATTRIBUTE_NAME: the name of a custom attribute inyour attribute mapping
    • ATTRIBUTE_VALUE: the value of the custom attribute in your attribute mapping

    You can grant roles on any Google Cloud resource that supportsIAM allow policies.

    Note: You must use the project number, not the project ID, in themember identifier.

Service account impersonation

  1. To create a service account for the external workload, do the following:

    1. Enable the IAM, Security Token Service, and Service Account Credentials APIs.

      Roles required to enable APIs

      To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

      Enable the APIs

    2. Create a service accountthat represents the workload. We recommend that youuse a dedicated service account for each workload.The service account doesn't need to be in the same project as theworkload identity pool, but you must refer to the project thatcontains the service account.

    3. Grant the service account accessto resources that you want external identities to access.

  2. To let the federated identity impersonate the service account, do thefollowing:

Console

To use the Google Cloud console to grant IAM rolesto a federated identity with service account, do the following:

Service Account in the same project

  1. To grant access using service account impersonation for aservice account in the same project, do the following:

    1. Go to theWorkload Identity Pools page.

      Go to Workload Identity Pools

    2. SelectGrant access.

    3. In theGrant access to service account dialog, selectGrant access using Service Account impersonation.

    4. In theService accounts list, select theservice account for the external identities to impersonate,and do the following:

    5. To choose which identities in the pool can impersonate theservice account, perform one of the following actions:

      • To allow only specific identities of the workloadidentity pool to impersonate the service account, selectOnly identities matching the filter.

      • In theAttribute name list, select the attributethat you want to filter on.

      • In theAttribute value field, enter the expectedvalue of the attribute; for example, if you use anattribute mappinggoogle.subject=assertion.sub, setAttribute name tosubject andAttribute valueto the value of thesub claim in tokens that areissued by your external identity provider.

    6. To save the configuration, clickSave and thenDismiss.

Service account in a different project

Note: Service accounts from different projects won't appear in the"CONNECTED SERVICE ACCOUNTS" section of yourWorkload Identity Pool.
  1. To grant access using service account impersonation for aservice account in a different project, do the following:

    1. Go to theService Accounts page.

      Go to Service Accounts

    2. Select the service account that you want to impersonate.

    3. ClickManage access.

    4. ClickAdd principal.

    5. In theNew principal field, enter one of the followingprincipal identifiersfor the identities in your pool that will impersonate theservice account.

      By subject

      principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT

      Replace the following:

      • PROJECT_NUMBER: the projectnumber
      • POOL_ID: the workloadpool ID
      • SUBJECT: the individualsubject mapped from your IdP—for example,administrator@example.com

      By group

      principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/group/GROUP

      Replace the following:

      • PROJECT_NUMBER: the projectnumber
      • WORKLOAD_POOL_ID: the workloadpool ID
      • GROUP: the groupmapped from your IdP—for example:administrator-group@example.com

      By attribute

      principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE

      Replace the following:

      • PROJECT_NUMBER: the projectnumber
      • WORKLOAD_POOL_ID: the workloadpool ID
      • ATTRIBUTE_NAME: one of theattributes that was mapped from your IdP
      • ATTRIBUTE_VALUE: the valueof the attribute

      By pool

      principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/*

      Replace the following:

      • PROJECT_NUMBER: the projectnumber
      • WORKLOAD_POOL_ID: the workloadpool ID
    6. InSelect a role, select the Workload Identity Userrole (roles/iam.workloadIdentityUser).

    7. To save the configuration, clickSave.

gcloud

To grant the Workload Identity User role (roles/iam.workloadIdentityUser) to a federated principal or principal set, run the following command. To learn more about Workload Identity Federation principal identifiers, seePrincipal types.

By subject

gcloud iam service-accounts add-iam-policy-bindingSERVICE_ACCOUNT_EMAIL \    --role=roles/iam.workloadIdentityUser \    --member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT"

By group

gcloud iam service-accounts add-iam-policy-bindingSERVICE_ACCOUNT_EMAIL \    --role=roles/iam.workloadIdentityUser \    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/group/GROUP"

By attribute

gcloud iam service-accounts add-iam-policy-bindingSERVICE_ACCOUNT_EMAIL \    --role=roles/iam.workloadIdentityUser \    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE"

Replace the following:

  • SERVICE_ACCOUNT_EMAIL:the email address of the service account
  • PROJECT_NUMBER: theproject number.of the project that contains the workload identity pool
  • POOL_ID: the pool ID of the workload identity pool
  • SUBJECT: the expected value for the attribute thatyou've mappedtogoogle.subject
  • GROUP: the expected value for the attribute thatyou've mappedtogoogle.groups
  • ATTRIBUTE_NAME: the name of a custom attribute inyour attribute mapping
  • ATTRIBUTE_VALUE: the value of the custom attribute in your attribute mapping

Note: You must use the project number, not the project ID, in themember identifier.

Configure the deployment pipeline

This section describes how to use Workload Identity Federation in yourdeployment pipeline. The instructions in this section assume that your workloadsuseservice account impersonation to access Google Cloudresources.

Azure DevOps

Edit yourazure-pipelines.yml file and add the following to yourjob configuration:

variables:- name: Azure.WorkloadIdentity.Connection  value:CONNECTION- name: GoogleCloud.WorkloadIdentity.ProjectNumber  value:PROJECT_NUMBER- name: GoogleCloud.WorkloadIdentity.Pool  value:POOL_ID- name: GoogleCloud.WorkloadIdentity.Provider  value:PROVIDER_ID- name: GoogleCloud.WorkloadIdentity.ServiceAccount  value:SERVICE_ACCOUNT_EMAIL- name: GOOGLE_APPLICATION_CREDENTIALS  value: $(Pipeline.Workspace)/.workload_identity.wlconfigsteps:  - task: AzureCLI@2    inputs:      connectedServiceNameARM: $(Azure.WorkloadIdentity.Connection)      addSpnToEnvironment: true      scriptType: 'bash'      scriptLocation: 'inlineScript'      inlineScript: |        echo $idToken > $(Pipeline.Workspace)/.workload_identity.jwt        cat<< EOF > $GOOGLE_APPLICATION_CREDENTIALS        {          "type": "external_account",          "audience": "//iam.googleapis.com/projects/$(GoogleCloud.WorkloadIdentity.ProjectNumber)/locations/global/workloadIdentityPools/$(GoogleCloud.WorkloadIdentity.Pool)/providers/$(GoogleCloud.WorkloadIdentity.Provider)",          "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",          "token_url": "https://sts.REGION.rep.googleapis.com/v1/token",          "credential_source": {            "file": "$(Pipeline.Workspace)/.workload_identity.jwt"          },          "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/$(GoogleCloud.WorkloadIdentity.ServiceAccount):generateAccessToken"        }        EOF

Replace the following values:

  • CONNECTION: The name of your service connection.
  • PROJECT_NUMBER: The project number of the projectthat contains the workload identity pool.
  • POOL_ID: The ID of the workload identity pool.
  • PROVIDER_ID: The ID of the workload identitypool provider.
  • SERVICE_ACCOUNT_EMAIL: The email address of theservice account, if you use service account impersonation. If you usedirect resource access, omitGoogleCloud.WorkloadIdentity.ServiceAccount andservice_account_impersonation_url.
  • REGION: A region forregional STS endpoints,if they are available. If regional endpoints aren't available, you canuse https://sts.googleapis.com/v1/token.

The configuration does the following:

  1. Uses theAzureCLI taskto obtain an ID token for the service connection, and makes it availablein a variable namedidToken.
  2. Saves the ID token to a temporary file named.workload_identity.jwt.
  3. Creates a credential configuration file that instructs client librariesto read the ID token from.workload_identity.jwt and uses it to impersonatea service account.
  4. Sets the environment variableGOOGLE_APPLICATION_CREDENTIALS to pointto the credential configuration file.

GitHub Actions

Thegoogle-github-actions/auth action lets you automatically generate a credential configuration fileduring workflow execution. Client libraries and tools such asterraformcan then use this credential configuration file to automatically obtainGoogle credentials.

Edit your GitHub Actions YAML file and add the following:

  • Allow the job to fetch a GitHub ID token by adding the followingconfiguration:

    permissions:  id-token: write  contents: read
  • Add a step to create a credentials configuration file:

    - id: 'auth'  name: 'Authenticate to Google Cloud'  uses: 'google-github-actions/auth@v1'  with:    create_credentials_file: true    workload_identity_provider: 'projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID'    service_account: 'SERVICE_ACCOUNT_EMAIL'

Replace the following:

  • PROJECT_NUMBER: The project number of the project that contains the workload identity pool.
  • POOL_ID: The ID of the workload identity pool.
  • PROVIDER_ID: The ID of the workload identity pool provider.
  • SERVICE_ACCOUNT_EMAIL: The email address of the service account, if you use service account impersonation. If you use direct resource access, omitservice_account.

The following example configures the GitHub Action:

jobs:  build:    # Allow the job to fetch a GitHub ID token    permissions:      id-token: write      contents: read    runs-on: ubuntu-latest    steps:      - uses: actions/checkout@v3      - id: 'auth'        name: 'Authenticate to Google Cloud'        uses: 'google-github-actions/auth@v1'        with:          create_credentials_file: true          workload_identity_provider: 'projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID'          service_account: 'SERVICE_ACCOUNT_EMAIL'

For further details on using thegoogle-github-actions/auth action,seeSetting up Workload Identity Federation.

GitLab SaaS

Edit your.gitlab-ci.yml file and add the following to the jobconfiguration:

job:  variables:    WORKLOAD_IDENTITY_PROJECT_NUMBER:PROJECT_NUMBER    WORKLOAD_IDENTITY_POOL:POOL_ID    WORKLOAD_IDENTITY_PROVIDER:PROVIDER_ID    SERVICE_ACCOUNT:SERVICE_ACCOUNT_EMAIL    GOOGLE_APPLICATION_CREDENTIALS: $CI_BUILDS_DIR/.workload_identity.wlconfig  id_tokens:    WORKLOAD_IDENTITY_TOKEN:      aud: https://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID  script:    - |-      echo $WORKLOAD_IDENTITY_TOKEN > $CI_BUILDS_DIR/.workload_identity.jwt      cat<< EOF > $GOOGLE_APPLICATION_CREDENTIALS      {        "type": "external_account",        "audience": "//iam.googleapis.com/projects/$WORKLOAD_IDENTITY_PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_IDENTITY_POOL/providers/$WORKLOAD_IDENTITY_PROVIDER",        "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",        "token_url": "https://sts.REGION.rep.googleapis.com/v1/token",        "credential_source": {          "file": "$CI_BUILDS_DIR/.workload_identity.jwt"        },        "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/$SERVICE_ACCOUNT:generateAccessToken"      }      EOF

Replace the following values:

  • PROJECT_NUMBER: The project number of theproject that contains the workload identity pool.
  • POOL_ID: The ID of the workload identity pool.
  • PROVIDER_ID: The ID of the workload identitypool provider.
  • SERVICE_ACCOUNT_EMAIL: The email address of theservice account, if you use service account impersonation. If youuse direct resource access, omitSERVICE_ACCOUNTandservice_account_impersonation_url.
  • REGION: A region forregional STS endpoints,if they are available. If regional endpoints aren't available, you canuse https://sts.googleapis.com/v1/token.

The configuration does the following:

  1. Instructs GitLab to issue an ID token, and makes it available in theenvironment variable namedWORKLOAD_IDENTITY_TOKEN. The ID tokenuses your workload identity pool provider as audience.
  2. Saves the ID token to a temporary file named.workload_identity.jwt.
  3. Creates a credential configuration file that instructs client librariesto read the ID token from.workload_identity.jwt and uses it toimpersonate a service account.
  4. Sets the environment variableGOOGLE_APPLICATION_CREDENTIALS to pointto the credential configuration file.

Terraform Cloud

Configure your Terraform Cloud workspace so that it usesWorkload Identity Federation to authenticate to Google Cloud usingservice account impersonation:

  1. In Terraform Cloud, open your workspace and go toVariables.

  2. Add the following variables:

    Variable categoryKeyValue
    Environment variableTFC_GCP_PROVIDER_AUTHtrue
    Environment variableTFC_GCP_RUN_SERVICE_ACCOUNT_EMAILThe email address of the service account, if you use service account impersonation—for example,terraform@my-project-123.iam.gserviceaccount.com. Omit this environment variable if you use direct resource access.
    Environment variableTFC_GCP_PROJECT_NUMBERThe project number of the project that contains the workload identity pool
    Environment variableTFC_GCP_WORKLOAD_POOL_IDThe ID of the workload identity pool
    Environment variableTFC_GCP_WORKLOAD_PROVIDER_IDThe ID of the workload identity pool provider

    Optionally, if you use service account impersonation, you can addadditional environment variables to let Terraform Cloud use differentservice accounts for theplan andapply phases. For moreinformation about using environment variables in Terraformconfigurations, seeOptional Environment Variables.

  3. In the list of variables, verify thatCategory is set toenv forthe five variables that you added in the previous step.

  4. Verify that your Terraform configuration uses version4.48.0 or newerof the Google Cloud provider, and update it if necessary, as follows:

    terraform {  required_providers {    google = {      source  = "hashicorp/google"      version = "~> 4.48.0"    }  }}
  5. Submit the changes to your source code repository.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.