# state-backend / gcp / t0 "Quick start"
#
# A Cloud Storage bucket to contain Terraform state: versioned, private, and
# locked while a run is in progress. The gcs backend handles locking itself,
# with nothing extra to create.
#
# Change the project ID below, then:
#   gcloud auth application-default login
#   terraform init && terraform apply
#   terraform output backend_block
#
# Paste the printed block into any other folder and run terraform init there.
#
# Verify:
#   Start terraform plan in two terminals against a folder using this backend.
#   The second reports that the state is locked.
#
# This version is for a scratch project. terraform destroy removes the bucket
# and every state file in it.

locals {
  project_id = "your-project-id" # change me

  location = "US"
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 8.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
  }
}

provider "google" {
  project = local.project_id
}

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

resource "google_storage_bucket" "state" {
  name     = "tfstate-${random_id.suffix.hex}"
  location = local.location

  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"
  force_destroy               = true

  # Every write keeps the previous version, so a bad apply is one restore away.
  versioning {
    enabled = true
  }

  labels = {
    owner               = "platform-engineering"
    environment         = "prod"
    data_classification = "restricted"
    managed_by          = "terraform"
  }
}

output "bucket" {
  description = "Bucket containing state."
  value       = google_storage_bucket.state.name
}

output "backend_block" {
  description = "Paste into the terraform block of any folder that should keep its state here. Change the prefix per folder."
  value       = <<-EOT
    backend "gcs" {
      bucket = "${google_storage_bucket.state.name}"
      prefix = "CHANGE-ME"
    }
  EOT
}
