Gitlab CI — extract environment variables from terraform definition variables

Turhan Oz
2 min readJun 17, 2022

Gitlab offers multiple ways to define environment variables to be used in your cicd pipelines.

One of hight interest is the project variables, where you can define environment variables as a File.

That is useful for instance when we store Terraform variables definition (*.tfvars) with the gitlab project environment variables as a whole File.

Terraform variable definition is mainly composed of key=”value” list, as follow :

...
aws_region = "eu-west-1"
aws_profile = "default"
instance_name = "develop-rc1"
...

Let’s add this terraform variables definition as a FILE environment variables in Gitlab Project Settings and call this FILE environment variable AUTO_TERRAFORM_VARS

Terraform variables defined as Gitlab Environment variable

Now suppose we want to use the value of a given key (instance_name) from this FILE environment variable inside our cicd pipeline.

To do so, we will use the script block for a given job defined in our gitlab-ci.yml and extract the value we need thanks to simple bash commands, so we can use this value as an input for upcoming scripts.

job-name:
image: ...
stage: quality
only:
- production
- develop
script:
- export INSTANCE_NAME=`cat $AUTO_TERRAFORM_VARS…

--

--