Terraform Backend with Locking

A backend in Terraform determines how state is loaded and how an operation such as apply is executed. This abstraction enables non-local file state storage, remote execution, etc.

By default, Terraform uses the local backend, which is the normal behavior of Terraform you're used to.

Here are some of the benefits of backends:

  • Working in a team: Backends can store their state remotely and protect that state with locks to prevent corruption. Some backends such as Terraform Enterprise even automatically store a history of all state revisions.
  • Keeping sensitive information off disk: State is retrieved from backends on demand and only stored in memory. If you're using a backend such as Amazon S3, the only location the state ever is persisted is in S3.
  • Remote operations: For larger infrastructures or certain changes, terraform apply can take a long, long time. Some backends support remote operations which enable the operation to execute remotely. You can then turn off your computer and your operation will still complete. Paired with remote state storage and locking above, this also helps in team environments.

Backends are completely optional. You can successfully use Terraform without ever having to learn or use backends. However, they do solve pain points that afflict teams at a certain scale. If you're an individual, you can likely get away with never using backends.

Even if you only intend to use the local backend, it may be useful to learn about backends since you can also change the behavior of the local backend.

In this blog we are using s3 as a backend.

let's create an S3 bucket (here I am creating a bucket with the name gaurav-youtube-tf). and create a dynamoDB table (here I am creating it with name gaurav-youtube-tf-table)

let's create a file with tf extension ( i am naming it as resource.tf )

terraform {
  backend "s3" {
    bucket = "gaurav-youtube-tf"
    region = "us-east-1"
    key="terraform.tfstate"
    dynamodb_table = "gaurav-youtube-tf-table"
  }
}
variable "access_key" {
  type = string
}
variable "secret_key" {
  type = string
}
provider "aws" {
  region     = "us-east-1"
  access_key = var.access_key
  secret_key = var.secret_key
}
resource "aws_instance" "web" {
  ami           = "ami-0e472ba40eb589f49"
  instance_type = "t2.small"
}

now let's run terraform init command and after that terraform apply. you can see that terraform.tfstate file is not stored in your local system it will be stored in your s3 bucket that you created and configured. (gaurav-youtube-tf).

and one more thing two or more developers can not run terraform apply at the same time.

Demo Video