Search code examples
terraformterraform-provider-gcpterraform-cloud

How to store GCP Service Account JSON in a terrafrom variable?


My terraform gcp provider config looks like

provider "google" {
  project     = var.project
  region      = var.region
  credentials = file("account.json")
}

I want to run my terraform file on terraform cloud and I don't want want to put the account.json file in source control. How can I store the json GCP service account file in terraform cloud and then access it from the terraform script?


Solution

  • You can supply the credentials as an Multi-Line value called google_credentials in the Terraform Cloud UI and mark it as a Sensitive Value and enter something like this with the correct values for your account (likely just a copy paste of your account.json file you have already):

    {
      "type": "service_account",
      "project_id": "project-id",
      "private_key_id": "key-id",
      "private_key": "-----BEGIN PRIVATE KEY-----\nprivate-key\n-----END PRIVATE KEY-----\n",
      "client_email": "service-account-email",
      "client_id": "client-id",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "token_uri": "https://accounts.google.com/o/oauth2/token",
      "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
      "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account-email"
    }
    

    You can then provide the credentials from the workspace variable to your google provider in your Terraform module as follows as a single variable which will be interpreted as JSON:

    provider "google" {
      project     = var.project
      region      = var.region
      credentials = var.google_credentials
    }
    
    variable "google_credentials" {
      description = "the contents of a service account key file in JSON format."
      type = string
    }
    

    credentials - (Optional) Either the path to or the contents of a service account key file in JSON format. You can manage key files using the Cloud Console.

    From Google Provider Configuration Reference.