aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • DevOps
  • Engineering

Using Google Cloud Service Account Impersonation In Your Terraform Code

  • aster.cloud
  • December 10, 2021
  • 4 minute read

Terraform is one of the most popular open source infrastructure-as-code tools out there, and it works great for managing resources on Google Cloud.  When you’re just kicking the tires and learning how to use Terraform with Google Cloud, having the owner role on the project and running Terraform yourself makes things very easy.  That’s because with unlimited permissions, you can focus on understanding the syntax and functionality without getting distracted by any issues caused by missing IAM permissions.

However, once you’re past that, or if it’s just not possible in the project you’re working from, it’s a good idea to limit your own permissions and get into the habit of running your Terraform code as one or more service accounts with just the right set of IAM roles.  A service account is a special kind of account that is typically used by applications and virtual machines in your Google Cloud project to access APIs and services.  Applications and users can authenticate as a service account using generated service account keys.


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

The downside to this approach is that it creates a security risk as soon as the key is generated and distributed. Any user with access to a service account key, whether authorized or not, will be able to authenticate as the service account and access all the resources for which the service account has permissions.  Fortunately, there’s another way to run Terraform code as a service that’s generally safer – service account impersonation.

Creating resources as a service account

To begin creating resources as a service account you’ll need two things. First, you’ll need a service account in your project that you’ll use to run the Terraform code.  This service account will need to have the permissions to create the resources referenced in your code. Second,  you’ll need to have the Service Account Token Creator IAM role granted to your own user account.  This role enables you to impersonate service accounts to access APIs and resources.  The IAM role can be granted on the project’s IAM policy, thereby giving you impersonation permissions on all service accounts in the project. However, if you’re adhering to the principle of least privilege, the role should be granted to you on the service account’s IAM policy instead.

Read More  Building The Most Open And Extensible Platform For Hybrid Work

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

 

After that, any Terraform code you run in your current terminal session will use the service account’s credentials instead of your own.  It’s a quick and easy way to run Terraform as a service account, but of course, you’ll have to remember to set that variable each time you restart your terminal session. You’ll also be limited to using just one service account for all of the resources your Terraform code creates.

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.  First, set a local variable to the service account email:

locals {
 terraform_service_account = "YOUR_SERVICE_ACCOUNT@YOUR_PROJECT.iam.gserviceaccount.com"
}

 

You can also set this variable by writing a variable block and setting the value in the terraform.tfvars file.  Either way works fine.  Next, create a provider that will be used to retrieve an access token for the service account. The provider is “google” but note the “impersonation” alias that’s assigned to it:

provider "google" {
 alias = "impersonation"
 scopes = [
   "https://www.googleapis.com/auth/cloud-platform",
   "https://www.googleapis.com/auth/userinfo.email",
 ]
}

 

Next, add a data block to retrieve the access token that will be used to authenticate as the service account.  Notice that the block references the impersonation provider and the service account specified above:

Read More  How-To: Install and Configure MongoDB Community on Ubuntu 20.04
data "google_service_account_access_token" "default" {
 provider               	= google.impersonation
 target_service_account 	= local.terraform_service_account
 scopes                 	= ["userinfo-email", "cloud-platform"]
 lifetime               	= "1200s"
}

 

And finally, include a second “google” provider that will use the access token of your service account. With no alias, it’ll be the default provider used for any Google resources in your Terraform code:

provider "google" {
 project 		= YOUR_PROJECT_ID
 access_token	= data.google_service_account_access_token.default.access_token
 request_timeout 	= "60s"
}

 

Now, any Google Cloud resources your Terraform code creates will use the service account instead of your own credentials without the need to set any environment variables. With this method, you also have the option of using more than one service account by specifying additional provider blocks with unique aliases.

Updating remote state files with a service account

When you run Terraform code, it keeps track of the Google Cloud resources it manages in a state file. By default, the state file is generated in your working directory, but as a best practice the state file should be kept in a GCS bucket instead.  When you specify a backend, you need to provide an existing bucket and an optional prefix (directory) to keep your state file in.  If this bucket exists but your user account doesn’t have access to it, a service account that does have access can be used instead.

Once again, you’ll need the Service Account Token Creator role granted via the service account’s policy.  This service account can be different from the one you’ll use to execute your Terraform code. Specifying the service account here is as simple as adding the impersonate_service_account argument to your backend block:

terraform {
 backend "gcs" {
   bucket                      = "GCS_BUCKET_NAME"
   prefix                      = "OPTIONAL_PREFIX" 
   impersonate_service_account = "YOUR_SERVICE_ACCOUNT@YOUR_PROJECT.iam.gserviceaccount.com"
 }
}

 

Read More  2021 Accelerate State Of DevOps Report Addresses Burnout, Team Performance

With this one argument added to your backend block, a service account will read and update your state file when changes are made to your infrastructure, and your user account won’t need any access to the bucket, only to the service account.

The advantages of impersonation

The methods above don’t require any service account keys to be generated or distributed.  While Terraform does support the use of service account keys, generating and distributing those keys introduces some security risks that are minimized with impersonation.  Instead of administrators creating, tracking, and rotating keys, the access to the service account is centralized to its corresponding IAM policy.  By using impersonation, the code becomes portable and usable by anyone on the project with the Service Account Token Creator role, which can be easily granted and revoked by an administrator.

 

 

By: Roger Martinez (Cloud Developer Advocate)
Source: Google Cloud Blog


For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

aster.cloud

Related Topics
  • Google Cloud
  • Terraform
You May Also Like
Points, Lines and a Question
View Post
  • Architecture
  • Design
  • Engineering
  • People

What Is The Point In Making Points?

  • November 26, 2025
View Post
  • Engineering
  • Software Engineering

Development gets better with Age

  • October 9, 2025
Users with laptops working with database. Data storage and organization, information access and management, big data protection concept. Vector isolated illustration.
View Post
  • Architecture
  • DevOps
  • Technology

What is application migration? Examples and best practices

  • August 18, 2025
View Post
  • Engineering
  • Technology

Apple supercharges its tools and technologies for developers to foster creativity, innovation, and design

  • June 9, 2025
View Post
  • Engineering

Just make it scale: An Aurora DSQL story

  • May 29, 2025
View Post
  • Engineering
  • Technology

Guide: Our top four AI Hypercomputer use cases, reference architectures and tutorials

  • March 9, 2025
View Post
  • Computing
  • Engineering

Why a decades old architecture decision is impeding the power of AI computing

  • February 19, 2025
View Post
  • Engineering
  • Software Engineering

This Month in Julia World

  • January 17, 2025

Stay Connected!
LATEST
  • 1
    Expectations vs. Reality: The AI We Thought We’d Have in 10 Years
    • June 19, 2026
  • digital-nomad-freelancer-worker-2151205464 2
    One paperwork problem – Get your Digital Nomad Visa employment documents fast from UK, EU or Singapore
    • June 16, 2026
  • 3
    Samsung Art Store Brings Art Basel to Homes Worldwide With New Curated Collection
    • June 15, 2026
  • 4
    You Do Not Need to Invest in the IPO of SpaceX, Anthropic, and OpenAI
    • June 10, 2026
  • 5
    The consequences of relying on AI for accurate news
    • June 10, 2026
  • 6
    Connecting AI agents with unstructured data using Google Cloud Storage MCP Servers
    • June 10, 2026
  • 7
    WWDC26: Apple unveils next generation of Apple Intelligence, Siri AI, powerful parental controls, and an expansive set of software improvements
    • June 8, 2026
  • 8
    IBM and Google Cloud Announce Strategic Partnership to Scale AI with Human Expertise and AI‑Powered Delivery
    • June 4, 2026
  • Data center 9
    Data Sovereignty in Spain. It’s Not Just About the Law, It’s About Efficiency
    • June 3, 2026
  • 10
    Ink vs Pixels. What you miss versus what you are actually missing.
    • June 1, 2026
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • 1
    Banks race to patch new cyber vulnerabilities, and other cybersecurity news
    • May 25, 2026
  • pope-leo-xiv-cq5dam-1500.844 2
    Pope Leo XIV to Publish First Encyclical on Artificial Intelligence and Human Dignity on 25 May
    • May 22, 2026
  • 3
    Portfolio to Clients, and is Strengthened by Ongoing Project Glasswing Work
    • May 20, 2026
  • reMarkable Paper Pure 4
    Everything The reMarkable Paper Pure Actually Does
    • May 14, 2026
  • 5
    Scaling cloud and AI: Microsoft Azure’s commitment to Europe’s digital future
    • May 11, 2026
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.