Search code examples
terraformgithub-actions

Terraform Init from Github Actions


I'm trying to call terraform init from Github actions. I'm using the Google provider which includes the block:

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

When I run this locally, its fine because the creds.json (service account key json) is there, but I don't want to have that key checked out as part of the repo in GHA. Instead the json for the key is added as a secret: ${{ env.GCP_CREDENTIALS }}

How do I get Terraform to use that secret in the 'terraform init' command? I tried changing the line to:

provider "google" {
  credentials = ${{ env.GCP_CREDENTIALS }}
  project     = var.project
  region      = var.region
  zone        = var.zone
}

But it just errors out. There must be a simpler way?


Solution

  • The environment variable must point to a file which is the location for a service account JSON key. You could write the contents to an artifact, but that is dangerous. . Still, a simple workaround to this would be:

    If you want to place your credentials in a Terraform Cloud environment variable:

    • Create an environment variable called GOOGLE_CREDENTIALS in your Terraform Cloud workspace.
    • Remove the newline characters from your JSON key file and then paste the credentials into the environment variable value field. You can use the tr command to strip newline characters. cat key.json | tr -s '\n' ' '
    • Mark the variable as Sensitive and click Save variable.

    Alternative:

    You can use this GitHub action to log in. Pretty much you have to create a secret with the content of the service account and specified it as input:

    - id: 'auth'
      name: 'Authenticate to Google Cloud'
      uses: 'google-github-actions/auth@v0'
      with:
        credentials_json: '${{ secrets.GOOGLE_CREDENTIALS }}