Saving Terraform State in S3

Published: (December 4, 2025 at 07:55 AM EST)
1 min read
Source: Dev.to

Source: Dev.to

Configuring S3 as a Terraform Backend

Terraform can store its state in an S3 bucket. Below is a minimal configuration that sets up the S3 backend:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 4.0"
    }
  }
  required_version = ">= 1.0"

  backend "s3" {
    bucket                  = "terraform-state-dev"
    key                     = "my-key"
    region                  = "us-east-1"
    shared_credentials_file = "~/.aws/credentials"
  }
}
  • You can use a single key (the key argument) to store all of your Terraform state in one file, or
  • You can allocate one key per Terraform workspace (or per environment) to keep states isolated.

Migrating Existing State to S3

If you already have a local state file or are using a different backend, you can migrate it to the S3 bucket with:

terraform init -migrate-state

Warning: Losing your Terraform state can cause significant trouble, as Terraform relies on that state to track resources. Ensure the S3 bucket is versioned and backed up to prevent accidental loss.

Back to Blog

Related posts

Read more »

Terraform Project: Simple EC2 + Security Group

Project Structure terraform-project/ │── main.tf │── variables.tf │── outputs.tf │── providers.tf │── terraform.tfvars │── modules/ │ └── ec2/ │ ├── main.tf │...

AWS Terraform Lifecycle Rules

Introduction Infrastructure as Code IaC is most powerful when you have full control over how resources behave during updates, replacements, and deletions. Terr...