Search code examples
google-cloud-platformterraformgoogle-iamterraform-provider-gcp

Want to assign multiple Google cloud IAM roles to a service account via terraform


I want to assign multiple IAM roles to a single service account through terraform. I prepared a TF file to do that, but it has an error. With a single role it can be successfully assigned but with multiple IAM roles, it gave an error.

data "google_iam_policy" "auth1" {
  binding {
    role = "roles/cloudsql.admin"
    members = [
      "serviceAccount:${google_service_account.service_account_1.email}",
    ]    
    role = "roles/secretmanager.secretAccessor"
    members = [
      "serviceAccount:${google_service_account.service_account_1.email}",
    ]      
    role = "roles/datastore.owner"
    members = [
      "serviceAccount:${google_service_account.service_account_1.email}",
    ]  
    role = "roles/storage.admin"
    members = [
      "serviceAccount:${google_service_account.service_account_1.email}",
    ]      
  }
}

How can I assign multiple roles against a single service account?


Solution

  • According with the documentation

    Each document configuration must have one or more binding blocks, which each accept the following arguments: ....

    You have to repeat the binding, like this

    data "google_iam_policy" "auth1" {
      binding {
        role = "roles/cloudsql.admin"
        members = [
          "serviceAccount:${google_service_account.service_account_1.email}",
        ]
      }
      binding {
        role = "roles/secretmanager.secretAccessor"
        members = [
          "serviceAccount:${google_service_account.service_account_1.email}",
        ]
      }
      binding {
        role = "roles/datastore.owner"
        members = [
          "serviceAccount:${google_service_account.service_account_1.email}",
        ]
      }
      binding {
        role = "roles/storage.admin"
        members = [
          "serviceAccount:${google_service_account.service_account_1.email}",
        ]
      }
    }
    

    It's the same thing with you use the gcloud command, you can add only 1 role at the time on a list of email.