# state-backend / aws / t0 "Quick start"
#
# An S3 bucket to contain Terraform state: versioned, encrypted, private, and
# locked while a run is in progress.
#
# Run:
#   terraform init && terraform apply
#   terraform output backend_block
#
# Paste what the last command prints into the terraform block of any other
# folder, run terraform init there, and its state lives here from then on.
#
# Verify:
#   Start terraform plan in two terminals against a folder using this backend.
#   The second waits with a message about acquiring the state lock.
#
# This version is for a scratch account. force_destroy is on, so terraform
# destroy removes the bucket and every state file in it. The Standard version
# refuses to be destroyed.

terraform {
  required_version = ">= 1.10"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
  }
}

provider "aws" {
  default_tags {
    tags = {
      owner               = "platform-engineering"
      environment         = "prod"
      data_classification = "restricted"
      managed_by          = "terraform"
    }
  }
}

data "aws_caller_identity" "current" {}
data "aws_region" "current" {}

resource "random_id" "suffix" {
  byte_length = 4
}

resource "aws_s3_bucket" "state" {
  bucket        = "tfstate-${data.aws_caller_identity.current.account_id}-${random_id.suffix.hex}"
  force_destroy = true
}

# Every write keeps the previous version. A bad apply or a corrupted file is
# one restore away.
resource "aws_s3_bucket_versioning" "state" {
  bucket = aws_s3_bucket.state.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
  bucket = aws_s3_bucket.state.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
    bucket_key_enabled = true
  }
}

resource "aws_s3_bucket_public_access_block" "state" {
  bucket                  = aws_s3_bucket.state.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# ACLs off. Access is decided by IAM and the bucket policy alone.
resource "aws_s3_bucket_ownership_controls" "state" {
  bucket = aws_s3_bucket.state.id
  rule {
    object_ownership = "BucketOwnerEnforced"
  }
}

data "aws_iam_policy_document" "state" {
  statement {
    sid     = "DenyUnencryptedTransport"
    effect  = "Deny"
    actions = ["s3:*"]
    principals {
      type        = "AWS"
      identifiers = ["*"]
    }
    resources = [aws_s3_bucket.state.arn, "${aws_s3_bucket.state.arn}/*"]
    condition {
      test     = "Bool"
      variable = "aws:SecureTransport"
      values   = ["false"]
    }
  }
}

resource "aws_s3_bucket_policy" "state" {
  bucket     = aws_s3_bucket.state.id
  policy     = data.aws_iam_policy_document.state.json
  depends_on = [aws_s3_bucket_public_access_block.state]
}

output "bucket" {
  description = "Bucket containing state."
  value       = aws_s3_bucket.state.id
}

# use_lockfile stores a small lock object beside the state, so no DynamoDB
# table is needed. Older guides that tell you to create one predate it.
output "backend_block" {
  description = "Paste into the terraform block of any folder that should keep its state here. Change the key per folder."
  value       = <<-EOT
    backend "s3" {
      bucket       = "${aws_s3_bucket.state.id}"
      key          = "CHANGE-ME/terraform.tfstate"
      region       = "${data.aws_region.current.region}"
      encrypt      = true
      use_lockfile = true
    }
  EOT
}
