I manage a few servers with some friends. We mostly rely on Terraform to update/change DNS records or create new VMs.
Terraform uses 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 different machines at the same time. You can find it also the official documentation, but I will provide you with a quick start.
Create a personal API token for your GitLab account with the scope
api
.Add the following settings to your
main.tf
.
terraform {
backend "http" {
}
}
- Run
terraform init
with the following arguments and replaceUSERNAME
API-TOKEN
PROJECT-ID
STATE-NAME
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" \
-backend-config="retry_wait_min=5"
- Run
terraform plan
orterraform 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.