Terraform Service Account Authentication Patterns in Google Cloud

Introduction

Running Terraform against Google Cloud in production means you need a service account. Your personal Google account works fine for experimentation, but automated deployments need a dedicated identity with specific permissions. This guide covers creating a service account, assigning the right roles, and configuring the Terraform Google provider to use it. A GCP service account is a special type of Google account that belongs to your project rather than to an individual user. It has an email address like terraform@PROJECT_ID.iam.gserviceaccount.com, a key pair for authentication, and IAM role bindings that determine its permissions. Service accounts are the standard way to authenticate automated workloads including Terraform, CI/CD pipelines, and applications running on GCP. The identity that executes Terraform determines what infrastructure can be created, modified, or destroyed. Using a personal user account couples human credentials to automation, creates audit gaps, and prevents least privilege enforcement. A dedicated service account isolates the automation identity, allows granular role assignment, and enables rotation without affecting individual users. When Infra Manager executes Terraform, it uses the identity of this service account. You do not need a service account to view information about Infra Manager deployments. This page explains how to configure a service account so that you can deploy resources with Infrastructure Manager.

What Is a GCP Service Account

A GCP service account is a special type of Google account that belongs to your project rather than to an individual user. It is not tied to a human and persists independently of personnel changes.

The service account possesses:

  • An email address like terraform@PROJECT_ID.iam.gserviceaccount.com
  • A key pair for authentication
  • IAM role bindings that determine its permissions

Service accounts are the standard way to authenticate automated workloads including Terraform, CI/CD pipelines, and applications running on GCP. The email address is used as the principal in IAM policy bindings. The key pair enables programmatic authentication when a key file is used. IAM role bindings map the service account to roles such as roles/editor, roles/cloudsql.admin, roles/iam.serviceAccountUser, roles/config.agent, and roles/iam.serviceAccountTokenCreator.

The impact for operations teams is that every Terraform run is auditable to the service account principal in Cloud Audit Logs. The contextual connection to Terraform is that the provider google must authenticate as this identity to read current state, plan changes, and apply them.

Creating a Service Account with gcloud CLI

Creation is performed with gcloud iam service-accounts create.

Before creation, set the target project.

bash export PROJECT_ID="my-project-123" gcloud config set project $PROJECT_ID

Create the service account with display name and description.

bash gcloud iam service-accounts create terraform \ --display-name="Terraform Service Account" \ --description="Used by Terraform to manage GCP infrastructure"

Verify creation.

bash gcloud iam service-accounts list

The command creates a service account principal that is now ready for role assignment. The display name and description provide human readable metadata for IAM reviews. Verification ensures the principal exists before bindings are added.

Assigning Roles and IAM Bindings

Grant the service account the permissions it needs.

A broad access example for initial setup not recommended for production:

bash gcloud projects add-iam-policy-binding $PROJECT_ID \ --member="serviceAccount:terraform@${PROJECT_ID}.iam.gserviceaccount.com" \ --role="roles/editor"

For a general-purpose Terraform service account, you might use the Editor role during initial setup and tighten it later.

A more specific example includes:

bash --role="roles/cloudsql.admin"

Grant access to the service account for Infra Manager usage. To use Infrastructure Manager to create, update, or delete a deployment, an individual user needs access to the service account.

bash gcloud projects add-iam-policy-binding INFRA_MANAGER_PROJECT_ID \ --member="serviceAccount:SERVICE_ACCOUNT_EMAIL" \ --role="roles/iam.serviceAccountUser"

Grant permissions for Infra Manager. To work with Infra Manager, the service account needs the Infra Manager Agent role.

bash gcloud projects add-iam-policy-binding INFRA_MANAGER_PROJECT_ID \ --member="serviceAccount:SERVICE_ACCOUNT_EMAIL" \ --role="roles/config.agent"

This grants permissions for Infra Manager to create, update, and delete resources.

Cross-project setup for Cloud Build execution requires Service Account Token Creator on the Cloud Build service agent.

bash gcloud projects add-iam-policy-binding SERVICE_ACCOUNT_PROJECT_ID \ --member="serviceAccount:service-INFRA_MANAGER_PROJECT_NUMBER@gcp-sa-cloudbuild.iam.gserviceaccount.com" \ --role="roles/iam.serviceAccountTokenCreator"

The service agent email forms as service-INFRAMANAGER[email protected].

For Terraform managing Cloud Functions, the service account that Terraform uses needs appropriate permissions. Prerequisites include permissions to create resources that depends on what exactly is in the Terraform code.

Required IAM permissions include:

  • resourcemanager.projects.getIamPolicy
  • resourcemanager.projects.setIamPolicy
    for setting project-level policies
  • secretmanager.secrets.getIamPolicy
  • secretmanager.secrets.setIamPolicy
    to use googlesecretmanagersecretiam_member
  • Potentially other permissions that end with *.setIamPolicy for resource-level policies.

The impact layer is that overprivileged service accounts increase blast radius. The contextual layer connects role binding to the provider authentication method and to the principle of least privilege.

Authentication Methods for Terraform Google Provider

There are several ways to authenticate Terraform with the service account.

The choice affects credential lifecycle, security posture, and operational complexity.

| Method | Credential Storage | Rotation Burden | Suitable Environment |
| Method 1 - Service Account Key File | JSON key file on disk | Manual or automated key rotation | Local development, on-prem |
| Environment Variable GOOGLECREDENTIALS | Process environment | Per session | CI/CD pipelines |
| Environment Variable GOOGLE
APPLICATION_CREDENTIALS | File path reference | File lifecycle | Local ADC |
| Service Account Impersonation | No long-lived key | Token lifetime limited | Secure production |
| Workload Identity Federation | External identity | Federation trust | Cross-cloud |

Service Account Key File Method

Generate a JSON key and point Terraform at it.

Create and download a key file.

bash gcloud iam service-accounts keys create terraform-key.json \ --iam-account="terraform@${PROJECT_ID}.iam.gserviceaccount.com"

The file contains private key material - handle it securely.

bash chmod 600 terraform-key.json

Provider configuration with explicit credentials file.

bash provider "google" { project = var.project_id region = "us-central1" credentials = file("terraform-key.json") }

Important security note: Service account keys are long-lived credentials. Long-lived keys increase exposure window if leaked. Key files must be stored in secret management systems and access restricted.

Environment Variable Credential Injection

Set the credentials via environment variable.

bash export GOOGLE_CREDENTIALS=$(cat terraform-key.json)

Or point to the file path.

bash export GOOGLE_APPLICATION_CREDENTIALS="/path/to/terraform-key.json"

Provider configuration without credentials in code.

bash provider "google" { project = var.project_id region = "us-central1" }

The provider reads from GOOGLECREDENTIALS or GOOGLEAPPLICATION_CREDENTIALS. This approach keeps secrets out of version control. The impact is reduced accidental commit risk. The contextual layer is that CI systems can inject the variable at runtime without persisting the key in image layers.

Service Account Impersonation and ADC

Authenticate using service account impersonation.

You can use service account impersonation to set up a local ADC file. Terraform uses those credentials automatically.

Make sure you must have the Service Account Token Creator role on the service account you are impersonating.

Use service account impersonation to create a local ADC file by running the following command:

bash gcloud auth application-default login --impersonate-service-account SERVICE_ACCT_EMAIL

After you sign in, your credentials are stored in the local credential file used by ADC.

When running Terraform on a Google Cloud cloud-based development environment such as Cloud Shell, the tool uses the credentials you provided when you signed in for authentication.

When using Terraform with Google Cloud services such as Compute Engine, App Engine, and Cloud Run functions, you can attach a user-managed service account to resources. Generally, attaching a service account is supported when that service's resources can run or include application code.

If you want to allow users to use a shared primary authentication source and a variable service account per environment, set the impersonateserviceaccount field in your Terraform configuration file:

bash provider "google" { impersonate_service_account = "SERVICE_ACCT_EMAIL" }

Impersonation eliminates long-lived key storage. Tokens are short lived. The user must have roles/iam.serviceAccountTokenCreator on the target service account.

Terraform Configuration Examples for Authentication

Provider with explicit credentials file.

bash provider "google" { project = var.project_id region = "us-central1" credentials = file("terraform-key.json") }

Provider with impersonation.

bash provider "google" { impersonate_service_account = "SERVICE_ACCT_EMAIL" }

Provider relying on Application Default Credentials.

bash provider "google" { project = var.project_id region = "us-central1" }

Authentication when running Terraform on Google Cloud uses the credentials you provided when you signed in.

Authenticate to Cloud Storage backends. Terraform lets you configure Cloud Storage as a backend to store Terraform state files. To authenticate to a Cloud Storage backend, use any of the methods described on this page.

Create a credential configuration file and set the GOOGLEAPPLICATIONCREDENTIALS environment variable to point to it. This approach is more secure than creating a service account key. For instructions on setting up Workload Identity Federation for ADC, see Workload Identity Federation with other clouds.

Authenticate using service account keys when running Terraform in a local development environment, on premises, or a different cloud provider. You can create a service account, grant it the IAM roles that your application requires, and create a key for the service account.

To create a service account key and make it available to ADC:

Create a service account with the roles your application needs, and a key for that service account, by following the instructions in Creating a service account key.

Permissions Summary for Common Scenarios

| Scenario | Required Role / Permission |
| Infra Manager Agent | roles/config.agent |
| Service Account User access | roles/iam.serviceAccountUser |
| Service Account Token Creator | roles/iam.serviceAccountTokenCreator |
| Project level policy management | resourcemanager.projects.getIamPolicy, resourcemanager.projects.setIamPolicy |
| Secret Manager IAM | secretmanager.secrets.getIamPolicy, secretmanager.secrets.setIamPolicy |
| Cloud SQL admin | roles/cloudsql.admin |
| Editor for initial setup | roles/editor |

Security Considerations

Service account keys are long-lived credentials. Rotate keys regularly and revoke unused keys. Avoid embedding credentials in code. Prefer impersonation and Workload Identity Federation. For instructions on setting up Workload Identity Federation for ADC, see Workload Identity Federation with other clouds.

Grant read permission for the storage bucket you can use a storage bucket to store the Terraform configurations that are deployed by Infra Manager. If you use a storage bucket to store the Terraform configurations that are deployed by Infra Manager.

Contextual Connections

The service account used by Terraform to manage Cloud Functions must have permissions to create resources that depends on what exactly is in the Terraform code. The hashicorp/google Terraform provider has to be used. The service account that Terraform uses needs to have appropriate permissions.

We have a system that’s based on Google Cloud Platform. Some of the logic is built using Cloud Functions and Firebase. We use Terraform for managing our infrastructure.

Infra Manager executes Terraform using the identity of this service account. You do not need a service account to view information about Infra Manager deployments.

When running Terraform with Google Cloud services such as Compute Engine, App Engine, and Cloud Run functions, you can attach a user-managed service account to resources.

Conclusion

Terraform service account configuration in Google Cloud centers on creating a dedicated non-human principal, binding least privilege IAM roles, and choosing an authentication method that matches the execution environment. Creating the service account with gcloud iam service-accounts create establishes the identity. Assigning roles such as roles/editor for initial bootstrap, roles/cloudsql.admin for database management, roles/iam.serviceAccountUser for user access, roles/config.agent for Infra Manager, and roles/iam.serviceAccountTokenCreator for impersonation controls the blast radius. Authentication can be performed via a JSON key file passed through credentials = file(), via GOOGLECREDENTIALS or GOOGLEAPPLICATIONCREDENTIALS environment variables, or via service account impersonation with gcloud auth application-default login --impersonate-service-account and provider impersonateservice_account. Long-lived keys present security risk and should be avoided in production in favor of impersonation and Workload Identity Federation. The service account that Terraform uses for Cloud Functions needs resourcemanager.projects.getIamPolicy and setIamPolicy, secretmanager.secrets.getIamPolicy and setIamPolicy, and potentially other *.setIamPolicy permissions. Infra Manager requires the Infra Manager Agent role and cross-project Service Account Token Creator grants for Cloud Build execution. These patterns together enable secure, auditable, and least-privilege Terraform automation against Google Cloud.

Sources

  1. How to configure GCP provider with service account
  2. How to define a service account for GCP Cloud Functions using Terraform
  3. Configure service account for Infrastructure Manager
  4. Terraform authentication for Google Cloud

Related Posts