Terraform Advanced — Partial Backend Configuration

less than 1 minute read

Keep credentials out of your .tf files by using partial backend configuration.


The Problem

# ❌ Anti-pattern: credentials in config
terraform {
  backend "s3" {
    bucket     = "mycompany-terraform-state"
    key        = "prod/terraform.tfstate"
    region     = "us-east-1"
    access_key = "AKIA..."    # Never do this!
    secret_key = "wJal..."    # Never do this!
  }
}

Partial Configuration via CLI

# ✅ Best practice: only non-sensitive values in config
terraform {
  backend "s3" {
    bucket         = "mycompany-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}
# Pass the rest via -backend-config flags
$ terraform init \
    -backend-config="access_key=$AWS_ACCESS_KEY_ID" \
    -backend-config="secret_key=$AWS_SECRET_ACCESS_KEY"

Partial Configuration via File

# backend.hcl (gitignored)
access_key = "AKIA..."
secret_key = "wJal..."
$ terraform init -backend-config=backend.hcl

Best Practice: Use IAM Roles

# ✅ Best: no credentials at all — use IAM role or SSO
$ export AWS_PROFILE=terraform-prod
$ terraform init

# Or in CI/CD with OIDC (no static credentials)
$ terraform init   # AWS credentials from OIDC token

💡 Production Tip: In CI/CD, use OIDC federation (GitHub Actions → AWS) or instance profiles (EC2/ECS). Never store static credentials.


What’s Next?

Read outputs from other stacks.

← State Encryption Remote State Data Source →

Updated: