Service Account impersonation


To run Terraform locally, you need to use a service account using either a key file or service account impersonation.

Managing key files poses a security risk. Key files are not automatically rotated and hence tend to be long-lived. Even if your organization manually rotates key files, they then need to be distributed, which introduces considerable overhead.

provider "google" {
  project     = <PROJECT_ID>
  region      = "us-central1"
  zone        = "us-central1-c"
  credentials = "./terraform.json"
}

Using service account impersonation eliminates the risk associated with generating and distributing service account keys. Service account impersonation also makes code more portable as it does not depend on any external file

When the principal you are using doesn’t have the permissions you need to accomplish your task, or you want to use a service account in a development environment, you can use service account impersonation.

When you use service account impersonation, you start with an authenticated principal (your user account or a service account) and request short-lived credentials for a service account that has the authorization that your use case requires. The authenticated principal must have the necessary permissions to impersonate the service account.

Service account impersonation is more secure than using a service account key because service account impersonation requires a prior authenticated identity, and the credentials that are created by using impersonation do not persist. In comparison, authenticating with a service account key requires no prior authentication, and the persistent key is a high risk credential if exposed.

Once you have a service account and the Service Account Token Creator role, you can impersonate service accounts in Terraform in two ways: set an environment variable to the service account’s email or add an extra provider block in your Terraform code.

For the first method, set the GOOGLE_IMPERSONATE_SERVICE_ACCOUNT environment variable to that service account’s email. For example:

export GOOGLE_IMPERSONATE_SERVICE_ACCOUNT=YOUR_SERVICE_ACCOUNT@YOUR_PROJECT.iam.gserviceaccount.com

For the second method, you will need to add a few blocks into your Terraform code (preferably in the provider.tf file) that will retrieve the service account credentials.