---
title: "Secure Your State With Terraform Backends"
description: "Learn how to secure your Terraform state by using different Terraform backends and avoid losing the current status of your infrastructure!"
canonical: "https://adamtheautomator.com/terraform-backend/"
---

# Secure Your State With Terraform Backends

> Learn how to secure your Terraform state by using different Terraform backends and avoid losing the current status of your infrastructure!

Source: https://adamtheautomator.com/terraform-backend/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Secure Your State With Terraform Backends](https://adamtheautomator.com/wp-content/uploads/2022/05/Secure-Your-State-With-Terraform-Backends.jpg)

# Secure Your State With Terraform Backends

[![](https://secure.gravatar.com/avatar/2beb65fca997135120ed98dc6a2e57dcdf1a7d7d2f5ff687b5d91dc7ccd7a6b5?s=192&d=mm&r=g)Sagar](https://adamtheautomator.com/author/shanky-mendiratta/)11 May 20227 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Terraform](/tag/terraform/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [What is Terraform State and Why a Backend](#what-is-terraform-state-and-why-a-backend)
*   [Defining Local Terraform Backend](#defining-local-terraform-backend)
*   [Provisioning an AWS EC2 instance with Terraform](#provisioning-an-aws-ec2-instance-with-terraform)
*   [Verifying the AWS EC2 Instance and Local backend](#verifying-the-aws-ec2-instance-and-local-backend)
*   [Configuring a Remote Backend](#configuring-a-remote-backend)
*   [Conclusion](#conclusion)

If you’re building a massive infrastructure with Terraform, storing information about your infrastructure is a crucial matter. But how do you store infrastructure information? Not a problem, [Terraform backend](https://developer.hashicorp.com/terraform/language/settings/backends/configuration) has got you covered!

Terraform backend allows you to keep your Terraform state file containing all resource details and tracking which were provisioned or will be provisioned with Terraform. And in this tutorial, you’ll learn how Terraform’s backend lets team members or developers securely manage states without impacting existing resources.

Read on and never miss a piece of your infrastructure’s information!

## Prerequisites

If you’d like to follow along in this tutorial, ensure you have the following in place:

*   A local machine – This tutorial uses [Ubuntu](https://adamtheautomator.com/install-ubuntu/) 21.04.5 LTS, but other operating systems with Terraform will work.

Related:[How to Install Ubuntu 20.04 \[Step-by-Step\]](https://adamtheautomator.com/install-ubuntu/)

*   Terraform installed on your machine – This tutorial uses [Terraform v1.0](https://releases.hashicorp.com/terraform/0.14.9/).

Related:[How to Install Terraform on Linux and Windows](https://adamtheautomator.com/install-terraform/)

*   An [Amazon Web Service (AWS) account](https://repost.aws/knowledge-center/create-and-activate-aws-account) – You can create a free-tier account if you don’t have one.
    
*   An [existing AWS S3 Bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-bucket.html) – This tutorial uses an S3 bucket named mys3bucketata.
    
*   [AWS CLI installed](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) and configured on your machine – This tutorial uses aws-cli/2.6.1.
    
*   A code editor – Even though you can use any text editor to work with Terraform configuration files, you should have one that understands the HCL Terraform language. Try out [Visual Studio (VS) Code](https://code.visualstudio.com/).
    

Related:[What You Need to Know about Visual Studio Code: A Tutorial](https://adamtheautomator.com/visual-studio-code-tutorial/)

## What is Terraform State and Why a Backend

Have you come across the terms Terraform state and state file while working with Terraform? These two essential components are needed when you have a team that works on the same projects or as your infrastructure grows.

In a nutshell, these components serve as follows:

*   **Terraform state** – contains bindings between objects in remote systems and is defined in your Terraform configuration files. And all these states are stored in the Terraform state file.
*   **Terraform state file** – is by default stored locally on your machine where you run the Terraform commands with the name of _terraform.tfstate_.

Terraform state is stored in JSON format. As a result, when you run either [terraform show](https://developer.hashicorp.com/terraform/cli/commands/show) or [terraform output](https://developer.hashicorp.com/terraform/cli/commands/output) command, Terraform fetches the output from the Terraform state file in JSON format.

> _You can also_ [_import existing infrastructure_](https://spacelift.io/blog/importing-exisiting-infrastructure-into-terraform) _you created by other means, such as manually or using scripts within Terraform state file. But the topic of importing infrastructure is beyond this tutorial._

Keeping the Terraform state file in your local machine (aka local backend) is fine when you’re working as an individual. But when you work in a team, storing the state file in a backend, such as AWS S3, is a much better option.

While you write anything on the resource that is a Terraform configuration file, the Terraform state file gets locked. As a result, Terraform prevents someone else from using the state file and prevents it from being corrupted.

## Defining Local Terraform Backend

You’ve been introduced to the idea behind leveraging Terraform state and state file. But enough about the introduction. It’s time to get your hands dirty with Terraform!

But before using Terraform state and backends, you must define them first in configuration files. You’ll set the local backend to store the state file in your local machine in a specified location.

1\. SSH to your Ubuntu machine.

2\. Next, run the commands below to create a working directory called ~/terraform-backend-demo and switch to that directory_._ This directory will contain all of the configuration files you’ll be working on in this tutorial.

```bash
mkdir ~/terraform-backend-demo
cd ~/terraform-backend-demo
```

3\. Create a file called _main.tf_ inside the ~/_terraform-backend-demo_ directory with your preferred code editor. This file is the Terraform configuration for your AWS EC2 instance.

Related:[Getting Started with the Terraform AWS Provider](https://adamtheautomator.com/terraform-aws/)

4\. Now, copy/paste the following configuration to the _main.tf_ file, and save the changes.

The ami declared in the code below is an [Amazon Machine Image (AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html). This AMI provides the information required to launch an instance, such as the type of OS, which software to install, etc.

> _You can_ [_find Linux AMIs_](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) _using the Amazon EC2 console._

```powershell
# Creating the instance with the instance_type t2.micro 
resource "aws_instance" "my-machine" {
# Declarling the AMI 
  ami = "ami-0a91cd140a1fc148a"
  instance_type  = "t2.micro"
}
```

5\. Create another file in ~/_terraform-backend demo,_ name it _provider.tf_ and populate the content below. This _provider.tf_ file defines providers (i.e., AWS, Oracle, Azure, etc.) so that Terraform can connect with the correct cloud services.

The below code also uses the local backend (local) with path set to _home/ubuntu/terraform-backend-demo/terraform.tfstate._ Terraform stores the state file in this path and later use the same backend to create the AWS EC2 instance.

> _The tutorial creates resources in the us-east-1 region. But a list of_ [_regions that AWS support_](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) _is also available._

```powershell
# Declaring the Provider Requirements and Backend
terraform {
  backend "local" {
    path = "home/ubuntu/terraform-backend-demo/terraform.tfstate"
}
  # A provider requirement consists of a local name (aws),  source location, and a version constraint. 
  required_providers {
    aws = {     
      # Declaring the source location/address where Terraform can download plugins
      source  = "hashicorp/aws"
      # Declaring the version of aws provider as greater than 3.0
      version = "~> 3.0"  
    }
  }
}

# Configuring the AWS Provider in us-east-1 region
provider "aws" {
  region = "us-east-1"
}
```

6\. Finally, run the tree command to verify all required files in the _~/terraform-backend-demo_ directory.

```bash
tree
```

![Verifying Required Files for Building AWS S3 in AWS Cloud via Local Backend](https://adamtheautomator.com/wp-content/uploads/2022/05/image-158.png)

Verifying Required Files for Building AWS S3 in AWS Cloud via Local Backend

## Provisioning an AWS EC2 instance with Terraform

You’ve set up a Terraform configuration and variables files, but they’re not doing much right now. You’ll have to initiate Terraform, create the AWS EC2 instance and verify your local backend.

Related:[How to Manage Virtual Machines With Ansible EC2 AWS Module](https://adamtheautomator.com/ansible-ec2/)

To provision the AWS EC2, like all other Terraform configurations, Terraform uses three commands in sequence ([terraform init](https://developer.hashicorp.com/terraform/cli/commands/init), [terraform plan](https://developer.hashicorp.com/terraform/cli/commands/plan), and [terraform apply](https://developer.hashicorp.com/terraform/cli/commands/apply)).

> _If the Terraform configuration files you created are not correctly formatted, you can run the_ [_terraform fmt_](https://developer.hashicorp.com/terraform/cli/commands/fmt) _command to fix them._

1\. Run the terraform init command below in the ~/_terraform-backend-demo_ directory to initialize the plugins and providers required to work with resources.

```bash
terraform init
```

If all goes well, you’ll see the message that says Terraform has been successfully initialized in the output, as shown below.

![Initializing Terraform](https://adamtheautomator.com/wp-content/uploads/2022/05/image-159.png)

Initializing Terraform

2\. Next, run the terraform plan command below to ensure your configuration files syntax is correct and gives you a blueprint of resources provisioned in your infrastructure.

```bash
terraform plan
```

Once the command completes, you’ll see a message like Plan: “X” to add, “Y” to change, or “Z” to destroy in the output. Below, the Plan shows 1 to add as four resources need to be created.

![Showing Resources to Build ](https://adamtheautomator.com/wp-content/uploads/2022/05/image-160.png)

Showing Resources to Build

3\. Finally, run the terraform apply command to provision the AWS EC2 instance using each configuration (_\*.tf_) in the working directory (~/_terraform-backend-demo_).

The –auto-approve parameter automatically accepts all prompts while running the command.

```bash
terraform apply --auto-approve
```

Note down the instance ID from the output. You’ll use it to verify the instance created in the AWS EC2 instance dashboard later.

![Provisioning the AWS EC2 Instance](https://adamtheautomator.com/wp-content/uploads/2022/05/image-161.png)

Provisioning the AWS EC2 Instance

## Verifying the AWS EC2 Instance and Local backend

You’ve successfully created a new AWS EC2 instance in your AWS account. But how do you know it’s running? You’ll verify the instance in your AWS account and Terraform state file if the instance is created on your local machine in a specified location.

1\. Open your favorite web browser, navigate the [AWS Management Console](https://aws.amazon.com/console/), and log in to your AWS account.

2\. In the AWS Management Console, click on the search bar at the top, search for ‘EC2’, and click on the EC2 menu item.

Your browser redirects to the EC2 instance dashboard, where you’ll see all your EC2 instances. Verify that the Instance ID is the same as what you noted in the last step of the “Provisioning an AWS EC2 instance with Terraform” section.

![Verifying the AWS EC2 Instance on AWS Account](https://adamtheautomator.com/wp-content/uploads/2022/05/image-162.png)

Verifying the AWS EC2 Instance on AWS Account

3\. Lastly, run the following commands to verify the state file on your local machine

```powershell
# Change working directory
cd /home/ubuntu/terraform-backend-demo
# Print contents of the terraform.tfstate file
cat terraform.tfstate
```

Like in your AWS EC2 dashboard, verify the same instance ID inside the _terraform.tfstate_ file, as shown below.

![Verifying Instance ID in State File](https://adamtheautomator.com/wp-content/uploads/2022/05/image-163.png)

Verifying Instance ID in State File

## Configuring a Remote Backend

There’s nothing wrong with storing your state file locally on your machine by setting the local backend if you’re working on a project by yourself. But when you’re working with a team, you need a way to keep the backend on a remote machine by configuring an AWS S3 bucket.

Why configure a remote backend? Doing so lets all the team members update the Terraform state file and manage the resources without impacting them.

1\. Open the _provider.tf_ file and replace the local backend config block with the following lines to define a remote backend instead (AWS S3).

```powershell
  backend "s3" { # Define a remote bucket (AWS S3)
    bucket = "mys3bucketata" # Set your bucket's name
    key    = "mykey"         # Set the bucket key
    region = "us-east-1"     # Set the region where the bucket exists
  }
```

![Configuring a Remote Backend (AWS S3)](https://adamtheautomator.com/wp-content/uploads/2022/05/image-164.png)

Configuring a Remote Backend (AWS S3)

2\. Next, rerun the terraform init command in the ~/_terraform-backend-demo_ directory to initialize the plugins and providers required to work with resources. But this time, you’ll append the -migrate-state flag as you’re changing the state location from local to AWS S3 bucket.

```powershell
terraform init -migrate-state
```

![Initializing Terraform with Remote Backend (AWS S3) ](https://adamtheautomator.com/wp-content/uploads/2022/05/image-165.png)

Initializing Terraform with Remote Backend (AWS S3)

3\. Run the following commands as you did in steps two and three of the “Provisioning an AWS EC2 instance with Terraform” section. But this time, you’re applying the configurations for an AWS S3 bucket as the remote backend.

```bash
terraform plan
terraform apply
```

Note down your S3 bucket’s instance ID to compare it to the one in your AWS account later.

![Applying Configurations for the Remote Backend](https://adamtheautomator.com/wp-content/uploads/2022/05/image-166.png)

Applying Configurations for the Remote Backend

4\. Now, navigate to your [AWS S3 buckets dashboard](https://s3.console.aws.amazon.com/s3/buckets?region=us-east-1) on your web browser. And click on your bucket (mys3bucketata) and your bucket key (mykey) to verify if the Terraform state file has been created.

As you can see below, the Terraform state file is now stored in your AWS S3 bucket (mys3bucketata).

![Verifying the Terraform object in the AWS S3 bucket](https://adamtheautomator.com/wp-content/uploads/2022/05/image-167.png)

Verifying the Terraform object in the AWS S3 bucket

5\. Lastly, click on the Object URL, as shown below, to verify the details of the newly created instance in the state file.

![verify the details of the newly created instance](https://adamtheautomator.com/wp-content/uploads/2022/05/image-168.png)

verify the details of the newly created instance

As you can see below, the instance that Terraform launched (i-07930a50afd420d6d) is present in the Terraform state file.

![Checking the Terraform State File](https://adamtheautomator.com/wp-content/uploads/2022/05/image-169.png)

Checking the Terraform State File

## Conclusion

In this tutorial, you’ve learned the importance and how the Terraform state and backend work. You’ve also touched on securing your Terraform state with Terraform backends, local backend, and remote backend (AWS S3).

With this newfound knowledge, why not try storing the states of other AWS services with Terraform backends? Or perhaps [migrate state from S3 to Terraform Cloud](https://developer.hashicorp.com/terraform/tutorials/cloud/migrate-remote-s3-backend-tfc)?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fterraform-backend%2F&text=Secure%20Your%20State%20With%20Terraform%20Backends)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fterraform-backend%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fterraform-backend%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2024/03/terragrunt.png)

### [Keeping Terraform Maintainable with Terragrunt](/terragrunt/)

Discover Terragrunt and embrace the power to simplify Terraform workflows—Ensure maintainability and organization of your infrastructure today!

![](https://adamtheautomator.com/wp-content/uploads/2022/07/How-to-Monitor-AWS-via-the-Terraform-Cloudwatch-Module.jpg)

### [Monitor AWS via the Terraform Cloudwatch Module](/terraform-cloudwatch/)

Learn how to monitor and provision with the Terraform Cloudwatch module and keep your AWS infrastructure healthy and in check!

![](https://adamtheautomator.com/wp-content/uploads/2022/01/How-to-Migrate-Existing-Terraform-State-into-Terraform-Cloud.jpg)

### [How to Migrate Existing Terraform State into Terraform Cloud](/terraform-state/)

Learn how to migrate your existing Terraform state files into Terraform Cloud, and never worry about losing changes in your state file in this step-by-step tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
