Programster's Blog

Tutorials focusing on Linux, programming, and open-source

GitLab - Add Pipeline Variable

Go to your project's repository and click settings (1), then CI/CD (2). Then click on the Expand button (3) by the Variables header.


The section will expand to show the names of existing variables. Click the Add Variable button in order to add a new variable.


Add Variable Modal

Fill in the name (1) and value (2) for the variable.

Most of the time, you will want to leave the type (3) as variable for it to just be treated as setting an environment variable. If you set the type to File, then GitLab will create a file at the path specified in tha value of Key (1), and fill it with the contents specified in Value (2).

If you select Protect Variable (5) then it is only passed to pipelines running on protected branches or protected tags.

If you select Mask Variable (6) then the variable’s value is masked in job logs. The variable fails to save if the value does not meet the masking requirements.


That's it, you have now added your variable.

Passing Variables To Terraform

If you are using Gitlab with Terraform (which I recommend), then you are likely going to wish to set variables in GitLab and have them passed to terraform. That way you don't have to hardcode the settings in the codebase itself, such as in a .tfvars file, and the same code can be deployed in multiple environments.

To do this, you just need to prefix the terraform variable name with TF_VAR_. For example, TF_VAR_user_name would set the terraform variable user_name. Alternatively, you could add likes like the following to your .gitlab-ci.yml file:

job:
    stage: build
    script:
        - export TF_VAR_user_name=${GITLAB_NON_PREFIXED_VARIABLE_NAME}

This TF_VAR_ prefix isn't anything to do with GitLab. Terraform will natually pull in environment variables from your shell that start with TF_VAR_ and remove the prefix. I just keep forgetting this because I tend to create .tfvars files

References

Last updated: 10th February 2021
First published: 10th February 2021