Terraform Tip #02 - Always use a backend
When working with the cloud, something that we need to worry about is tracking our infrastructure. Every resource has an id when it's generated, and since we have different environments for our applications, saving the state of them is necessary.
And when using Terraform, you can save that state using a terraform backend.
To set up a backend is quite simple:
Create a bucket on AWS S3. Example: my-terraform-states
Setup the S3 backend on Terraform:
terraform {
backend "s3" {
bucket = "my-terraform-states"
key = "my-app-dev-state"
region = "us-east-1"
}
}
terraform init
The steps above will:
Setup the backend on the given bucket, and the state file will be named "my-app-dev-state". When you run terraform apply
, the state generated from the success of that operation will be saved on your backend, i.e, on your bucket.
Until today I am not aware of a way to user vars to build the bucket or key names since those values are only loaded when using terraform plan
, not with init. So those need to be hardcoded. My strategy for that is to have base repositories with terraform modules, then I fork for each environment and start from there.
If you want to learn more about terraform backend and states check Terraform docs.
That's all folks. =D