How to setup terraform with remote state S3
Terraform stores the state locally by default in the local project directory but we can also store this state remotely using the terraform backend.

Terraform is developed by HashiCorp, it uses HCL language to build the infrastructure using the code. In this tutorial we are going to see how to setup the terraform and setup remote config state with AWS S3.
Terraform stores the state locally by default in the local project directory but we can also store this state remotely using the terraform backend. It supports all leading cloud storage like AWS S3, GCS Bucket, Azure Storage, and etc.
Though is setup is optional its is always recommended to use remote state as the best practice like keeping sensitive information off the disk and protects the state corruption with locks.
What you need to start
- AWS CLI
- Terraform
- VS Code
- S3 bucket for the storing remote state
Note: This article requires basic knowledge about AWS Infrastructure
Lets create main.tf file with the following content
provider "aws" {
profile = "default"
region = "ap-south-1"
}
resource "aws_instance" "mobilelabs" {
ami = "ami-040c7ad0a93be494e"
instance_type = "t2.micro"
}
Here we are specifing the aws profile which is will default most of the time, you can specify the aws region in region field.
Amazon Machine Image(ami) is the operating system installed in the EC2 instance, This can be configured in ami field and instance type in the instance_type.
Now let's setup the AWS S3 backend to terraform state, create backend.tf file with the following content.
terraform {
backend "s3" {
region = "ap-south-1"
bucket = "mobilelabs.in"
key = "mobilelabs.in/development/state.tfstate"
encrypt = true #AES-256 encryption
}
}
Check out below link in case you want to learn about creating s3 bucket using terraform

Project directory structure

let's run
terraform init -backend=true
Now you should run
terraform plan

terraform apply

Now you can check your s3 bucket and you should be able to find the state.tfstate file created.

lets checkout our EC2 instance created by terraform

To destroy the setup you just run
terraform destroy
This will delete all the created resource, isn't that really cool!!!
Latest on Terraform - Azure storage

Reference
1. https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html
2. https://www.terraform.io/docs/backends/types/s3.html