Secure way to store API token in gitlab

Viewed 811

I am working on this small terraform project that uses gcp (google cloud platform) token.json which contains secure credentials to create resources.

Terraform files are executed by the Gitlab CI/CD.

My concern is, this token.json is used by the one of the terraform files (main.tf) as below.

# Configure the backend
terraform {
  backend "gcs" {
    bucket      = "tf_backend_gcp_banuka_jana_jayarathna_k8s"
    prefix      = "terraform/gcp/boilerplate"
    credentials = "./token.json" ----> file I need to keep securely
  }
}

This token.json is in the root folder with the main.tf file above.

This file is needed for that file and I can't think of any other way how I can store this. This token cannot even put to gitlab variables as there is no way to pass the values of the token to this main.tf file when the pipeline runs.

I don't want to expose the token.json to public too. Is there a way I can achieve this in Gitlab? Can't even use a tool like git-crypt because then how can I decrypt this token.json and feed it to the main.tf...

Is there a way to inject variables to terraform files ?

Thank you

3 Answers

You can base64 encode the file and put it into a GitLab CI variable.

cat token.json | base64

And then you can decode it and create the file before you run terraform apply

terraform-apply:
  stage: deploy
  script:
    - echo $GCE_TOKEN | base64 -d > token.json
    - terraform apply 
  • Store the token as a variable in GitLab (Settings -> CI/CD -> Variables), make sure to enable masking.
  • Define a variable for the token in your terraform manifests.
  • Supply the token variable to terraform when you run apply.

variables.tf

variable "gce_token" {
  type = string
}

main.tf

  terraform {
    backend "gcs" {
      bucket      = "tf_backend_gcp_banuka_jana_jayarathna_k8s"
      prefix      = "terraform/gcp/boilerplate"
      credentials = var.gce_token
    }
  }

.gitlab-ci.yml

  terraform apply -var="gce_token=$GCE_TOKEN"

After a while, when I was working on the same thing, I encounter the same problem and I found a solution.

We can put AWS access-key and secret-key in Gitlab CI Variables and we can export them before terraform init or terraform apply or any terraform command:

  before_script:
    - export AWS_ACCESS_KEY_ID=${access_key}
    - export AWS_SECRET_ACCESS_KEY=${secrect_key}
Related