Some Google Cloud services—such as Compute Engine, App Engine, and Cloud Run functions—support attaching a user-managed service account to some types of resources. Generally, attaching a service account is supported when that service's resources can run or include application code. When you attach a service account to a resource, the code running on the resource can use that service account as its identity.
Attaching a user-managed service account is the preferred way to provide credentials to ADC for production code running on Google Cloud.
For help determining the roles that you need to provide to your service account, see Choose predefined roles.
For information about which resources you can attach a service account to, and help with attaching the service account to the resource, see the IAM documentation on attaching a service account.
Set up authentication:
-
Create the service account:
gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
Replace
SERVICE_ACCOUNT_NAME
with a name for the service account. -
To provide access to your project and your resources, grant a role to the service account:
gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=ROLE
Replace the following:
SERVICE_ACCOUNT_NAME
: the name of the service accountPROJECT_ID
: the project ID where you created the service accountROLE
: the role to grant
- To grant another role to the service account, run the command as you did in the previous step.
-
Grant the required role to the principal that will attach the service account to other resources.
gcloud iam service-accounts add-iam-policy-binding SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com --member="user:USER_EMAIL" --role=roles/iam.serviceAccountUser
Replace the following:
SERVICE_ACCOUNT_NAME
: the name of the service accountPROJECT_ID
: the project ID where you created the service accountUSER_EMAIL
: the email address for a Google Account
What's next
- Understand best practices for using service accounts and service account keys.
- Learn more about how ADC finds credentials.
- Authenticate for using Cloud Client Libraries.
- Explore authentication methods.