Azure Policy - Set expiry for keys/secrets - azure

I am trying to write an Azure Policy that checks if a Azure key has an expiry date, if it does not then I want to do a DeployIfNotExists effect to set one. However I am getting a "ResourceNotFound" error.
Note: The "if" statement without the "then" statement works fine, when I run this policy it shows me which keys do not have a expiration date. Getting the issue when I add in the deployifnotexist effect.
{
"mode": "All",
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.KeyVault/vaults/keys"
},
{
"field": "Microsoft.KeyVault/vaults/keys/attributes.exp",
"exists": false
}
]
},
"then": {
"effect": "deployIfNotExists",
"details": {
"type": "Microsoft.KeyVault/vaults/keys",
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635"
],
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"resources": [
{
"type": "Microsoft.KeyVault/vaults/keys",
"apiVersion": "2021-06-01-preview",
"properties": {
"exp": "10000"
}
}
]
}
}
}
}
}
},
"parameters": {}
}

Here you are working at the Data layer of the Key Vault, what is inside of it (Keys, Secrets, Certificates).
In that case, when it is not about the infrastructure as such (the configuration of the Key Vault itself), you have to use the Microsoft.KeyVault.Data mode for your custom policy instead of All.
That said, DeployIfNotExist policies are not yet supported - see official documentation about Azure Policy for Key Vault. You can only Audit or Deny.

Related

Azure policy fails to deploy a policy assignment with deployIfNotExists

I have a resource whitelist policy defined as follows:
{
"properties": {
"displayName": "Deny resource creation if not in whitelist",
"policyType": "Custom",
"mode": "Indexed",
"description": "This policy denies the creation resources which are not allowed in the whitelist.",
"policyRule": {
"if": {
"not": {
"field": "type",
"in": [
"Microsoft.KeyVault/vaults",
"Microsoft.Storage/storageAccounts"
]
}
},
"then": {
"effect": "Deny"
}
}
},
"id": "<POLICYDEFINITIONID>",
"type": "Microsoft.Authorization/policyDefinitions",
"name": "Deny_resource_creation_if_not_in_whitelist",
}
This policy works as expected when assigned to a resource group.
I also have a second policy assigned at the subscription level to deploy the first policy on resource groups with names starting with "rg-*":
{
"properties": {
"displayName": "Deploy resource whitelist policy",
"policyType": "Custom",
"mode": "All",
"description": "This policy assigns the resource whitelist policy to resource groups starting with rg-*.",
"policyRule": {
"if": {
"allOf": [
{
"equals": "Microsoft.Resources/subscriptions/resourceGroups",
"field": "type"
},
{
"field": "name",
"like": "rg-*"
}
]
},
"then": {
"details": {
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"resources": [
{
"apiVersion": "2022-06-01",
"name": "[guid('<POLICYDEFINITIONID>', resourceGroup().name)]",
"properties": {
"displayName": "Deny resource creation if not in whitelist",
"enforcementMode": "Default",
"policyDefinitionId": "<POLICYDEFINITIONID>"
},
"type": "Microsoft.Authorization/policyAssignments"
}
]
}
}
},
"evaluationDelay": "AfterProvisioning",
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635"
],
"type": "Microsoft.Authorization/policyAssignments"
},
"effect": "DeployIfNotExists"
}
}
},
"id": "",
"type": "Microsoft.Authorization/policyDefinitions",
"name": "Deploy_resource_whitelist_policy",
}
The second policy is evaluated, I can see a successful deployIfNotExists event but in fact the assignment is not created.
A few additional facts:
I successfully deployed the policy assignment ARM template from the Azure portal
When replacing the policy assignment ARM template with a simple storage account ARM template it works, a storage account is created in the resource group.
Any help would be much appreciated.
Your policy assignment in the example seems to be missing a scope property to assign it to the given resourcegroup. Try adding a scope property to the policy assignment.
"template": {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"resources": [
{
"apiVersion": "2022-06-01",
"name": "[guid('<POLICYDEFINITIONID>', resourceGroup().name)]",
"properties": {
"displayName": "Deny resource creation if not in whitelist",
"enforcementMode": "Default",
"policyDefinitionId": "<POLICYDEFINITIONID>"
"scope": "[subscriptionResourceId('Microsoft.Resources/resourceGroups', resourceGroup().name)]"
},
"type": "Microsoft.Authorization/policyAssignments"
}```
I finally solved this using only the first policy and a value expression condition:
{
"properties": {
"displayName": "Deny resource creation if not in whitelist",
"policyType": "Custom",
"mode": "Indexed",
"description": "This policy denies the creation resources which are not allowed in the whitelist.",
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"notIn": [
"Microsoft.KeyVault/vaults",
"Microsoft.Storage/storageAccounts"
]
},
{
"value": "[resourceGroup().name]",
"like": "rg-*"
}
]
},
"then": {
"effect": "Deny"
}
}
},
"id": "<POLICYDEFINITIONID>",
"type": "Microsoft.Authorization/policyDefinitions",
"name": "Deny_resource_creation_if_not_in_whitelist",
}

Create resource group with azure policy in each subscription

I'm trying to create an Azure policy for creating a RG for every subscription under my tenant.
I created this custom policy like I saw in some example but nothing is being created.
The custom policy:
{
"properties": {
"displayName": "Create resource group if not exists",
"description": "This policy will create resource group if not exists",
"policyType": "Custom",
"mode": "All",
"metadata": {
"version": "1.0.0",
"category": "Resource Management"
},
"parameters": {},
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Resources/subscriptions"
}
]
},
"then": {
"effect": "deployIfNotExists",
"details": {
"type": "Microsoft.Resources/deployments",
"name": "createResourceGroup",
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
],
"existenceCondition": {
"field": "name",
"equals": "TestRG"
},
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "",
"parameters": {},
"variables": {},
"resources": [
{
"type": "Microsoft.Resources/resourceGroups",
"apiVersion": "2018-05-01",
"name": "TestRG",
"location": "eastus",
"tags": {
"Test": "Infra"
},
"properties": {}
}
]
},
"parameters": {}
}
}
}
}
}
}
}
If you have any ideas I would really appreciate that.
Thanks.
The alias "Microsoft.Resources/subscriptions" which you are referring to does not exist within the available aliases, hence the custom policy isn't working as expected. You can verify the list of available aliases using the PowerShell command "Get-AzPolicyAlias".
To raise a new policy alias request, you need to create ticket with Microsoft Support team.

Azure policy not creating roles for managed identity when deployed through devOps

I created an azure policy via devops . I had a role enabled as given below(storage contributor). The identity was created for the policy but there was no role assigned to it. So I had to manually create it to run the remediation task. Shouldn't the policy create the role itself? or the deployment?
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/17d1049b-9a84-46fb-8f53-869881c3d3ab"
],
We deploy it as an arm template using New-AzDeployment
This is the full template
{
"$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"policyDefinitionName": {
"type": "string"
}
},
"resources": [{
"type": "Microsoft.Authorization/policyDefinitions",
"name": "[parameters('policyDefinitionName')]",
"apiVersion": "2019-09-01",
"properties": {
"displayName": "Deploy Soft-Delete for Blobs",
"mode": "All",
"description": "This policy enables soft-delete for blobs.",
"parameters": {
"retentionInDays": {
"type": "Integer",
"metadata": {
"displayName": "Retention in days",
"description": "This defines how long the deleted object should be retained for. Allowed values are 1 to 365."
}
}
},
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Storage/storageAccounts"
},
{
"field": "kind",
"in": [
"Storage",
"StorageV2",
"BlobStorage",
"BlockBlobStorage"
]
},
{
"field": "Microsoft.Storage/storageAccounts/isHnsEnabled",
"equals": false
},
]
},
"then": {
"effect": "DeployIfNotExists",
"details": {
"type": "Microsoft.Storage/storageAccounts/blobServices",
"existenceCondition": {
"field": "Microsoft.Storage/storageAccounts/blobServices/default.deleteRetentionPolicy.enabled",
"equals": true
},
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/17d1049b-9a84-46fb-8f53-869881c3d3ab"
],
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"storageAccountName": {
"type": "string"
},
"retentionInDays": {
"type": "int"
}
},
"variables": {},
"resources": [
{
"name": "[[concat(parameters('storageAccountName'), '/default')]",
"type": "Microsoft.Storage/storageAccounts/blobServices",
"apiVersion": "2019-06-01",
"properties": {
"deleteRetentionPolicy": {
"enabled": true,
"days": "[[parameters('retentionInDays')]"
}
}
}
],
"outputs": {}
},
"parameters": {
"storageAccountName": {
"value": "[[field('name')]"
},
"retentionInDays": {
"value": "[[parameters('retentionInDays')]"
}
}
}
}
}
}
}
}
}]
}
POLICY DEFINITION DEPLOYMENT
(Optional) INITIATIVE DEFINTION DEPLOYMENT
POLICY ASSIGNMENT DEPLOYMENT <- This is where you add your role assignment.
The role assignment must be made for the managed identity created by the policy assignment. If you create the policy assignment from the portal, I believe this is done automatically for you. An ARM template in DevOps will require a manual definition.
The policy assignment therefore must also be deployed with a role assignment.
I would recommend using a separate ARM template for assignments due to issues using "dependsOn" between definitions, initiatives, and assignments. Therefore your policy assignment template with the role assignment would stand alone and look something like the example template below.
I know it's not related to your question, but it's annoying enough to mention. In my experience, I've had to delay 2 minutes between definition deployments and subsequent initiative deployments and then another 2 minutes before assignment deployments in order to avoid 404 errors on dependencies.
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {},
"variables": {
"scope": "[concat('/subscriptions/', subscription().subscriptionId, '/')]"
},
"resources": [
{
"type": "Microsoft.Authorization/policyAssignments",
"apiVersion": "2019-09-01",
"name": "my-policy-assignment",
"location": "westus2",
"identity": {
"type": "SystemAssigned"
},
"properties": {
"displayName": "My Policy Assignment",
"policyDefinitionId": "[concat(variables('scope'), 'providers/Microsoft.Authorization/policySetDefinitions/my-policy-initiative')]",
"scope": "[variables('scope')]",
"notScopes": [],
"parameters": {},
"description": "This is an example assignment for a Stack Overflow post.",
"metadata": {
"category": "My Category"
}
}
},
{
"type": "Microsoft.Authorization/roleAssignments",
"apiVersion": "2019-04-01-preview",
"name": "b74efc56-19fa-44a3-9665-49b08f7c384d",
"dependsOn": [
"my-policy-assignment"
],
"properties": {
"roleDefinitionId": "[concat(subscription().id, '/providers/Microsoft.Authorization/roleDefinitions/', '17d1049b-9a84-46fb-8f53-869881c3d3ab')]",
"principalType": "ServicePrincipal",
"delegatedManagedIdentityResourceId": "[concat(subscription().id, '/providers/Microsoft.Authorization/policyAssignments/', 'my-policy-assignment')]",
"principalId": "[toLower(reference(concat('/providers/Microsoft.Authorization/policyAssignments/', 'my-policy-assignment'), '2018-05-01', 'Full' ).identity.principalId)]"
}
}
]
}

Azure policy deployment using visual studio

I am trying to use in built allowed locations Azure policy.
Below my ARM template definition
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"listOfAllowedLocations": {
"type": "Array"
}
},
"variables": {},
"resources": [{
"type": "Microsoft.Authorization/policyDefinitions",
"name": "Test",
"apiVersion": "2018-03-01",
"properties": {
"displayName": "Test allowed locations",
"policyType": "BuiltIn",
"description": "This policy enables you to restrict the locations your organization can specify when deploying resources. Use to enforce your geo-compliance requirements.",
"parameters": {
"listOfAllowedLocations": {
"type": "Array",
"metadata": {
"description": "The list of locations that can be specified when deploying resources.",
"strongType": "location",
"displayName": "Allowed locations"
}
}
},
"policyRule": {
"if": {
"not": {
"field": "location",
"in": "[parameters('listOfAllowedLocations')]"
}
},
"then": {
"effect": "Deny"
}
}
}
}],
"outputs": {}
}
I am getting below error when I try to deploy this using Visual Studio deploy option
{
"error": {
"code": "InvalidPolicyUri",
"message": "The policy request scope '/subscriptions/xxx/resourcegroups/Test' should be '/', '/subscriptions/id' or '/providers/Microsoft.Management/managementGroups/id'."
}
}
I really appreciate if someone can guide me the right way for deploying policies using Visual Studio. This template will go into DevOps release pipeline later once it is successful in VS deploy testing.
I figured it out. By default visual studio uses resource group deployment, that is the reason this is not working. We need to use New-AzureRmDeployment instead of New-AzureRmResourceGroupDeployment.

Set Access key of service bus in Arm Template

I have trying to set up the access keys to an azure service bus in an azure resource manager template. No matter what I do the template ignores the keys and sets some random ones instead without giving any errors. I have the following parameters file:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"environmentName": { "value": "Integration" },
"primaryKey": {
"value": "<myKey1>"
},
"secondaryKey": {
"value": "<myKey2>"
}
}
}
where myKey are substitued the real value of the keys. I also have the following template (part of it below):
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"environmentName": {
"type": "string"
},
"primaryKey": {
"type": "string"
},
"secondaryKey": {
"type": "string"
}
},
"variables": {
"ServiceBus_ReadWriteKey": "[concat(parameters('environmentName'), '/ReadWrite')]",
"servicebus_namespace": "[parameters('environmentName')]",
"servicebus_topic_name": "[concat(parameters('environmentName'), '/products')]",
This is the resource that creates the access policy and should set it's keys:
{
"type": "Microsoft.ServiceBus/namespaces/AuthorizationRules",
"name": "[variables('ServiceBus_ReadWriteKey')]",
"apiVersion": "2015-08-01",
"scale": null,
"properties": {
"keyName": "ReadWrite",
"claimType": "SharedAccessKey",
"claimValue": "None",
"primaryKey": "[parameters('primaryKey')]",
"secondaryKey": "[parameters('secondaryKey')]",
"rights": [
"Listen",
"Send"
],
"revision": -1
},
"dependsOn": [
"[resourceId('Microsoft.ServiceBus/namespaces', variables('servicebus_namespace'))]"
]
},
The access policy is created, always with a random key, never the one I specified. How do I set this programmatically and what is wrong with the code above?
You are using a different api version as the sample you are using:
sample api version 2014-09-01
your api version 2015-08-01
try to change the api version to see if that causes the issue

Resources