Terraform Backend Using S3 and DynamoDB With State Locking
Lasantha Sanjeewa Silva
DevOps Engineer @ IFS | AWS Community Builder | Enabling DevOps
Terraform is an infrastructure as code (IaC) tool that allows you to build, change, and version infrastructure safely and efficiently. This includes low-level components such as compute instances, storage, and networking, as well as high-level components such as DNS entries, SaaS features, etc. Terraform can manage both existing service providers and custom in-house solutions.
You must have installed the following things
We can use the following easy steps
Step 1 -?Create an Empty Directory and open it via the code editor.
Step 2 -?Inside the empty folder create a file called provider.tf and add the following content.
terraform {
? required_providers {
? ? aws = {
? ? ? source ?= "hashicorp/aws"
? ? ? version = "~> 4.16"
? ? }
? }
}
Step 3 -?Create backend.tf file and add S3 bucket and DynamoDb table details.
terraform {
? backend "s3" {
? ? bucket? ? ? ? ?= "{{s3-bucket-name}}"
? ? key? ? ? ? ? ? = "terraform.tfstate"
? ? region? ? ? ? ?= "{{aws-region}}"
? ? dynamodb_table = "{{dynamodb-table-name}}"
? }
}
Step 4 -?Firstly Configure AWS using AWS CLI keys(Use aws configure command). next run terraform init command for initialize terraform project.
terraform init
领英推荐
Step 5 -?Create the following files in your repository for EC2 instance creation.
main.tf
resource "aws_instance" "app_server" {
? ami ? ? ? ? ? = "{{ami-id}}"
? instance_type = "t2.micro"
? tags = {
? ? Name = var.instance_name
? }
}
variables.tf
variable "instance_name" {
? description = "Value of the Name tag for EC2"
? type ? ? ? ?= string
? default ? ? = "Example EC2 Instance"
}
outputs.tf
output "instance_id" {
? description = "Id EC2"
? value ? ? ? = aws_instance.app_server.id
}
output "instance_public_ip" {
? description = "Public ip EC2"
? value ? ? ? = aws_instance.app_server.public_ip
}
Step 6 - Type terraform apply to creating resources. In the creation process enter yes for approval.
Step 6 - You can see the DynamoDB table like this.
Also, see terraform.tfstate file inside S3 bucket.
Step 7 - Finally, run terraform destroy command to remove all created resources. Because it helps to reduce AWS cost.
Thanks for reading the Article.
Git repository: https://github.com/sanju2/tf-state-mgt
good one but its better you create the bucket and table using IaC too. can give a try this https://github.com/devopswithzack/aws-terraform-s3-backend