Terraform state locking using DynamoDB table
create S3 bucket in AWS console.
Create dynamodb table. go to table and click on create table and enter table name of your choice and Partition key as "LockID" and click on create table.
Table will be created. status will be "Active"
Add AWS DynamoDB Table reference to Backend S3 remote state.
Note: mention bucket name and dynamodb table name.
terraform { backend "s3" { bucket = "abhijit-tf-test-bucket-for-remote-state" key = "abhijit/terraform.tfstate" encrypt = true region = "us-east-1" dynamodb_table = "dynamodb-state-lock-testing" } }
Now suppose 2 people in the organization using same terraform state file along with dynamodb table. Go to project 1 and run terraform init command. This command will apply the above configuration with Dynamodb table.
Now the run the terraform plan command.
Now run the terraform apply command but do not type yes (Enter a value field) because then changes will be applied and resource will be created.
Navigate to project 2 and imagine a situation where another person working in project 2 using terraform state file at the same time and he has run terraform init command but note that changes done by person 1 are still not yet applied.
Now person 2 has run terraform plan command and immediately received error - Error acquiring the state lock. Error message: conditionalCheckFailedException: The conditional request failed │ Lock Info: │ ID: 14095f46-4bed-45f7-8d9f-9d5748d659e9
this error is caused because person 1 is still working on his changes which are not yet applied, thus lock is created.
Verify the dynamo DB lock by going to AWS console. enter attribute as "LockID" and click on Run.
above screenshot shows the lockid in DynamoDB table.
Now finish the work i.e. apply the changes of person 1 by clicking yes.
Note that EC2 instance [id=i-099d2e5c7908a4432] has been created and lock has been released.
Navigate to AWS console and verify EC2 instance is created.
Verify in AWS console that Dynamodb lock has been released by refreshing the page. we can see that long detail of lock id has gone.
now person 2 can run terraform plan and terraform apply command as lock has been released.
Conclusion - Terraform state locking using Dynamodb table ensures that the state is only being updated from one place at a time (no concurrent updates), which is very useful in team settings where people or processes may attempt to run and apply at the same time. Thus AWS S3 and Dynamo DB terraform state locking feature can improve your state management and help us to avoid any unforeseen issues.