The idea of GCP service account impersonation is to run and deploy Terraform infrastructure without the need of using service account keys as it introduces security risks along the way – not rotating keys frequently enough and hardcoding them being only part of the problem.
To minimize the threat, impersonation can be done in a couple of not so simple steps which I’ll try to explain it briefly.
Prerequisites
- GCP account
- Terraform
Solution
First things first, the concept can be boiled down to two things:
- A low privilege account (your own account) that will impersonate the high privilege account by using access tokens.
- A high privilege account (service account) that has enough permissions to deploy the TF infra, by following the least privilege best practices.
Step 1. Before removing your Owner IAM role from the project, make sure to create a service account per GCP project with sufficient permissions. This could be done by applying predefined or custom organization, billing, folder and project roles as part of the IAM policies.
To start with, the best bet will be to google for the following TF resources: google_organization_iam
and google_project_iam
and apply accordingly.
For instance, adding the Folder Creator
org IAM role to a service account would look like:
## variables.tf
variable "org_id" {
description = "Google Organization ID."
type = string
}
## terraform.tfvars
org_id = "<some_org_id>"
## main.tf
resource "google_organization_iam_binding" "folder_creator" {
org_id = var.org_id
role = "roles/resourcemanager.folderCreator"
members = [
"serviceAccount:[email protected]",
]
}
Step 2. Allow your user account to generate a token for the high privilege service account. Example code snippet:
## main.tf
resource "google_service_account_iam_member" "this" {
service_account_id = google_service_account.this.name
role = "roles/iam.serviceAccountTokenCreator"
member = "user:[email protected]"
}
Step 3. For the rest of the TF configuration, check out the official Using Google Cloud Service Account impersonation in your Terraform code docs.
Conclusion
Security-wise few key advantages:
- No need to manage service account keys (generate, distribute, rotate).
- Code is portable and usable by anyone having the
roles/iam.serviceAccountTokenCreator
IAM role. - Short-lived access tokens.
Any questions, thoughts and opinions are much appreciated. On a side note, follow our official channel on Telegram.