Set GitLab CI/CD environment to contents of file in repository

Problem to solve

We’re using Terraform in a pipeline on self hosted GitLab instance. The pipeline has multiple stages: init, plan, and apply.

We’d like to set the environment that GitLab uses during plan and apply to the content of a file in the repository. I managed to set the Terraform state name for the http/GitLab managed backend by doing something like that in .gitlab-ci.yaml:

  TF_STATE_NAME: dummy

  - TF_STATE_NAME=$(cat name-of-vm.txt)
  - export TF_STATE_NAME

The Terraform state name (as shown in GitLab WebUI → Project → Operate → Terraform states) is set to whatever is in the file name-of-vm.txt. Without that before_script, it would be “dummy”.

I find, that the environment as shown in GitLab WebUI → Project → Operate → Environment is still set to dummy, as it seems to default to using $TF_STATE_NAME. I’d like to set it to what’s in name-of-vm.txt as well.

I do know, that I can change the environment name to something custom by setting in each job:

# …
    name: ${CI_COMMIT_SHORT_SHA}
# …

Works fine for pre-defined variables (like CI_COMMIT_SHORT_SHA). It does not seem to pick up the value defined in before_script.


Please select whether options apply, and add the version information.

  • Self-managed
  • SaaS
  • Self-hosted Runners



This is not possible, as described in the documentation:

Possible inputs: The name of the environment the job deploys to, in one of these formats:

  • Plain text, including letters, digits, spaces, and these characters: -, _, /, $, {, }.
  • CI/CD variables, including predefined, project, group, instance, or variables defined in the .gitlab-ci.yml file. You can’t use variables defined in a script section.

BUT, I just realized, you can set it using dotenv artifacts :slight_smile:

1 Like

Bummer :frowning:

Regarding dotenv — that’s just for the URL, isn’t it? At least that’s how I understood it.