Christoffer
Christoffer

Reputation: 2411

GCP "omnipotent" Service Account to create multiple services through Terraform

I am running an application using some 4-5 services on GCP, I have done it mainly to learn some new skills (including GCP) and it is not a commercial application so I run it on free credits, create a new account, transfer the database and run it there. Rinse and repeat.

Lately, I have been trying to learn Terraform and as such I try to create and configurate my services (such as setting up an SQL database with the right configuration, creating a Cloud Run-service with env variables etc). In order to do so, I am constantly running into permission issues if I e.g. use the Compute Engine-service account (which works fine if everything is already created!).

How should I create an "omnipotent" service account that I can use as a SA for my terraform creation of my GCP environment from scratch. The SA does not in itself need to be created through Terraform (although that would be neat). All I want is a SA that I can create, download and reference the JSON, and create all my GCP services.

Is it possible?

Upvotes: 1

Views: 339

Answers (2)

Maciej Rostański
Maciej Rostański

Reputation: 405

Of course this is possible.

The operations you need to perform:

  • Create Service Account in GCP console
  • Use IAM & Admin -> Service Accounts -> Create Service Account
  • Name it whatever you like, e.g. "terraform"
  • In "Grant this service account access to the project" select "Owner" basic role.
  • When created, click this account on the list and open "keys" tab.
  • Use "add key -> create new key"
  • Download the json and voila, you can use it in terraforming.

Note that you can use this json filein two ways:

  1. Directly in the code (provider credentials argument) - the code would look like this:
provider "google" {
  credentials = file(var.credentials) # var.credentials is a path to the JSON keys
  project     = var.project
  region      = var.region
}
  1. or you can run terraform while having GOOGLE_APPLICATION_CREDENTIALS environment variable set to the path to this file.

Upvotes: 1

al-dann
al-dann

Reputation: 2725

I don’t know details of your context, scope, requirements and restrictions. So my personal experience only.

I use a Cloud Build service and it’s build in service account.

That service account should be granted relevant permissions (I.e. an owner role) in proper projects. That is a “precondition”.

Then, I create a cloudbuild.yaml file in which I initialise and apply a terraform job.

Note: the terraform state file is stored in a GCS bucket. So, that is to be prepared as well.

Here is an example of a part of the cloudbuild.yaml file: Terraform and Cloud Build

Upvotes: 1

Related Questions