Terraform Backends
- Terraform by default when applied to create infrastructure will create a local state file, so when multiple users execute the terraform on multiple machines it leads to creation of multiple target infrastructures which is not idle.
- The solution for this is if we can store the state file in some common location which is referred as
Backend
, then even if multiple users try to apply it leads to same infrastructure.
- To avoid multiple users writing to the state file at the same time, terraform implements locking
- Refer Here for the official docs of the backend
- Terraform supports the following backends
- Lets first implement the backend using azurerm and then we will implment s3 based backend
Azurerm Backend
- Lets create a resource group
- Now create a storage account
- Once the storage account is created, create a container
- Now lets add the backend to our terraform
- Now execute
terraform init
to initialize the backend
- Now lets execute
terraform apply -var-file="experiment.tfvars" -auto-approve
- To simulate the multi user scenario, let create a new linux vm and install terrform over there and see parallel executions
- Now lets apply terraform on linux system
- Before the state has been applied lets try to simulate apply by other user i.e on my windows system
AWS S3 Backend
- Refer Here for official docs
- Create an s3 bucket
- Lets create a dynamodb table for locking purposes
- Now initialize
- And Apply
- As this user has acquired the lock which will be released upon completion of terraform execution till that moment no other user will be able to create infra.