hi, I have some terraform code in a Gitlab project which creates stuff in Hetzner cloud. I want to have separated dev / stage / prod environments for it. Therefor I created a branch for each, checked out each branch and created a distinct remote state for each (approximately following Terraform Multiple State Files Example (#220559) · Issues · GitLab.org / GitLab · GitLab and the mentioned links therein). The states are stored correctly in Gitlab, but there doesn´t seem to be a fixed conjunction between a branch and a state.
Example: I´m on dev and if I change anything using terraform command the dev state changes. But if I switch to prod and change another thing using terraform, still the ´dev´ state file changes (visible by the timestamp of the state in Gitlab).
I thought it would be just as simple as using different branches, but either I don´t understand the concept correctly or I´m doing something wrong. Can someone share some insights on this topic?
Thanks in advance
1 Like
Yes, multiple Terraform state files can be used in a pipeline.
It may be easier to use the provided GitLab container image as it supports the GitLab backend by default.
This demo repo uses environments to mange the pipeline (CI/CD variables are managed by environment):
image: registry.gitlab.com/gitlab-org/terraform-images/stable:latest
variables:
TF_ROOT: ${CI_PROJECT_DIR}/${ENVIRONMENT}
TF_ADDRESS: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/terraform/state/${ENVIRONMENT}
In your use case, replace $ENVIRONMENT
with $CI_COMMIT_BRANCH
or however you require to track your pipeline branch.