Nick
Nick

Reputation: 1

Soft delete and Purge Protection should be enabled and retention days should be 90 days as Terraform error

We are using terraform to deploy azure key vault, getting error to enable Soft delete and Purge Protection should be enabled and retention days should be 90 days, as we have already given the purge protection and retention days in the terraform configuration files, getting below error to enable purge protection and retention days.


Error: creating Key Vault (Subscription: "XXX" Resource Group Name: "AZR-WHK-Appservice-POC" Key Vault Name: "kv-sctddi-poc"): performing CreateOrUpdate: vaults.VaultsClient#CreateOrUpdate: Failure sending request: StatusCode=0 -- Original Error: Code="RequestDisallowedByPolicy" Message="Resource 'kv-sctddi-p oc' was disallowed by policy. Reasons: 'Soft delete and Purge Protection should be enabled and retention days should be 90 days'. See error details for policy resource IDs." Target="kv-sctddi-poc" AdditionalInfo=[{"info ":{"evaluationDetails":{"evaluatedExpressions":[{"expression":"type","expressionKind":"Field","expressionValue":"Microsoft.KeyVault/vaults","operator":"Equals","path":"type","result":"True","targetValue":"Microsoft.KeyV

ault/vaults"},{"expression":"Microsoft.KeyVault/vaults/createMode","expressionKind":"Field","expressionValue":"default","operator":"Equals","path":"properties.createMode","result":"False","targetValue":"recover"},{"expr ession":"Microsoft.KeyVault/vaults/softDeleteRetentionInDays","expressionKind":"Field","operator":"NotEquals","path":"properties.softDeleteRetentionInDays","result":"True","targetValue":"90"}],"reason":"Soft delete and Purge Protection should be enabled and retention days should be 90 days"},"policyAssignmentDisplayName":"VPCx Landing Zone KeyVault","policyAssignmentId":"/providers/Microsoft.Management/managementGroups/Production/prov iders/Microsoft.Authorization/policyAssignments/vpcx-lzn-keyvault","policyAssignmentName":"vpcx-lzn-keyvault","policyAssignmentParameters":{},"policyAssignmentScope":"/providers/Microsoft.Management/managementGroups/Pro duction","policyDefinitionDisplayName":"VPCx - Key vaults should have soft delete and purge protection enabled and retention set as 90 days","policyDefinitionEffect":"Deny","policyDefinitionId":"/providers/Microsoft.Man agement/managementGroups/Production/providers/Microsoft.Authorization/policyDefinitions/vpcx-lzn-keyvault-enable-soft-delete-purge-retention-days-90","policyDefinitionName":"vpcx-lzn-keyvault-enable-soft-delete-purge-re tention-days-90","policyDefinitionReferenceId":"vpcx-lzn-keyvault-enable-soft-delete-purge-retention-days-90","policyExemptionIds":[],"policySetDefinitionDisplayName":"VPCx Landing Zone KeyVault Baseline","policySetDefi nitionId":"/providers/Microsoft.Management/managementGroups/Production/providers/Microsoft.Authorization/policySetDefinitions/vpcx-landingzone-keyvault-baseline","policySetDefinitionName":"vpcx-landingzone-keyvault-baseline"},"type":"PolicyViolation"}] with azurerm_key_vault.azure_key_vault, on main.tf line 122, in resource "azurerm_key_vault" "azure_key_vault": 122: resource "azurerm_key_vault" "azure_key_vault"

data "azurerm_client_config" "current" {}

data "azuread_service_principal" "azure_service_app_principle" {
  client_id = "XXX"
}


resource "tls_private_key" "ssh" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

resource "azurerm_key_vault_secret" "azure_key_vault" {
  name         = "azure-key-vault-secret"
  value        = "sctddi"
  key_vault_id = azurerm_key_vault.azure_key_vault.id
  depends_on   = [azurerm_key_vault.azure_key_vault]
}

resource "azurerm_key_vault_secret" "ssh-private-key" {
  name         = "ssh-private-key"
  value        = tls_private_key.ssh.private_key_pem
  key_vault_id = azurerm_key_vault.azure_key_vault.id
  depends_on   = [azurerm_key_vault.azure_key_vault]


}
resource "azurerm_key_vault_secret" "ssh-public-key-pem" {
  name         = "ssh-public-key-pem"
  value        = tls_private_key.ssh.public_key_pem
  key_vault_id = azurerm_key_vault.azure_key_vault.id
  depends_on   = [azurerm_key_vault.azure_key_vault]


}
resource "azurerm_key_vault_secret" "ssh-public-key-openssh" {
  name         = "ssh-public-key-openssh"
  value        = tls_private_key.ssh.public_key_openssh
  key_vault_id = azurerm_key_vault.azure_key_vault.id
  depends_on   = [azurerm_key_vault.azure_key_vault]


}

resource "azurerm_key_vault" "azure_key_vault" {

  depends_on = [data.azurerm_client_config.current, data.azuread_service_principal.azure_service_app_principle]


  enable_rbac_authorization     = true
  purge_protection_enabled      = true
  soft_delete_retention_days    = 90
  enabled_for_disk_encryption   = true
  sku_name                      = "standard"
  public_network_access_enabled = false
  name                          = "kv-sctddi-poc"
  location                      = var.location
  resource_group_name           = var.resourcegroupname
  tenant_id                     = data.azurerm_client_config.current.tenant_id


  network_acls {
    default_action = "Deny"
    bypass         = "AzureServices"
  }


  access_policy {

    tenant_id = data.azurerm_client_config.current.tenant_id
    object_id = data.azurerm_client_config.current.object_id

    key_permissions = [
      "Get", "List", "Update", "Create", "Import", "Delete", "Recover", "Backup", "Restore", "Decrypt",
      "Encrypt", "UnwrapKey", "WrapKey", "Verify",
      "Sign", "Purge", "Release", "Rotate", "GetRotationPolicy", "SetRotationPolicy"
    ]
    secret_permissions = ["Get", "List", "Set", "Delete", "Recover", "Backup", "Restore", "Purge"]

    storage_permissions = [
      "Get", "Backup", "Delete", "DeleteSAS", "Get", "GetSAS", "List", "ListSAS", "Purge",
      "Recover", "RegenerateKey", "Restore", "Set", "SetSAS", "Update"
    ]


  }

}

{
  "properties": {
    "displayName": "VPCx - Key vaults should have soft delete and purge protection enabled and retention set as 90 days",
    "policyType": "Custom",
    "mode": "All",
    "description": "Accidental deletion of a key vault can lead to permanent data loss. Soft delete allows you to recover an accidently deleted key vault for a retention period configured to a provided number of days. Purge protection protects you from insider attacks by enforcing a mandatory retention period for soft deleted key vaults. No one inside your organization or Microsoft will be able to purge your key vaults during the soft delete retention period.     ",
    "metadata": {
      "category": "Key Vault",
      "createdBy": "",
      "createdOn": "2024-04-05T12:25:59.6392467Z",
      "updatedBy": null,
      "updatedOn": null
    },
    "version": "1.0.0",
    "parameters": {
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "The effect determines what happens when the policy rule is evaluated to match"
        },
        "allowedValues": [
          "Audit",
          "Deny",
          "Disabled"
        ],
        "defaultValue": "Deny"
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.KeyVault/vaults"
          },
          {
            "not": {
              "field": "Microsoft.KeyVault/vaults/createMode",
              "equals": "recover"
            }
          },
          {
            "anyOf": [
              {
                "field": "Microsoft.KeyVault/vaults/enableSoftDelete",
                "exists": "false"
              },
              {
                "field": "Microsoft.KeyVault/vaults/enablePurgeProtection",
                "exists": "false"
              },
              {
                "field": "Microsoft.KeyVault/vaults/enableSoftDelete",
                "equals": "false"
              },
              {
                "field": "Microsoft.KeyVault/vaults/enablePurgeProtection",
                "equals": "false"
              },
              {
                "field": "Microsoft.KeyVault/vaults/softDeleteRetentionInDays",
                "notEquals": "90"
              }
            ]
          }
        ]
      },
      "then": {
        "effect": "[parameters('effect')]"
      }
    },
    "versions": [
      "1.0.0"
    ]
  },
  "id": "/providers/Microsoft.Management/managementGroups/Production/providers/Microsoft.Authorization/policyDefinitions/vpcx-lzn-keyvault-enable-soft-delete-purge-retention-days-90",
  "type": "Microsoft.Authorization/policyDefinitions",
  "name": "vpcx-lzn-keyvault-enable-soft-delete-purge-retention-days-90",
  "systemData": {
    "createdBy": "daab",
    "createdByType": "Application",
    "createdAt": "2024-04-05T12:25:59.6005721Z",
    "lastModifiedBy": "aab",
    "lastModifiedByType": "Application",
    "lastModifiedAt": "2024-04-05T12:25:59.6005721Z"
  }
}

Upvotes: 0

Views: 456

Answers (1)

Venkat V
Venkat V

Reputation: 7614

The policy expects the Microsoft.KeyVault/vaults/enableSoftDelete to be enabled. However, Terraform does not have an argument to enable soft delete in its code, while the CLI and Portal accept it.

By default, Terraform supports enabling purge protection and soft delete options during Key Vault creation.

  purge_protection_enabled      = true
  soft_delete_retention_days    = 90

To resolve the issue, you may remove the below part from your policy or run CLI commands within Terraform.

{  
"field":  "Microsoft.KeyVault/vaults/enableSoftDelete",  "exists":  "false"  
},

Azure Policy

{
  "mode": "All",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "type",
          "equals": "Microsoft.KeyVault/vaults"
        },
        {
          "anyOf": [
            {
              "field": "Microsoft.KeyVault/vaults/enablePurgeProtection",
              "exists": "false"
            },
            {
              "field": "Microsoft.KeyVault/vaults/softDeleteRetentionInDays",
              "notEquals": "90"
            }
          ]
        }
      ]
    },
    "then": {
      "effect": "[parameters('effect')]"
    }
  },
  "parameters": {
    "effect": {
      "type": "String",
      "metadata": {
        "displayName": "Effect",
        "description": "The effect determines what happens when the policy rule is evaluated to match"
      },
      "allowedValues": [
        "Audit",
        "Deny",
        "Disabled"
      ],
      "defaultValue": "Deny"
    }
  }
}

While creating the Key vault from portal policy is blocking resource creation if retention days are set to 75 days with purge protection enabled

enter image description here

While creating the Key vault from portal policy is blocking resource creation if retention days are set to 75 days with purge protection enabled

enter image description here

Azure CLI command is blocking resource creation if retention days are set to 75 with purge protection enabled

enter image description here

Azure CLI command is blocking resource creation if retention days are set to 90 with purge protection disabled

enter image description here

The policy is accepted the Key vault creation with Purge protection enabled and soft deleted days 90 days from both CLI and Portal.

enter image description here

Terraform with Azure CLI

    provider "azurerm" {
      features {}
    }
    
    resource "null_resource" "powershell" {
      provisioner "local-exec" {
        command = <<-EOT
        az keyvault create --location EastUS --name kv-sytedctddi-poc1dr --resource-group Venkat --sku standard --enable-rbac-authorization --bypass AzureServices --default-action Deny --retention-days 90 --enable-purge-protection
        EOT
      }
    }

Terraform apply

enter image description here

Portal View

enter image description here

Upvotes: 0

Related Questions