Tutorial
NOTE: If you are starting a new project, click here
Setting up S3 remote backend and DynamoDB locking
- 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"
}
- 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"
}
}
- Apply the resources.
terraform init
terraform apply
- 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"
}
- Migrate the state from local to S3.
terraform init
And choose yes
when prompted.
Moving to S3 native state locking
- 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.
- Move the state locking to S3.
terraform init -reconfigure
- Validate the move to S3, and then remove the DynamoDB resource.
New projects
- Create the
backend.tf
file.
backend "s3" {
bucket = "tf-state"
key = "state"
region = "eu-central-1"
encrypt = true
use_lockfile = true
}
- Initialise Terraform
terraform init