Terraform Tutorial — Backend Migration and .gitignore

1 minute read

At some point, you’ll need to move state from one backend to another (local → S3, S3 → Terraform Cloud). Here’s how to do it safely.


Migrating from Local to S3

  1. Add the backend configuration:
terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}
  1. Run init with migration:
$ terraform init -migrate-state

Initializing the backend...
Do you want to copy existing state to the new backend?
  Enter a value: yes

Successfully configured the backend "s3"!

Terraform copies the local state to S3 and switches to the new backend.


Migrating Between Remote Backends

Same process — change the backend config and run:

$ terraform init -migrate-state

Reconfiguring (No Migration)

If you want to start fresh without migrating:

$ terraform init -reconfigure

This ignores the existing state and initializes from scratch.


Essential .gitignore

# .gitignore for Terraform projects

# State files (contain secrets!)
*.tfstate
*.tfstate.*

# Provider plugins (large, regenerated by init)
.terraform/

# Crash logs
crash.log
crash.*.log

# Variable files with secrets
*.tfvars
!example.tfvars

# Override files
override.tf
override.tf.json
*_override.tf
*_override.tf.json

# CLI configuration
.terraformrc
terraform.rc

# Plan files
*.tfplan

💡 Tip: Create an example.tfvars with placeholder values and commit it. This shows teammates what variables to set without exposing real values.


What’s Next?

Practice backend configuration with the exercises.


← Terraform Cloud Backend Practice Exercises →