Sample - Enforce tag match pattern for tag values

Require that a tag value meets a match pattern. Specify the allowed pattern in the policy rule.

If you don't have an Azure subscription, create a free account before you begin.

Sample template

{
    "properties": {
        "displayName": "Use match condition on tag value.",
        "description": "Enforce a text pattern on tag value.",
        "mode": "All",
        "policyRule": {
            "if": {
                "not": {
                    "field": "tags.date",
                    "match": "##-???-####"
                }
            },
            "then": {
                "effect": "deny"
            }
        }
    }
}

You can deploy this template using the Azure portal, with PowerShell or with the Azure CLI.

Deploy with the portal

Deploy the Policy sample to Azure

Deploy with PowerShell

This sample requires Azure PowerShell. Run Get-Module -ListAvailable Az to find the version. If you need to install or upgrade, see Install Azure PowerShell module.

Run Connect-AzAccount to create a connection with Azure.

$definition = New-AzPolicyDefinition -Name "enforce-tag-match-pattern" -DisplayName "Ensure that a tag value matches a text pattern." -description "Ensure that a tag value matches a text pattern." -Policy 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/TextPatterns/enforce-tag-match-pattern/azurepolicy.rules.json' -Parameter 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/TextPatterns/enforce-tag-match-pattern/azurepolicy.parameters.json' -Mode All
$definition
$assignment = New-AzPolicyAssignment -Name <assignmentname> -Scope <scope> -PolicyDefinition $definition
$assignment

Clean up PowerShell deployment

Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup

Deploy with Azure CLI

To run this sample, make sure you have installed the latest version of the Azure CLI. To start, run az login to create a connection with Azure.

This sample works in a Bash shell. For options on running Azure CLI scripts on Windows client, see Install the Azure CLI on Windows.

az policy definition create --name 'enforce-tag-match-pattern' --display-name 'Ensure that a tag value matches a text pattern.' --description 'Ensure that a tag value matches a text pattern.' --rules 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/TextPatterns/enforce-tag-match-pattern/azurepolicy.rules.json' --params 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/TextPatterns/enforce-tag-match-pattern/azurepolicy.parameters.json' --mode All

az policy assignment create --name <assignmentname> --scope <scope> --policy "enforce-tag-match-pattern"

Clean up Azure CLI deployment

Run the following command to remove the resource group, VM, and all related resources.

az group delete --name myResourceGroup --yes

Next steps