What is Terraform Backend ?
A "backend" is how the terraform state file is loaded & how apply get’s executed
Default "backend" is local so the .tfstate file gets stored locally.
But when you are working in a team, it makes sense to have the state file (.tfstate) stored at remote location.
What are Backends Available ?
The following standard backends are currently supported by terraform.
What is state locking
When multiple people in the team are trying to use terraform in parallel, then to allow only one user to make changes to the resources can be given by state locking
Terraform S3 Backend & State Locking with AWS S3 & DynamoDb
- To demonstrate backend & i would be using a very simple template which creates a network which can be found here
- Create a S3 bucket and note the name
- Create a dynamo db table in aws with LockID key of type string
- If you dont want to create these manually, There is module which can help you with creation of s3 storage & dynamo db tables. To do that please add the module as mentioned below
module s3_backend {
source = "youngfeldt/backend-s3/aws"
version = ">= 1.0.0"
backend_s3_bucket = "<bucket name which you want to create>"
backend_dynamodb_lock_table = "<dynamo db lock table>"
create_dynamodb_lock_table = true
create_s3_bucket = true
s3_key = "<state storage file key in s3>"
}
- Configuring terraform backend to this terraform. To do this you need to add the following snippet to your .tf file
terraform {
backend "s3"{
bucket = "${var.statestoragelocations3}"
key = "${var.statestoragekey}"
}
}
- Execute the init command with state locking enabled
terraform init -backend-config='dynamodb_table=<dynamodbtablename>' --backend-config='access_key=whatever' --backend-config='secret_key=whatever'
- Create the terraform.tfvars file with access key, secret key of your aws account. If you need to detailed info on creating keys in aws refer here. The terraform.tfvars file looks like
accesskey= "YOUR AWS ACCESS KEY"
secretkey= "YOUR AWS SECRET KEY"
- Now execute terraform apply command & carefully observe the console you can observe the state locking & your s3 bucket with a file to store state
- The implementation with backend can be found here
is there a possibility for azurerm backend