Store your Terraform state file remotely on AWS S3.

Hello World!

Today I will show you how to store you Terraform state file remotely in an AWS S3 Bucket.

First we need to be comfortable with the State file and what it represents for Terraform.

Whenever you run Terraform Apply Terraform saves the state of the resources changed in a file called the State file that is named terraform.tfstate in your working directory. According to the information stored in the State file Terraform knows what to change or destroy when you use Terraform Apply or Terraform destroy.

By default the state file is store locally, meaning that the state file will be in your local directory, it is recommended that you store your state file remotely as it provides better security and the ability to work in teams properly.

  1. First step I’m going to launch an EC2 instance and store the state file in the s3 bucket.
Image for post
Image for post

2. Second Step is to Initialize your Terraform working directory by running Terraform init, once done you will receive the message below.

Image for post
Image for post
terraform init

3. Lets run Terraform Plan, Terraform plan looks at the current state of the resources in order to effectively determine the changes that it needs to make to reach the desired configuration. In our case we are creating an Ec2 instance.

4. Now its time to run Terraform apply to apply the changes required to reach to desired state, in our case it will be the creation of an Ec2 instance.

Image for post
Image for post

5. Now lets head over to the console and check our S3 bucket and see if the state file is there.

When I open the terraform.tfstate file this is what I see.

Image for post
Image for post

Now lets see what happens when I destroy the Ec2 Instance that we launched earlier by running Terraform Destroy

Image for post
Image for post

Now lets take a look at our S3 bucket.

{
"version": 4,
"terraform_version": "0.12.28",
"serial": 1,
"lineage": "be1108ad-ecae-3912-1553-f7e04c28b647",
"outputs": {},
"resources": []
}

Its completely empty, because we destroyed the Ec2 Instance that was running. Now every time we make any changes to our state file we will be able to see that change in the S3 bucket!

Please note that you can always change your backend configuration anytime. You can change both the configuration itself as well as the type of backend (for example from “consul” to “s3”).

AWS Certified Cloud Practitioner | UMBC Alum

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store