# state-backend / azure / t0 "Quick start"
#
# A storage account to contain Terraform state: versioned, private, key access
# switched off, and locked while a run is in progress through a blob lease.
#
# Run:
#   az login
#   export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
#   terraform init && terraform apply
#   terraform output backend_block
#
# Paste the printed block into any other folder and run terraform init there.
# The role grant below can take a minute to take effect. If that first init
# fails with 403, wait and run it again.
#
# Verify:
#   Start terraform plan in two terminals against a folder using this backend.
#   The second fails to acquire the lease and waits or stops.
#
# This version is for a scratch subscription. terraform destroy removes the
# storage account and every state file in it.

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

provider "azurerm" {
  features {}
  storage_use_azuread = true
}

data "azurerm_client_config" "current" {}

resource "random_string" "suffix" {
  length  = 6
  special = false
  upper   = false
}

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

resource "azurerm_resource_group" "state" {
  name     = "rg-tfstate"
  location = "eastus"
  tags     = local.tags
}

resource "azurerm_storage_account" "state" {
  name                            = "tfstate${random_string.suffix.result}"
  resource_group_name             = azurerm_resource_group.state.name
  location                        = azurerm_resource_group.state.location
  account_tier                    = "Standard"
  account_replication_type        = "LRS"
  min_tls_version                 = "TLS1_2"
  https_traffic_only_enabled      = true
  allow_nested_items_to_be_public = false

  # No account keys. Everyone who reads state signs in as themselves, and the
  # access shows up in the logs under their name.
  shared_access_key_enabled = false

  tags = local.tags

  blob_properties {
    # Every write keeps the previous version, so a bad apply is one restore away.
    versioning_enabled = true
    delete_retention_policy {
      days = 7
    }
  }
}

resource "azurerm_storage_container" "state" {
  name                  = "tfstate"
  storage_account_id    = azurerm_storage_account.state.id
  container_access_type = "private"
}

# Owner on a subscription manages storage accounts and still cannot read the
# blobs inside them. Reading and writing state needs this data role.
resource "azurerm_role_assignment" "runner" {
  scope                = azurerm_storage_account.state.id
  role_definition_name = "Storage Blob Data Contributor"
  principal_id         = data.azurerm_client_config.current.object_id
}

output "storage_account" {
  description = "Account containing state."
  value       = azurerm_storage_account.state.name
}

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 "azurerm" {
      resource_group_name  = "${azurerm_resource_group.state.name}"
      storage_account_name = "${azurerm_storage_account.state.name}"
      container_name       = "${azurerm_storage_container.state.name}"
      key                  = "CHANGE-ME.tfstate"
      use_azuread_auth     = true
    }
  EOT
}
