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.
- First step I’m going to launch an EC2 instance and store the state file in the s3 bucket.
2. Second Step is to Initialize your Terraform working directory by running Terraform init, once done you will receive the message below.
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.
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.
Now lets see what happens when I destroy the Ec2 Instance that we launched earlier by running Terraform Destroy
Now lets take a look at our S3 bucket.
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”).