is there any way to add a service account automatically whenever a project is created?

801 views Asked by At

I have several projects under an organization in GCP.I have an service account with certain scopes set on a project (for automation).I wanted to add the same service account to all other projects as an member, I did manually until now.

is there any way I can automate this, like whenever a project is created the service account along with its scopes should be added as its member?

2

There are 2 answers

0
guillaume blaquiere On

It's the purpose of the ressource hierarchy. Create a service account (in a project, a service account can only live in a project) and then grant it at the organization or the folder level; with the permission that you want

But be careful, the permission will be the same for all the child resources and you haven't the possibility to deny these permissions (at least, for now!). See IAM Policy Inheritance

0
Maxim On

If you're using Terraform to create the projects the idea would remain the same. Just as for creating projects in GCP, there's an equivalent gcloud command and a REST API behind it. The gcloud command specifically would be gcloud projects add-iam-policy-binding:

gcloud projects add-iam-policy-binding example-project-id-1 \
--member='serviceAccount:[email protected]' \
--role='roles/editor'

Here's a Terraform example you can use:

resource "google_project_iam_binding" "project" {
  project = "your-project-id"
  role    = "roles/editor"

  members = [
    "serviceAccount:[email protected]",
  ]
}
  1. Create a main.tf file or anything else you want to call the Terraform config file.
  2. Replace [email protected] with your Service Account, roles/editor with the role you want to give it and your-project-id with your Project ID.
  3. Authenticate with ADC i.e or any other way you prefer and run terraform apply in the same directory the Terraform config file is at.

I think you could even use Ansible for that. Or if you really want to, create a Bash script.