# compliance-evaluation / azure / t0 "Quick start"
#
# The Microsoft cloud security benchmark assigned to one subscription, so
# Azure Policy grades every resource against it, and an email each time a
# resource is created or changed into a non-compliant state.
#
# Change the alert address below, then:
#   az login
#   export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
#   terraform init && terraform apply
#
# Verify: the first full evaluation takes a few hours. Then:
#   az policy state summarize --filter "policyAssignmentName eq 'security-benchmark'"

locals {
  alert_email = "security-alerts@example.com" # change me
  location    = "eastus"
}

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

provider "azurerm" {
  features {}
}

data "azurerm_subscription" "current" {}

# Looked up by name, so the template does not carry Microsoft's internal ID.
data "azurerm_policy_set_definition" "benchmark" {
  display_name = "Microsoft cloud security benchmark"
}

# Some benchmark policies can deploy settings, which needs an identity and a
# location on the assignment even when nothing is deployed.
resource "azurerm_subscription_policy_assignment" "benchmark" {
  name                 = "security-benchmark"
  display_name         = "Microsoft cloud security benchmark"
  subscription_id      = data.azurerm_subscription.current.id
  policy_definition_id = data.azurerm_policy_set_definition.benchmark.id
  location             = local.location

  identity {
    type = "SystemAssigned"
  }
}

resource "azurerm_resource_group" "alerts" {
  name     = "rg-compliance-alerts"
  location = local.location
  tags = {
    owner               = "security-engineering"
    environment         = "prod"
    data_classification = "internal"
    managed_by          = "terraform"
  }
}

resource "azurerm_monitor_action_group" "security" {
  name                = "compliance-alerts"
  resource_group_name = azurerm_resource_group.alerts.name
  short_name          = "compliance"
  email_receiver {
    name          = "security"
    email_address = local.alert_email
  }
}

# Azure Policy writes an audit event to the Activity Log whenever a created or
# updated resource fails a policy in audit mode.
resource "azurerm_monitor_activity_log_alert" "noncompliant" {
  name                = "noncompliant-resource"
  resource_group_name = azurerm_resource_group.alerts.name
  location            = "global"
  scopes              = [data.azurerm_subscription.current.id]
  description         = "A resource was created or changed into a state the security benchmark flags."
  criteria {
    category       = "Policy"
    operation_name = "Microsoft.Authorization/policies/audit/action"
  }
  action {
    action_group_id = azurerm_monitor_action_group.security.id
  }
}
