- Notifications
You must be signed in to change notification settings - Fork278
A GitHub Action for authenticating to Google Cloud.
License
google-github-actions/auth
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This GitHub Action authenticates to Google Cloud. It supports authentication viaa Google Cloud Service Account Key JSON and authentication viaWorkloadIdentity Federation.
Workload Identity Federation is recommended over Service Account Keys as itobviates the need to export a long-lived credential and establishes a trustdelegation relationship between a particular GitHub Actions workflow invocationand permissions on Google Cloud. There are three ways to set up this GitHubAction to authenticate to Google Cloud:
- (Preferred) Direct Workload Identity Federation
- Workload Identity Federation through a Service Account
- Service Account Key JSON
Important
Thegsutil command willnot use the credentials exported by this GitHubAction. Customers should usegcloud storage instead.
This is not an officially supported Google product, and it is not covered by aGoogle Cloud support contract. To report bugs or request features in a GoogleCloud product, please contactGoogle Cloudsupport.
Run the
actions/checkout@v4stepbefore this action. Omitting thecheckout step or putting it afterauthwill cause future steps to beunable to authenticate.To create binaries, containers, pull requests, or other releases, add thefollowing to your
.gitignore,.dockerignoreand similar files to preventaccidentally committing credentials to your release artifact:# Ignore generated credentials from google-github-actions/authgha-creds-*.jsonThis action runs using Node 24. Use arunnerversion that supports thisversion of Node or newer.
jobs:job_id:# Any runner supporting Node 20 or newerruns-on:ubuntu-latest# Add "id-token" with the intended permissions.permissions:contents:'read'id-token:'write'steps: -uses:'actions/checkout@v4' -uses:'google-github-actions/auth@v3'with:project_id:'my-project'workload_identity_provider:'projects/123456789/locations/global/workloadIdentityPools/my-pool/providers/my-provider'
Note
Changing thepermissions block may remove some default permissions. See thepermissions documentation for more information.
For more usage options, see theexamples.
Warning
This option isnot supported by Firebase AdminSDK. Use ServiceAccount Key JSON authentication instead.
Warning
As of the time of this writing, the GitHub OIDC token expires in 5 minutes,which means any derived credentials also expire in 5 minutes.
The following inputs are forauthenticating to Google Cloud via WorkloadIdentity Federation.
workload_identity_provider: (Required) The full identifier of the WorkloadIdentity Provider, including the project number, pool name, and providername. If provided, this must be the full identifier which includes allparts:projects/123456789/locations/global/workloadIdentityPools/my-pool/providers/my-providerservice_account: (Optional) Email address or unique identifier of theGoogle Cloud service account for which to impersonate and generatecredentials. For example:my-service-account@my-project.iam.gserviceaccount.comWithout this input, the GitHub Action will useDirect Workload IdentityFederation. If this input is provided, the GitHub Action will useWorkload Identity Federation through a Service Account.
audience: (Optional) The value for the audience (aud) parameter in thegenerated GitHub Actions OIDC token. This value defaults to the value ofworkload_identity_provider, which is also the default value Google Cloudexpects for the audience parameter on the token.
Caution
Service Account Key JSON credentials are long-lived credentials and must betreated like a password.
The following inputs are forauthenticating to Google Cloud via a ServiceAccount Key JSON.
credentials_json: (Required) The Google Cloud Service Account Key JSON touse for authentication.We advise minifying your JSON into a single line string before storing it ina GitHub Secret. When a GitHub Secret is used in a GitHub Actions workflow,each line of the secret is masked in log output. This can lead toaggressive sanitization of benign characters like curly braces (
{}) andbrackets ([]).To generate access tokens or ID tokens using this service account, you mustgrant the underlying service account
roles/iam.serviceAccountTokenCreatorpermissions on itself.
The following inputs are forgenerating OAuth 2.0 access tokens forauthenticating to Google Cloud as an output for use in future steps in theworkflow. These options only apply to access tokens generated by this action. Bydefault, this action does not generate any tokens.
service_account: (Required) Email address or unique identifier of theGoogle Cloud service account for which to generate the access token. Forexample:my-service-account@my-project.iam.gserviceaccount.comtoken_format: (Required) This value must be"access_token"to generateOAuth 2.0 access tokens.access_token_lifetime: (Optional) Desired lifetime duration of the accesstoken, in seconds. This must be specified as the number of seconds with atrailing "s" (e.g. 30s). The default value is 1 hour (3600s). The maximumvalue is 1 hour, unless theconstraints/iam.allowServiceAccountCredentialLifetimeExtensionorganization policy is enabled, in which case the maximum value is 12 hours.access_token_scopes: (Optional) List of OAuth 2.0 access scopes to beincluded in the generated token. This is only valid when "token_format" is"access_token". The default value is:https://www.googleapis.com/auth/cloud-platformThis can be specified as a comma-separated or newline-separated list.
access_token_subject: (Optional) Email address of a user to impersonateforDomain-Wide Delegation. Access tokens created for Domain-WideDelegation cannot have a lifetime beyond 1 hour, even if theconstraints/iam.allowServiceAccountCredentialLifetimeExtensionorganization policy is enabled.In order to support Domain-Wide Delegation via Workload Identity Federation,you must grant the external identity ("principalSet")
roles/iam.serviceAccountTokenCreatorin addition toroles/iam.workloadIdentityUser. The default Workload Identity setup willonly grant the latter role. If you want to use this GitHub Action withDomain-Wide Delegation, you must manually add the "Service Account TokenCreator" role onto the external identity.You will also need to customize the
access_token_scopesvalue tocorrespond to the OAuth scopes required for the API(s) you will access.
The following inputs are forgenerating ID tokens for authenticating to GoogleCloud as an output for use in future steps in the workflow. These options onlyapply to ID tokens generated by this action. By default, this action does notgenerate any tokens.
Caution
ID Tokens have a maximum lifetime of 10 minutes. This value cannot be changed.
service_account: (Required) Email address or unique identifier of theGoogle Cloud service account for which to generate the ID token. Forexample:my-service-account@my-project.iam.gserviceaccount.comtoken_format: This value must be"id_token"to generate ID tokens.id_token_audience: (Required) The audience for the generated ID Token.id_token_include_email: (Optional) Optional parameter of whether toinclude the service account email in the generated token. If true, the tokenwill contain "email" and "email_verified" claims. This is only valid when"token_format" is "id_token". The default value is false.
The following inputs are for controlling the behavior of this GitHub Actions,regardless of the authentication mechanism.
project_id: (Optional) Custom project ID to use for authentication andexporting into other steps. If unspecified, we will attempt to extract theproject ID from the Workload Identity Provider, Service Account email, orthe Service Account Key JSON. If this fails, you will need to specify theproject ID manually.create_credentials_file: (Optional) If true, the action will securelygenerate a credentials file which can be used for authentication via gcloudand Google Cloud SDKs in other steps in the workflow. The default is true.The credentials file is exported into
$GITHUB_WORKSPACE, which makes itavailable to all future steps and filesystems (including Docker-based GitHubActions). The file is automatically removed at the end of the job via a postaction. In order to use exported credentials, youmust add theactions/checkoutstep before callingauth. This is due to how GitHubActions creates$GITHUB_WORKSPACE:jobs:job_id:steps: -uses:'actions/checkout@v4'# Must come first! -uses:'google-github-actions/auth@v3'
export_environment_variables: (Optional) If true, the action will exportcommon environment variables which are known to be consumed by populardownstream libraries and tools, including:CLOUDSDK_PROJECTCLOUDSDK_CORE_PROJECTGCP_PROJECTGCLOUD_PROJECTGOOGLE_CLOUD_PROJECT
If
create_credentials_fileis true, additional environment variables areexported:CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDEGOOGLE_APPLICATION_CREDENTIALSGOOGLE_GHA_CREDS_PATH
If false, the action will not export any environment variables, meaningfuture steps are unlikely to be automatically authenticated to Google Cloud.The default value is true.
delegates: (Optional) List of additional service account emails or uniqueidentities to use for impersonation in the chain. By default there are nodelegates. This can be specified as a comma-separated or newline-separatedlist.universe: (Optional) The Google Cloud universe to use for constructing APIendpoints. The default universe is "googleapis.com", which corresponds tohttps://cloud.google.com. Trusted Partner Cloud and Google DistributedHosted Cloud should set this to their universe address.You can also override individual API endpoints by setting the environmentvariable
GHA_ENDPOINT_OVERRIDE_<endpoint>where endpoint is the APIendpoint to override. This only applies to theauthaction and does notpersist to other steps. For example:env:GHA_ENDPOINT_OVERRIDE_oauth2:'https://oauth2.myapi.endpoint/v1'
request_reason: (Optional) An optional Reason RequestSystemParameter for eachAPI call made by the GitHub Action. This will inject the"X-Goog-Request-Reason" HTTP header, which will provide user-suppliedinformation in Google Cloud audit logs.cleanup_credentials: (Optional) If true, the action will remove anycreated credentials from the filesystem upon completion. This only appliesif "create_credentials_file" is true. The default is true.
project_id: Provided or extracted value for the Google Cloud project ID.credentials_file_path: Path on the local filesystem where the generatedcredentials file resides. This is only available if"create_credentials_file" was set to true.auth_token: The Google Cloud federated token (for Workload IdentityFederation) or self-signed JWT (for a Service Account Key JSON). This outputis always available.access_token: The Google Cloud access token for calling other Google CloudAPIs. This is only available when "token_format" is "access_token".id_token: The Google Cloud ID token. This is only available when"token_format" is "id_token".
This section describes the three configuration options:
- (Preferred) Direct Workload Identity Federation
- Workload Identity Federation through a Service Account
- Service Account Key JSON
Important
It can take up to 5 minutes for Workload Identity Pools, Workload IdentityProviders, and IAM permissions to propagate. Please wait at least five minutesand follow allTroubleshooting steps before openingan issue.
In this setup, the Workload Identity Pool has direct IAM permissions on GoogleCloud resources; there are no intermediate service accounts or keys. This ispreferred since it directly authenticates GitHub Actions to Google Cloud withouta proxy resource. However, not all Google Cloud resources supportprincipalSetidentities, and the resulting token has a maximum lifetime of 10 minutes. Pleasesee the documentation for your Google Cloud service for more information.
Important
To generate OAuth 2.0 access tokens or ID tokens, youmust provide a serviceaccount email, and the Workload Identity Pool must haveroles/iam.workloadIdentityUser permissions on the target Google CloudService Account. Follow the steps for Workload Identity Federation through aService Account instead.
Click here to show detailed instructions for configuring GitHub authentication to Google Cloud via a direct Workload Identity Federation.
These instructions use thegcloud command-line tool.
Create a Workload Identity Pool:
# TODO: replace ${PROJECT_ID} with your value below.gcloud iam workload-identity-pools create"github" \ --project="${PROJECT_ID}" \ --location="global" \ --display-name="GitHub Actions Pool"
Get the full ID of the Workload IdentityPool:
# TODO: replace ${PROJECT_ID} with your value below.gcloud iam workload-identity-pools describe"github" \ --project="${PROJECT_ID}" \ --location="global" \ --format="value(name)"
This value should be of the format:
projects/123456789/locations/global/workloadIdentityPools/githubCreate a Workload IdentityProvider in that pool:
🛑 CAUTION! Always add an Attribute Condition to restrict entry into theWorkload Identity Pool. You can further restrict access in IAM Bindings, butalways add a basic condition that restricts admission into the pool. A gooddefault option is to restrict admission based on your GitHub organization asdemonstrated below. Please see thesecurityconsiderations for more details.
# TODO: replace ${PROJECT_ID} and ${GITHUB_ORG} with your values below.gcloud iam workload-identity-pools providers create-oidc"my-repo" \ --project="${PROJECT_ID}" \ --location="global" \ --workload-identity-pool="github" \ --display-name="My GitHub repo Provider" \ --attribute-mapping="google.subject=assertion.sub,attribute.actor=assertion.actor,attribute.repository=assertion.repository,attribute.repository_owner=assertion.repository_owner" \ --attribute-condition="assertion.repository_owner == '${GITHUB_ORG}'" \ --issuer-uri="https://token.actions.githubusercontent.com"
❗️ IMPORTANT You must map any claims in the incoming token toattributes before you can assert on those attributes in a CEL expressionor IAM policy!
Extract the Workload IdentityProvider resource name:
# TODO: replace ${PROJECT_ID} with your value below.gcloud iam workload-identity-pools providers describe"my-repo" \ --project="${PROJECT_ID}" \ --location="global" \ --workload-identity-pool="github" \ --format="value(name)"
Use this value as the
workload_identity_providervalue in the GitHubActions YAML:-uses:'google-github-actions/auth@v3'with:project_id:'my-project'workload_identity_provider:'...'# "projects/123456789/locations/global/workloadIdentityPools/github/providers/my-repo"
❗️ IMPORTANT The
project_idinput is optional, but may be requiredby downstream authentication systems such as thegcloudCLI.Unfortunately we cannot extract the project ID from the Workload IdentityProvider, since it requires the projectnumber.It is technically possible to convert a projectnumber into a projectID, but it requires permissions to call Cloud Resource Manager, and wecannot guarantee that the Workload Identity Pool has those permissions.
As needed, allow authentications from the Workload Identity Pool to GoogleCloud resources. These can be any Google Cloud resources that supportfederated ID tokens, and it can be done after the GitHub Action isconfigured.
The following example shows granting access from a GitHub Action in aspecific repository a secret in Google Secret Manager.
# TODO: replace ${PROJECT_ID}, ${WORKLOAD_IDENTITY_POOL_ID}, and ${REPO}# with your values below.## ${REPO} is the full repo name including the parent GitHub organization,# such as "my-org/my-repo".## ${WORKLOAD_IDENTITY_POOL_ID} is the full pool id, such as# "projects/123456789/locations/global/workloadIdentityPools/github".gcloud secrets add-iam-policy-binding"my-secret" \ --project="${PROJECT_ID}" \ --role="roles/secretmanager.secretAccessor" \ --member="principalSet://iam.googleapis.com/${WORKLOAD_IDENTITY_POOL_ID}/attribute.repository/${REPO}"
Review theGitHub documentation for a complete list ofoptions and values. This GitHub repository does not seek to enumerate everypossible combination.
In this setup, the Workload Identity Pool impersonates a Google Cloud ServiceAccount which has IAM permissions on Google Cloud resources. This exchanges theGitHub Actions OIDC token with a Google Cloud OAuth 2.0 access token by grantingGitHub Actions permissions to mint tokens for the given Service Account. ThusGitHub Actions inherits that Service Account's permissions by proxy.
Click here to show detailed instructions for configuring GitHub authentication to Google Cloud via a Workload Identity Federation through a Service Account.
These instructions use thegcloud command-line tool.
(Optional) Create a Google Cloud Service Account. If you already have aService Account, take note of the email address and skip this step.
# TODO: replace ${PROJECT_ID} with your value below.gcloud iam service-accounts create"my-service-account" \ --project"${PROJECT_ID}"
Create a Workload Identity Pool:
# TODO: replace ${PROJECT_ID} with your value below.gcloud iam workload-identity-pools create"github" \ --project="${PROJECT_ID}" \ --location="global" \ --display-name="GitHub Actions Pool"
Get the full ID of the Workload IdentityPool:
# TODO: replace ${PROJECT_ID} with your value below.gcloud iam workload-identity-pools describe"github" \ --project="${PROJECT_ID}" \ --location="global" \ --format="value(name)"
This value should be of the format:
projects/123456789/locations/global/workloadIdentityPools/githubCreate a Workload IdentityProvider in that pool:
🛑 CAUTION! Always add an Attribute Condition to restrict entry into theWorkload Identity Pool. You can further restrict access in IAM Bindings, butalways add a basic condition that restricts admission into the pool. A gooddefault option is to restrict admission based on your GitHub organization asdemonstrated below. Please see thesecurityconsiderations for more details.
# TODO: replace ${PROJECT_ID} and ${GITHUB_ORG} with your values below.gcloud iam workload-identity-pools providers create-oidc"my-repo" \ --project="${PROJECT_ID}" \ --location="global" \ --workload-identity-pool="github" \ --display-name="My GitHub repo Provider" \ --attribute-mapping="google.subject=assertion.sub,attribute.actor=assertion.actor,attribute.repository=assertion.repository,attribute.repository_owner=assertion.repository_owner" \ --attribute-condition="assertion.repository_owner == '${GITHUB_ORG}'" \ --issuer-uri="https://token.actions.githubusercontent.com"
❗️ IMPORTANT You must map any claims in the incoming token toattributes before you can assert on those attributes in a CEL expressionor IAM policy!
Allow authentications from the Workload Identity Pool to your Google CloudService Account.
# TODO: replace ${PROJECT_ID}, ${WORKLOAD_IDENTITY_POOL_ID}, and ${REPO}# with your values below.## ${REPO} is the full repo name including the parent GitHub organization,# such as "my-org/my-repo".## ${WORKLOAD_IDENTITY_POOL_ID} is the full pool id, such as# "projects/123456789/locations/global/workloadIdentityPools/github".gcloud iam service-accounts add-iam-policy-binding"my-service-account@${PROJECT_ID}.iam.gserviceaccount.com" \ --project="${PROJECT_ID}" \ --role="roles/iam.workloadIdentityUser" \ --member="principalSet://iam.googleapis.com/${WORKLOAD_IDENTITY_POOL_ID}/attribute.repository/${REPO}"
Review theGitHub documentation for a complete list ofoptions and values. This GitHub repository does not seek to enumerate everypossible combination.
Extract the Workload IdentityProvider resource name:
# TODO: replace ${PROJECT_ID} with your value below.gcloud iam workload-identity-pools providers describe"my-repo" \ --project="${PROJECT_ID}" \ --location="global" \ --workload-identity-pool="github" \ --format="value(name)"
Use this value as the
workload_identity_providervalue in the GitHubActions YAML:-uses:'google-github-actions/auth@v3'with:service_account:'...'# my-service-account@my-project.iam.gserviceaccount.comworkload_identity_provider:'...'# "projects/123456789/locations/global/workloadIdentityPools/github/providers/my-repo"
As needed, grant the Google Cloud Service Account permissions to accessGoogle Cloud resources. This step varies by use case. The following exampleshows granting access to a secret in Google Secret Manager.
# TODO: replace ${PROJECT_ID} with your value below.gcloud secrets add-iam-policy-binding"my-secret" \ --project="${PROJECT_ID}" \ --role="roles/secretmanager.secretAccessor" \ --member="serviceAccount:my-service-account@${PROJECT_ID}.iam.gserviceaccount.com"
In this setup, a Service Account has direct IAM permissions on Google Cloudresources. You download a Service Account Key JSON file and upload it to GitHubas a secret.
Caution
Google Cloud Service Account Key JSON files must be securedand treated like a password. Anyone with access to the JSON key canauthenticate to Google Cloud as the underlying Service Account. By default,these credentials never expire, which is why the former authentication optionsare much preferred.
Click here to show detailed instructions for configuring GitHub authentication to Google Cloud via a Service Account Key JSON.
These instructions use thegcloud command-line tool.
(Optional) Create a Google Cloud Service Account. If you already have aService Account, take note of the email address and skip this step.
# TODO: replace ${PROJECT_ID} with your value below.gcloud iam service-accounts create"my-service-account" \ --project"${PROJECT_ID}"
Create a Service Account Key JSON for the Service Account.
# TODO: replace ${PROJECT_ID} with your value below.gcloud iam service-accounts keys create"key.json" \ --iam-account"my-service-account@${PROJECT_ID}.iam.gserviceaccount.com"
Upload the contents of this file as aGitHub ActionsSecret.
Use the name of the GitHub Actions secret as the
credentials_jsonvalue inthe GitHub Actions YAML:-uses:'google-github-actions/auth@v3'with:credentials_json:'${{ secrets.GOOGLE_CREDENTIALS }}'# Replace with the name of your GitHub Actions secret
About
A GitHub Action for authenticating to Google Cloud.
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.