I manage a few servers with some friends. We mostly rely on Terraform to update/change DNS records or create new VMs.

Terraform use a state to store the last applied configuration of the managed infrastructure. The default location for this state is your local filesystem, but if you manage your infrastructure with multiple persons it must be shared. This can be problematic as it also contains secrets, like api tokens, so it should not be accessible for everyone.

Terraform uses backends to provide a solution for storing the state somewhere remote instead of your local disk. If you have an account on a GitLab instance you already have access to a remote storage for your state which can be used as http backend. The backend also handles locking, so you can’t execute terraform apply from differnent machines at the same time. You can find the official documentation over here but I will provide you with a quickstart.

  1. Create a personal api token for your GitLab account with the scope api.

  2. Add the following settings to your main.tf.

terraform {
  backend "http" {
  1. Run terraform init with the following arguments and replace
terraform init \
    -backend-config="address=https://gitlab.com/api/v4/projects/<PROJECT-ID>/terraform/state/<STATE-NAME>" \
    -backend-config="lock_address=https://gitlab.com/api/v4/projects/<PROJECT-ID>/terraform/state/<STATE-NAME>/lock" \
    -backend-config="unlock_address=https://gitlab.com/api/v4/projects/<PROJECT-ID>/terraform/state/<STATE-NAME>/lock" \
    -backend-config="username=USERNAME" \
    -backend-config="password=API-TOKEN" \
    -backend-config="lock_method=POST" \
    -backend-config="unlock_method=DELETE" \
  1. Run terraform plan or terraform apply and the remote state should be used.

There are other ways to use a remote state with Terraform like a postgres database or S3, but if you have access to a GitLab instance or an account on gitlab.com this is a simple way to get the advantages of a remote Terraform state.