Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Terraform deployment using GCP service account

Hi,

I'm trying to do terraform deployment to my GCP project using a service account key file.I have the key file and made reference in terraform provider.tf as shown below:

 

provider "google" {
  version = "4.39.0"
  credentials = file("./terraform-sa.json")
  project = var.project_id
  region = var.region
  zone = var.zone
}

 

 
On terraform plan, I'm getting the following error:

 

│ Error: Error when reading or editing Instance Template "vm-template": Get "https://compute.googleapis.com/compute/beta/projects/dev-test/global/instanceTemplates/12345678?alt=json&prettyPrint=false": oauth2: "invalid_grant" "reauth related error (invalid_rapt)" "https://support.google.com/a/answer/9368756"
│
│ with module.vm-template.google_compute_instance_template.default[0],
│ on .terraform/modules/vm-template/modules/compute-vm/main.tf line 259, in resource "google_compute_instance_template" "default":
│ 259: resource "google_compute_instance_template" "default" {
│

 

My service account currently has 'Editor' role.
Please let me know how I can fix this? 
 
Regards,
Akhil
0 1 1,145
1 REPLY 1

Hi There,

It's better to use impersonation so you don't have to store service account keys that increases the attack surface. Here's an example:

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

My second suggestion is to really consider following the Google Security Foundation, they have the terraform-example-foundation github available which provides a proper landing zone structure which creates the core service accounts that you can use with the predefined fine-grained roles. Here - https://github.com/terraform-google-modules/terraform-example-foundation

You also might want to consider away from the old IAM roles, but that would be secondary.