Skip to content

Storing Terraform Modules In Gitlab

We store our terraform module releases in Gitlab's terraform module registry. On the surface it is a very straight forward and simple process, but there are a few gotchas depending on your specific environment. Here are a couple we ran into and how we solved them.

Uploading The Module To Gitlab

You can use either the api or CI/CD. We chose to use CI/CD for automation.

We used the terraform module template to automatically push all of the changes to the terraform module registry. It already has all the necessary configurations and all that it requires is setting the pipeline variables.

Accessing Published Modules

We also use gitlab CI/CD to run our terraform pipelines which consist of planning, applying, and destroying. This means that we need to be able to access and download the published modules. If you have the module published in a different project than the terraform code than it may not be able to access the module.

To fix this we use a deploy token. This can be found in *terraform module locaion* -> settings -> Repository -> Deploy Tokens. Make sure to create one with the read_package_registry scope. This will allow it to read anything in the terraform module registry. Once you have created a Deploy Token you need to switch to your terraform projects .gitlab-ci.yml file. Set the variable TF_VAR_gitlab_com to the deploy token's secret value in the CI/CD variables. To set a CI/CD variable go to Settings -> CI/CD -> Variables. If you are using a different gitlab site than gitlab.com then you will need to switch the gitlab_com piece of the variable to your specific url site. Keep in mind that you cannot use a . in the variable name, which is why there is a _ instead.

Once you have done all this then it should be able to successfully authenticate to the terraform module registry and download the module!