# state-backend / azure / t1 "Standard" # # The account every other Terraform folder keeps its state in: your own key, # versions and deletes recoverable for a set time, closed to the internet, and # protected from deletion by a management lock. # # Verify: # Start terraform plan in two terminals against a folder using this backend. # The second cannot take the lease. data "azurerm_client_config" "current" {} resource "random_string" "suffix" { length = 6 special = false upper = false } locals { clean = replace(lower(var.name), "/[^a-z0-9]/", "") storage_name = "${substr(local.clean, 0, 16)}${random_string.suffix.result}" # Whoever applies this folder always gets access, so the first init against # the new backend works without a second change. writers = distinct(concat([data.azurerm_client_config.current.object_id], var.state_writers)) tags = merge({ owner = var.owner environment = var.environment data_classification = "restricted" managed_by = "terraform" }, var.extra_tags) } resource "azurerm_resource_group" "state" { name = "rg-${var.name}" location = var.location tags = local.tags } resource "azurerm_storage_account" "state" { name = local.storage_name resource_group_name = azurerm_resource_group.state.name location = azurerm_resource_group.state.location account_tier = "Standard" account_replication_type = "GRS" min_tls_version = "TLS1_2" https_traffic_only_enabled = true allow_nested_items_to_be_public = false shared_access_key_enabled = false infrastructure_encryption_enabled = true tags = local.tags identity { type = "UserAssigned" identity_ids = [azurerm_user_assigned_identity.storage.id] } customer_managed_key { key_vault_key_id = azurerm_key_vault_key.state.versionless_id user_assigned_identity_id = azurerm_user_assigned_identity.storage.id } blob_properties { versioning_enabled = true change_feed_enabled = true delete_retention_policy { days = var.keep_deleted_days } container_delete_retention_policy { days = var.keep_deleted_days } } network_rules { default_action = "Deny" bypass = ["AzureServices"] ip_rules = var.allowed_ip_ranges } lifecycle { prevent_destroy = true } depends_on = [azurerm_role_assignment.storage_key_user] } resource "azurerm_storage_container" "state" { name = "tfstate" storage_account_id = azurerm_storage_account.state.id container_access_type = "private" } resource "azurerm_role_assignment" "writers" { for_each = toset(local.writers) scope = azurerm_storage_account.state.id role_definition_name = "Storage Blob Data Contributor" principal_id = each.value } # A management lock refuses deletion through the portal, the CLI, and Terraform # alike, for anyone, until someone removes the lock on purpose. resource "azurerm_management_lock" "state" { name = "do-not-delete-terraform-state" scope = azurerm_storage_account.state.id lock_level = "CanNotDelete" notes = "Stores Terraform state for every other folder. Remove this lock deliberately, never as a side effect." }