Skip to main content

Tutorial

NOTE: If you are starting a new project, click here

Setting up S3 remote backend and DynamoDB locking

  1. We start with the terraform.tf file.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.84.0"
}
}

required_version = ">= 1.2.0"
}

provider "aws" {
region = "eu-central-1"
}
  1. Then we provision two resources: an S3 bucket and a DynamoDB table.
resource "aws_s3_bucket" "state" {
bucket = "tf-state"
}

resource "aws_dynamodb_table" "state" {
name = "tf-state-lock"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"

attribute {
name = "LockID"
type = "S"
}
}
  1. Apply the resources.
terraform init
terraform apply
  1. Add backend block to terraform.tf file to enable remote state.
  backend "s3" {
bucket = "tf-state"
key = "state"
region = "eu-central-1"
encrypt = true
dynamodb_table = "tf-state-lock"
}
  1. Migrate the state from local to S3.
terraform init

And choose yes when prompted.

Moving to S3 native state locking

  1. Change the backend.tf file.
  backend "s3" {
bucket = "tf-state"
key = "state"
region = "eu-central-1"
encrypt = true
use_lockfile = true
}

We added the use_lockfile argument and removed the dynamodb_table argument.

  1. Move the state locking to S3.
terraform init -reconfigure
  1. Validate the move to S3, and then remove the DynamoDB resource.

New projects

  1. Create the backend.tf file.
  backend "s3" {
bucket = "tf-state"
key = "state"
region = "eu-central-1"
encrypt = true
use_lockfile = true
}
  1. Initialise Terraform
terraform init