Creating an Azure Policy to update a tag based off another tag in same resource

Teresa Silvestri 5 Reputation points
2023-04-11T15:46:33.24+00:00

I am trying to create an Azure Policy that looks for a specific tag and if that tag exists, then it should add or replace a new tag with the value of the existing tag. How do I retrieve the value of the existing tag?

{
  "mode": "All",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "tags['newtag']",
          "exists": "false"
        },
        {
          "field": "tags['kubernetes.io-created-for-pvc-namespace']",
          "exists": "true"
        },
        {
          "anyOf": [
            {
              "field": "type",
              "equals": "Microsoft.Compute/disks"
            },
            {
              "field": "type",
              "equals": "Microsoft.Compute/snapshots"
            }
          ]
        }
      ]
    },
    "then": {
      "effect": "modify",
      "details": {
        "roleDefinitionIds": [
          "/providers/microsoft.authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
        ],
        "operations": [
          {
            "operation": "addOrReplace",
            "field": "tags['newtag']",
            "value": "retrieve value from existing tags['kubernetes.io-created-for-pvc-namespace']"
          }
        ]
      }
    }
  },
  "parameters": {}
}
Azure Policy
Azure Policy
An Azure service that is used to implement corporate governance and standards at scale for Azure resources.
1,019 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AnuragSingh-MSFT 21,551 Reputation points Moderator
    2023-04-12T07:37:22.3733333+00:00

    @Teresa Silvestri , thank you for posting this question on Q&A.

    I see that you are trying to add/update a new tag based on the value of another tag. This is not possible based on the resource's tag itself, as there is no direct way to refer to the resource object in ARM template. Usually, such a reference requires some form of reference() or resourceId() function. Please see the following link for details - reference() function in ARM template

    However, if you are trying to update tag values based on a Tag which is available on ResourceGroup containing the resource, it can be done as shown in the sample here - Use tags with parameters. You may consider adding the required tag to ResourceGroup() and inheriting it to all the resources within it.

    Another way to achieve this (without the use of Policy) is by using PowerShell scripting with Az modules. For one such example, please see - How to bulk update Tags with wrong casing

    Hope this helps. Please let us know if you have any questions.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.