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.
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.
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: