Search code examples
google-cloud-platformterraformservice-accounts

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?


Solution

  • 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.