Using Service Account Impersonation With Terraform

Posted on Oct 10, 2021, on my blog https://blog.chy.la/posts/using-service-account-impersonation-with-terraform/

tl;dr: Setup two service accounts, a high privilege and a low privilege one. Allow low privilege to impersonate the high privilege as the only role. Create a token using a Terraform data source, pass the token to the primary provider while you run Terraform using the low privilege account.

Introduction

Account impersonation is an often overlooked or even unknown capability of Terraform that adds a layer of protection and allows for better monitoring and restrictions for the high privilege account that you usually use to deploy infrastructure with Terraform. In this article, I would like to give you a quick overview of the capability and one way of using it.

Setup

The following section focuses on the Google Cloud Platform. The idea is to use two accounts, low and high privilege.

  • low privilege account that can impersonate the high privilege account
  • high privilege that has the permissions to deploy the infrastructure

The following script creates the two accounts and the necessary permissions for impersonation.

Note

If you have Terraform runners on GCP, use the low privilege account to run the compute engine resources this way you do not have to pass any additional credentials to Terraform. Ensure that the low privilege account can write to the GCS bucket if that is your remote backend of choice.

setup-account-chain.sh

Next is the Terraform file that handles the credential generation. Using two providers and data sources and passing the

For external runners, generate credentials for the terraform-doorman (low privilege) account and pass them to Terraform while having the following configuration for your provider.

provider.tf

DevSecOops