Terraform is a tool that helps you manage your cloud infrastructure. It keeps track of the resources it creates using a file called the “state file”. This guide will show you how to store this state file on S3, which is a storage service by Amazon Web Services (AWS).
Why Use S3 for Terraform State?
Terraform allows storing state file on s3 for better management, which has several benefits:
- Safety: S3 is a safe place to store important files.
- Collaboration: Multiple people can work on the same Terraform project.
- Backups: S3 can keep backups of your state file.
Step-by-Step Guide
Follow the step by step instructions given below.
Step 1: Create an S3 Bucket
The first thing is to create s3 bucket using aws cli tool:
aws s3 mb s3://my-terraform-state-bucket
Step 2: Create a DynamoDB Table (Optional but Recommended)
A DynamoDB table is used for locking state file, which prevent multiple users from making changes at the same time.
aws dynamodb create-table \
--table-name terraform-lock-table \
--attribute-definitions AttributeName=LockID,AttributeType=S \
--key-schema AttributeName=LockID,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
Step 3: Configure Terraform to Use S3 and DynamoDB
- Open your Terraform project directory.
- Create or edit a file named main.tf.
- Add the following code to main.tf:
terraform { backend "s3" { bucket = "my-terraform-state-bucket" key = "terraform.tfstate" region = "us-west-2" dynamodb_table = "terraform-lock-table" encrypt = true } }
Replace my-terraform-state-bucket, us-west-2, and terraform-lock-table with your bucket name, region, and table name.
Step 4: Initialize Terraform
- Open your terminal or command prompt.
- Navigate to your Terraform project directory.
- Run the following command:
terraform init
This command tells Terraform to use the S3 bucket and DynamoDB table for storing the state file.
That’s it, Now you can use Terraform commands like terraform apply and terraform plan as usual. Terraform will store the state file in the S3 bucket you specified.
Conclusion
By storing your Terraform state file on S3, you ensure that it is safe, easy to access, and backed up. The DynamoDB table provides an extra layer of safety by preventing multiple users from making changes at the same time. Follow these simple steps to set it up, and you’ll be on your way to managing your infrastructure more efficiently.