Configure workload identity federation with AWS or Azure

This guide describes how to use workload identity federation to let AWS and Azure workloads authenticate to Google Cloud without a service account key.

Using workload identity federation, workloads that run on AWS EC2 and Azure can exchange their environment-specific credentials for short-lived Google Cloud Security Token Service tokens.

Environment-specific credentials include the following:

By setting up workload identity federation, you can let these workloads exchange these environment-specific credentials against short-lived Google Cloud credentials. Workloads can use these short-lived credentials to access Google Cloud APIs.

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

    You can use the gcloud CLI samples on this page from either of the following development environments:

    • Cloud Shell: To use an online terminal with the gcloud CLI already set up, activate Cloud Shell.

      At the bottom of this page, a Cloud Shell session starts and displays a command-line prompt. It can take a few seconds for the session to initialize.

    • Local shell: To use the gcloud CLI in a local development environment, install and initialize the gcloud CLI.

    Python

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

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

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

Prepare your external identity provider

You only need to perform these steps once for each Azure AD tenant or AWS account.

AWS

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

After you configure a workload identity pool to trust your AWS account, you can let AWS users and AWS roles use permanent or temporary AWS security credentials to obtain short-lived Google Cloud credentials.

Azure

You must create a new Azure AD application in your Azure AD tenant and configure it so that it can be used for workload identity federation.

After you configure a workload identity pool to trust the application, Azure users and service principals can request access tokens for this application and exchange these access tokens against short-lived Google Cloud credentials.

To create the application, do the following:

  1. Create an Azure AD application and service principal.

  2. Set an Application ID URI for the application. You can use the default Application ID URI (api://APPID) or specify a custom URI.

    You need the Application ID URI later when you configure the workload identity pool provider.

To let an application obtain access tokens for the Azure AD application, you can use managed identities:

  1. Create a managed identity. Note the Object ID of the managed identity. You need it later when you configure impersonation.

  2. Assign the managed identity to a virtual machine or another resource that runs your application.

Configure workload identity federation

You only need to perform these steps once per AWS account or Azure AD tenant. You can then use the same workload identity pool and provider for multiple workloads and across multiple Google Cloud projects.

To start configuring workload identity federation, do the following:

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

    Go to project selector

  2. It's best to use a dedicated project to manage workload identity pools and providers.
  3. Make sure that billing is enabled for your Google Cloud project.

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

    Enable the APIs

Define an attribute mapping and condition

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

Google Cloud uses the subject identifier in Cloud Audit Logs and in principal identifiers to uniquely identify an AWS or Azure user or role.

Optionally, you can map additional attributes. You can then refer to these additional attributes when granting access to resources.

AWS

Your attribute mapping can use the response fields for GetCallerIdentity as source attributes. These fields include the following:

  • account: the AWS account number.
  • arn: the AWS ARN of the external entity.
  • userid: the unique identifier of the calling entity.

If your application runs on an Amazon Elastic Compute Cloud (EC2) instance with an attached role, you can use the following attribute mapping:

google.subject=assertion.arn
attribute.account=assertion.account
attribute.aws_role=assertion.arn.extract('assumed-role/{role}/')
attribute.aws_ec2_instance=assertion.arn.extract('assumed-role/{role_and_session}').extract('/{session}')

The mapping does the following:

  • Use the ARN as subject identifier (Example: "arn:aws:sts::000000000000:assumed-role/ec2-my-role/i-00000000000000000)
  • Introduce a custom attribute account and assign it the AWS account ID
  • Introduce a custom attribute aws_role and assign it the AWS role name (Example: ec2-my-role)
  • Introduce a custom attribute aws_ec2_instance and assign it the EC2 instance ID (Example: i-00000000000000000)

Using this mapping, you can grant access to:

  • A specific EC2 instance:

    principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.aws_ec2_instance/EC2_INSTANCE_ID
    

  • All users and instances in a role:

    principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.aws_role/ROLE_NAME
    

Azure

Your attribute mappings can use the claims embedded in Azure access tokens, including custom claims, as source attributes. In most cases, it's best to use the sub claim as subject identifier:

google.subject=assertion.sub

For an access token issued to a managed identity, the sub claim contains the Object ID of the managed identity. If you use a different claim, make sure that the claim is unique and can't be reassigned.

If you're unsure about the list of claims you can reference, do the following:

  1. Connect to an Azure VM that has an assigned managed identity.

  2. Obtain an access token from the Azure Instance Metadata Service (IMDS):

    Bash

    curl \
      "http://169.254.169.254/metadata/identity/oauth2/token?resource=APP_ID_URI&api-version=2018-02-01" \
      -H "Metadata: true" | jq -r .access_token
    

    This command uses the jq tool. jq is available by default in Cloud Shell.

    PowerShell

    $SubjectTokenType = "urn:ietf:params:oauth:token-type:jwt"
    $SubjectToken = (Invoke-RestMethod `
      -Uri "http://169.254.169.254/metadata/identity/oauth2/token?resource=APP_ID_URI&api-version=2018-02-01" `
      -Headers @{Metadata="true"}).access_token
    Write-Host $SubjectToken
    

    Replace APP_ID_URI with the Application ID URI of the application that you've configured for workload identity federation.

  3. In a web browser, go to https://jwt.ms/ and paste the access token into the text box.

  4. Click Claims to view the list of claims embedded in the access token.

For service identities, it's typically not necessary to create a mapping for google.groups or any custom attributes.

Optionally, define an attribute condition. Attribute conditions are CEL expressions that can check assertion attributes and target attributes. If the attribute condition evaluates to true for a given credential, the credential is accepted. Otherwise, the credential is rejected.

AWS

You can use an attribute condition to restrict which IAM users and roles can use workload identity federation to obtain short-lived Google Cloud tokens.

For example, the following condition restricts access to AWS roles and disallows other IAM identifiers:

assertion.arn.startsWith('arn:aws:sts::AWS_ACCOUNT_ID:assumed-role/')

Azure

You can use an attribute condition to restrict which users and service principals can use workload identity federation to obtain short-lived Google Cloud tokens. Alternatively, you can configure your Azure AD application to use app role assignments.

Create the workload identity pool and provider

Required roles

To get the permissions that you need to configure workload identity federation, ask your administrator to grant you the following IAM roles on the project:

For more information about granting roles, see Manage access.

You might also be able to get the required permissions through custom roles or other predefined roles.

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

You now have collected all of the information that you need to create a workload identity pool and provider:

Console

  1. In the Google Cloud console, go to the New workload provider and pool page.

    Go to New workload provider and pool

  2. In the Create an identity pool section, 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. Click Continue.

  4. Configure provider settings:

    AWS

    Configure the following provider settings:

    • Select a provider: AWS.
    • Provider name: the name for the provider. The name is also used as the provider ID. You cannot change the provider ID later.

    Azure

    Configure the following provider settings:

    • Select a provider: OpenID Connect (OIDC).
    • Provider name: Name for the provider. The name is also used as the provider ID. You cannot change the provider ID later.
    • Issuer URL: https://sts.windows.net/TENANT_ID. Replace TENANT_ID with the tenant ID (GUID) of your Azure AD tenant.
    • Allowed audiences: Application ID URI that you used when you registered the application in Azure AD.
  5. Click Continue.

  6. In the Configure provider attributes section, add the attribute mappings that you've identified previously.

  7. In the Attribute conditions section, enter the attribute condition that you identified previously. Leave the field blank if you don't have an attribute condition.

  8. Click Save to create the workload identity pool and provider.

gcloud

  1. Create a new workload identity pool:

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

    Replace the following:

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

    AWS

    To create the workload identity pool provider for AWS, execute the following command:

    gcloud iam workload-identity-pools providers create-aws PROVIDER_ID \
      --location="global"  \
      --workload-identity-pool="POOL_ID" \
      --account-id="ACCOUNT_ID" \
      --attribute-mapping="MAPPINGS" \
      --attribute-condition="CONDITIONS"
    

    Replace the following:

    Example:

    gcloud iam workload-identity-pools providers create-aws example-provider \
      --location="global"  \
      --workload-identity-pool="pool-1" \
      --account-id="123456789000" \
      --attribute-mapping="google.subject=assertion.arn"
    

    Azure

    To create the workload identity pool provider for Azure, execute the following command:

    gcloud iam workload-identity-pools providers create-oidc PROVIDER_ID \
        --location="global" \
        --workload-identity-pool="POOL_ID" \
        --issuer-uri="ISSUER_URI" \
        --allowed-audiences="APPLICATION_ID_URI" \
        --attribute-mapping="MAPPINGS" \
        --attribute-condition="CONDITIONS"
    

    Replace the following:

    • PROVIDER_ID: The unique ID for the provider.
    • POOL_ID: The ID of the pool.
    • ISSUER_URI: The tenant ID (GUID) of your Azure AD tenant, sometimes formatted as https://sts.windows.net/TENANT_ID. The issuer URI can vary, and to find your issuer URI, you can debug your JWT using JWT.io.
    • APPLICATION_ID_URI: Application ID URI that you used when you registered the application in Azure AD.
    • MAPPINGS: The comma-separated list of attribute mappings that you previously identified.
    • CONDITIONS: (Optional) The attribute condition that you previously identified.

    Example:

    gcloud iam workload-identity-pools providers create-oidc example-provider \
        --location="global" \
        --workload-identity-pool="pool-1" \
        --issuer-uri="https://sts.windows.net/00000000-1111-2222-3333-444444444444" \
        --allowed-audiences="api://my-app" \
        --attribute-mapping="google.subject=assertion.sub,google.groups=assertion.groups"
    

Authenticate a workload

You must perform these steps once per workload.

Create a service account for the external workload

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

    Enable the APIs

  2. Create a service account that represents the workload. It's best to use a dedicated service account for each workload.

    The service account doesn't need to be in the same project as the workload identity pool.

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

Allow the external workload to impersonate the service account

To allow external identities to impersonate a service account, you grant them the Workload Identity User role (roles/iam.workloadIdentityUser) on the service account. You can grant the role to a specific external identity, or to multiple external identities:

  • For a specific external identity, write an attribute condition that checks the google.subject attribute.
  • For a group of external identities, write an attribute condition that checks the google.groups attribute or a custom attribute attribute.NAME.

Console

To allow external identities to impersonate a service account using the Google Cloud console, do the following:

  1. In the Google Cloud console, go to the Workload Identity Pools page.

    Go to Workload Identity Pools

  2. Find the workload identity pool you want to update and select it.

  3. To grant access to the selected workload identity pool, click Grant access.

  4. In the Service account list, select the service account for the external identities to impersonate.

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

    • To allow only specific identities of the workload identity pool to impersonate the service account, select Only identities matching the filter.

      In the Attribute name list, select the attribute that you want to filter on.

      In the Attribute value field, enter the expected value of the attribute; for example, if you use an attribute mapping google.subject=assertion.sub, set Attribute name to subject and Attribute value to the value of the sub claim in tokens issued by your external identity provider.

  6. To save the configuration, click Save and then Dismiss.

gcloud

To allow external identities to impersonate a service account using gcloud CLI, do the following:

  1. To obtain the project number of your current project, execute the following command:

    gcloud projects describe $(gcloud config get-value core/project) --format=value\(projectNumber\)
    
  2. To grant the Workload Identity User role (roles/iam.workloadIdentityUser) to external identities that meet a certain criteria:

    By subject

    gcloud iam service-accounts add-iam-policy-binding SERVICE_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-binding SERVICE_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-binding SERVICE_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: the project 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 that you've mapped to google.subject
    • GROUP: the expected value for the attribute that you've mapped to google.groups
    • ATTRIBUTE_NAME: the name of a custom attribute in your attribute mapping

Create a credential configuration

The Cloud Client Libraries, the gcloud CLI, and Terraform, can automatically obtain external credentials, and use these credentials to impersonate a service account. To let libraries and tools complete this process, you have to provide a credential configuration file. This file defines the following:

  • Where to obtain external credentials from
  • Which workload identity pool and provider to use
  • Which service account to impersonate

To create a credential configuration file, do the following:

Console

Download a credential configuration file in the Google Cloud console:

  1. In the Google Cloud console, go to the Workload Identity Pools page.

    Go to Workload Identity Pools

  2. Find the workload identity pool that contains the IdP you want to use and click on it.

  3. Select Connected service accounts.

  4. Find the service account you want to use and click Download.

  5. In the Configure your application dialog, select the provider that contains the external identities that will impersonate the service account.

  6. Provide the following additional settings:

    AWS

    No additional settings required.

    Azure

    Application ID URL: Application ID URI of the Azure application

  7. Select Download config to download the credential configuration file, then click Dismiss.

gcloud

To create a credential configuration file by using gcloud iam workload-identity-pools create-cred-config, do the following:

AWS

To create a credential configuration file that lets the library obtain an access token from EC2 instance metadata, do the following:

gcloud iam workload-identity-pools create-cred-config \
    projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \
    --service-account=SERVICE_ACCOUNT_EMAIL \
    --service-account-token-lifetime-seconds=SERVICE_ACCOUNT_TOKEN_LIFETIME \
    --aws \
    --output-file=FILEPATH.json

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
  • SERVICE_ACCOUNT_TOKEN_LIFETIME: lifetime of the service account access token, in seconds; this defaults to one hour when not provided. To specify a lifetime longer than one hour, you must configure the constraints/iam.allowServiceAccountCredentialLifetimeExtension organizational policy constraint.
  • FILEPATH: the file to save configuration to

If you use AWS IMDSv2, an additional flag --enable-imdsv2 needs to be added to the gcloud iam workload-identity-pools create-cred-config command:

gcloud iam workload-identity-pools create-cred-config \
    projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \
    --service-account=SERVICE_ACCOUNT_EMAIL \
    --aws \
    --enable-imdsv2 \
    --output-file=FILEPATH.json

If using the AWS metadata server isn't an option, you can provide AWS security credentials through the following AWS environment variables:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • Either of AWS_REGION or AWS_DEFAULT_REGION
  • Optional: AWS_SESSION_TOKEN

The gcloud CLI and libraries use these AWS environment variables when the AWS metadata server is unavailable.

Azure

Create a credential configuration file that lets the library obtain an access token from the Azure Instance Metadata Service (IMDS):

gcloud iam workload-identity-pools create-cred-config \
    projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \
    --service-account=SERVICE_ACCOUNT_EMAIL \
    --service-account-token-lifetime-seconds=SERVICE_ACCOUNT_TOKEN_LIFETIME \
    --azure \
    --app-id-uri APPLICATION_ID_URI \
    --output-file=FILEPATH.json

Replace the following:

  • PROJECT_NUMBER: 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
  • APPLICATION_ID_URI: the Application ID URI of the Azure application
  • SERVICE_ACCOUNT_TOKEN_LIFETIME: lifetime of the service account access token, in seconds; this defaults to one hour when not provided. To specify a lifetime longer than one hour, you must configure the constraints/iam.allowServiceAccountCredentialLifetimeExtension organizational policy constraint.
  • FILEPATH: the file to save configuration to

Use the credential configuration to access Google Cloud

To let tools and client libraries use your credential configuration, do the following in your AWS or Azure environment:

  1. Initialize an environment variable GOOGLE_APPLICATION_CREDENTIALS and point it to the credential configuration file:

    Bash

      export GOOGLE_APPLICATION_CREDENTIALS=`pwd`/FILEPATH.json
      
    where FILEPATH is the relative file path to the credential configuration file.

    PowerShell

      $env:GOOGLE_APPLICATION_CREDENTIALS = Resolve-Path 'FILEPATH.json'
      
    where FILEPATH is the relative file path to the credential configuration file.
  2. Use a client library or tool that supports workload identity federation and can find credentials automatically:

    C++

    The Google Cloud Client Libraries for C++ support workload identity federation since version v2.6.0. To use workload identity federation, you must build the client libraries with version 1.36.0 or later of gRPC.

    Go

    Client libraries for Go support identity federation if they use version v0.0.0-20210218202405-ba52d332ba99 or later of the golang.org/x/oauth2 module.

    To check which version of this module your client library uses, run the following commands:

    cd $GOPATH/src/cloud.google.com/go
    go list -m golang.org/x/oauth2
    

    Java

    Client libraries for Java support identity federation if they use version 0.24.0 or later of the com.google.auth:google-auth-library-oauth2-http artifact.

    To check which version of this artifact your client library uses, run the following Maven command in your application directory:

    mvn dependency:list -DincludeArtifactIds=google-auth-library-oauth2-http
    

    Node.js

    Client libraries for Node.js support workload identity federation if they use version 7.0.2 or later of the google-auth-library package.

    To check which version of this package your client library uses, run the following command in your application directory:

    npm list google-auth-library
    

    When you create a GoogleAuth object, you can specify a project ID, or you can allow GoogleAuth to find the project ID automatically. To find the project ID automatically, the service account in the configuration file must have the Browser role (roles/browser), or a role with equivalent permissions, on your project. For details, see the README for the google-auth-library package.

    Python

    Client libraries for Python support identity federation if they use version 1.27.0 or later of the google-auth package.

    To check which version of this package your client library uses, run the following command in the environment where the package is installed:

    pip show google-auth
    

    To specify a project ID for the authentication client, you can set the GOOGLE_CLOUD_PROJECT environment variable, or you can allow the client to find the project ID automatically. To find the project ID automatically, the service account in the configuration file must have the Browser role (roles/browser), or a role with equivalent permissions, on your project. For details, see the user guide for the google-auth package.

    gcloud

    To authenticate using workload identity federation, use the gcloud auth login command:

    gcloud auth login --cred-file=FILEPATH.json
    

    Replace FILEPATH with the file path to the credential configuration file.

    Support for workload identity federation in gcloud CLI is available in version 363.0.0 and later versions of the gcloud CLI.

    Terraform

    The Google Cloud provider supports workload identity federation if you use version 3.61.0 or later:

    terraform {
      required_providers {
        google = {
          source  = "hashicorp/google"
          version = "~> 3.61.0"
        }
      }
    }
    

    gsutil

    To authenticate using workload identity federation, use one of the following methods:

    When you use gsutil in conjunction with gcloud, sign in as normal:

    gcloud auth login --cred-file=FILEPATH.json
    

    When you use gsutil as a stand-alone command-line application, edit the .boto file to include the following section:

    [Credentials]
    gs_external_account_file = FILEPATH
    

    Replace FILEPATH, in both cases, with the file path to the credential configuration file.

    Support for workload identity federation in gsutil is available in version 379.0.0 and later versions of the gcloud CLI.

    bq

    To authenticate using workload identity federation, use the gcloud auth login command, as follows:

    gcloud auth login --cred-file=FILEPATH.json
    

    Replace FILEPATH with the file path to the credential configuration file.

    Support for workload identity federation in bq is available in version 390.0.0 and later versions of the gcloud CLI.

    If you can't use a client library that supports workload identity federation, you can authenticate programmatically by using the REST API.

Advanced scenarios

Authenticate a workload using the REST API

If you can't use the client libraries, you can follow these steps to let an external workload obtain a short-lived access token by using the REST API:

  1. Obtain credentials from your external IdP:

    AWS

    Create a JSON document that contains the information that you would normally include in a request to the AWS GetCallerIdentity() endpoint, including a valid request signature.

    Workload identity federation refers to this JSON document as a GetCallerIdentity token. The token lets workload identity federation verify the identity without revealing the AWS secret access key.

    A GetCallerIdentity token looks similar to the following:

    {
      "url": "https://sts.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15",
      "method": "POST",
      "headers": [
        {
          "key": "Authorization",
          "value" : "AWS4-HMAC-SHA256 Credential=AKIASOZTBDV4D7ABCDEDF/20200228/us-east-1/sts/aws4_request, SignedHeaders=host;x-amz-date,Signature=abcedefdfedfd"
        },
        {
          "key": "host",
          "value": "sts.amazonaws.com"
        },
        {
          "key": "x-amz-date",
          "value": "20200228T225005Z"
        },
        {
          "key": "x-goog-cloud-target-resource",
          "value": "//iam.googleapis.com/projects/12345678/locations/global/workloadIdentityPools/my-pool/providers/my-aws-provider"
        },
        {
          "key": "x-amz-security-token",
          "value": "GizFWJTqYX...xJ55YoJ8E9HNU="
        }
      ]
    }
    

    The token contains the following fields:

    • url: The URL of the AWS STS endpoint for GetCallerIdentity(), with the body of a standard GetCallerIdentity() request appended as query parameters. For example, https://sts.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15. We recommend that you use regional STS endpoints and design a reliable infrastructure for your workloads. For more information, see Regional AWS STS endpoints.
    • method: The HTTP request method: POST.
    • headers: The HTTP request headers, which must include:
      • Authorization: The request signature.
      • host: The hostname of the url field; for example, sts.amazonaws.com.
      • x-amz-date: The time you will send the request, formatted as an ISO 8601 Basic string. This value is typically set to the current time and is used to help prevent replay attacks.
      • x-goog-cloud-target-resource: The full resource name of the identity provider without a https: prefix. For example:
        //iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID
        
      • x-amz-security-token: Session token. Only required if you are using temporary security credentials.

    The following example creates a URL-encoded GetCallerIdentity token. Extract the URL-encoded token for later use. It also creates a human-readable token just for your reference:

    import json
    import urllib
    
    import boto3
    from botocore.auth import SigV4Auth
    from botocore.awsrequest import AWSRequest
    
    
    def create_token_aws(project_number: str, pool_id: str, provider_id: str) -> None:
        # Prepare a GetCallerIdentity request.
        request = AWSRequest(
            method="POST",
            url="https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15",
            headers={
                "Host": "sts.amazonaws.com",
                "x-goog-cloud-target-resource": f"//iam.googleapis.com/projects/{project_number}/locations/global/workloadIdentityPools/{pool_id}/providers/{provider_id}",
            },
        )
    
        # Set the session credentials and Sign the request.
        # get_credentials loads the required credentials as environment variables.
        # Refer:
        # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
        SigV4Auth(boto3.Session().get_credentials(), "sts", "us-east-1").add_auth(request)
    
        # Create token from signed request.
        token = {"url": request.url, "method": request.method, "headers": []}
        for key, value in request.headers.items():
            token["headers"].append({"key": key, "value": value})
    
        # The token lets workload identity federation verify the identity without revealing the AWS secret access key.
        print("Token:\n%s" % json.dumps(token, indent=2, sort_keys=True))
        print("URL encoded token:\n%s" % urllib.parse.quote(json.dumps(token)))
    
    
    def main() -> None:
        # TODO(Developer): Replace the below credentials.
        # project_number: Google Project number (not the project id)
        project_number = "my-project-number"
        pool_id = "my-pool-id"
        provider_id = "my-provider-id"
    
        create_token_aws(project_number, pool_id, provider_id)
    
    
    if __name__ == "__main__":
        main()

    Initialize the following variables:

    Bash

    SUBJECT_TOKEN_TYPE="urn:ietf:params:aws:token-type:aws4_request"
    SUBJECT_TOKEN=TOKEN
    

    PowerShell

    $SubjectTokenType = "urn:ietf:params:aws:token-type:aws4_request"
    $SubjectToken = "TOKEN"
    

    Where TOKEN is the URL encoded GetCallerIdentity token that was generated by the script above.

    Azure

    Connect to an Azure VM that has an assigned managed identity and obtain an access token from the Azure Instance Metadata Service (IMDS):

    Bash

    SUBJECT_TOKEN_TYPE="urn:ietf:params:oauth:token-type:jwt"
    SUBJECT_TOKEN=$(curl \
      "http://169.254.169.254/metadata/identity/oauth2/token?resource=APP_ID_URI&api-version=2018-02-01" \
      -H "Metadata: true" | jq -r .access_token)
    echo $SUBJECT_TOKEN
    

    This command uses the jq tool. jq is available by default in Cloud Shell.

    PowerShell

    $SubjectTokenType = "urn:ietf:params:oauth:token-type:jwt"
    $SubjectToken = (Invoke-RestMethod `
      -Uri "http://169.254.169.254/metadata/identity/oauth2/token?resource=APP_ID_URI&api-version=2018-02-01" `
      -Headers @{Metadata="true"}).access_token
    Write-Host $SubjectToken
    

    Where APP_ID_URI is the Application ID URI of the application that you've configured for workload identity federation.

  2. Use the Security Token Service API to exchange the credential against a short-lived access token:

    Bash

    STS_TOKEN=$(curl https://sts.googleapis.com/v1/token \
        --data-urlencode "audience=//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID" \
        --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
        --data-urlencode "requested_token_type=urn:ietf:params:oauth:token-type:access_token" \
        --data-urlencode "scope=https://www.googleapis.com/auth/cloud-platform" \
        --data-urlencode "subject_token_type=$SUBJECT_TOKEN_TYPE" \
        --data-urlencode "subject_token=$SUBJECT_TOKEN" | jq -r .access_token)
    echo $STS_TOKEN
    

    PowerShell

    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
    $StsToken = (Invoke-RestMethod `
        -Method POST `
        -Uri "https://sts.googleapis.com/v1/token" `
        -ContentType "application/json" `
        -Body (@{
            "audience"           = "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID"
            "grantType"          = "urn:ietf:params:oauth:grant-type:token-exchange"
            "requestedTokenType" = "urn:ietf:params:oauth:token-type:access_token"
            "scope"              = "https://www.googleapis.com/auth/cloud-platform"
            "subjectTokenType"   = $SubjectTokenType
            "subjectToken"       = $SubjectToken
        } | ConvertTo-Json)).access_token
    Write-Host $StsToken
    

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
  3. Use the token from the Security Token Service to invoke the generateAccessToken method of the IAM Service Account Credentials API to obtain an access token:

Bash

ACCESS_TOKEN=$(curl -0 -X POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL:generateAccessToken \
    -H "Content-Type: text/json; charset=utf-8" \
    -H "Authorization: Bearer $STS_TOKEN" \
    -d @- <<EOF | jq -r .accessToken
    {
        "scope": [ "https://www.googleapis.com/auth/cloud-platform" ]
    }
EOF
)
echo $ACCESS_TOKEN

PowerShell

$AccessToken = (Invoke-RestMethod `
    -Method POST `
    -Uri "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL:generateAccessToken" `
    -Headers @{ "Authorization" = "Bearer $StsToken" } `
    -ContentType "application/json" `
    -Body (@{
        "scope" = , "https://www.googleapis.com/auth/cloud-platform"
    } | ConvertTo-Json)).accessToken
Write-Host $AccessToken

Replace SERVICE_ACCOUNT_EMAIL with the email address of the service account.

What's next