1
votes

I have below terraform script, to create a new service account and make it owner. The scripts creates the service account, but it will throw an error on assigning role

resource "google_service_account" "pci_api_service_account" {
  account_id   = "pci-api"
  display_name = "Api"
  project      = var.project_id
}

resource "google_service_account_iam_member" "pci_api_owner_binding" {
  # service_account_id = "projects/pcb-poc-pci/serviceAccounts/[email protected]"
  service_account_id = google_service_account.pci_api_service_account.name
  role   = "roles/owner"
  member = "serviceAccount:${google_service_account.pci_api_service_account.email}"
  depends_on = [
    google_service_account.pci_api_service_account
  ]
}

and I already autheticated with infra-admin-sa service account by running

gcloud auth activate-service-account --project=pcb-poc-pci --key-file ~/sa/pcb-poc-pci-test-sa-94aa6c81d650.json

When I run terragrunt apply I get this error for the second script

Error: Error applying IAM policy for service account 'projects/pcb-poc-pci/serviceAccounts/[email protected]': Error setting IAM policy for service account 'projects/pcb-poc-pci/serviceAccounts/[email protected]': googleapi: Error 403: Permission iam.serviceAccounts.setIamPolicy is required to perform this operation on service account projects/pcb-poc-pci/serviceAccounts/[email protected]., forbidden

These are the Roles of that service account enter image description here

Based on google doc here and the error message, Service Account Admin should be enough, which my service account already have

enter image description here

Not sure what I missed

1

1 Answers

1
votes

Solution 1

seems command line was not picking the correct credential/service account although I used gcloud auth activate-service-account command.

so I added this to my script

provider "google" {
  credentials = file(var.service_account_file_path)
  project     = var.project_id
}

and now it's working fine

Solution 2

as per @John Hansley comments below

export GOOGLE_APPLICATION_CREDENTIALS=fullpath.json

then terraform will be picking that service account file and scripts will run successfully.

This method is preferred since less issue in CICD pipeline and other deveopers, to set terraform variables