create azure policy that retrieves resource createdTime and adds a tag createdTime to the resource

25 Views Asked by At

Is it at all possible to retrieve the resource createdTime value and somehow add a createdTime tag to the resource with that value?

I can see the value I am interested in in the output of the following command: az resource list --subscription $subid --query "[].{name:name,createdTime:createdTime}" but not sure if possible to add something like that in a policy...

I tried defining a policy like this and it works for newly created resources using the current date, but I prefer to use a date from createdTime if at all possible to retrieve and use it instead.

{
  "if": {
    "allOf": [
      {
        "exists": false,
        "field": "tags['Last Built']"
      }
    ]
  },
  "then": {
    "details": {
      "operations": [
        {
          "field": "tags['Last Built']",
          "operation": "add",
          "value": "[concat(substring(utcNow(), 8, 2), '/', substring(utcNow(), 5, 2), '/', substring(utcNow(), 0, 4))]"
        }
      ],
      "roleDefinitionIds": [
        "/providers/Microsoft.Authorization/roleDefinitions/36243c78-bf99-498c-9df9-86d9f8d28608"
      ]
    },
    "effect": "modify"
  }
}
1

There are 1 best solutions below

0
Niclas On

There are many ways to do it.

For example take a look at this detailed blog: https://stellium.consulting/sem-categoria/automatically-delete-resources-utilizing-azure-automation/

{
  "mode": "All",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "tags['CreatedDate']",
          "exists": false
        }
      ]
    },
    "then": {
      "effect": "modify",
      "details": {
        "operations": [
          {
            "operation": "add",
            "field": "tags['CreatedDate']",
            "value": "[concat(substring(utcNow(), 5, 2), '/', substring(utcNow(), 8, 2), '/', substring(utcNow(), 0, 4), '-', substring(utcNow(), 11, 8))]"
          }
        ],
        "roleDefinitionIds": [
          "/providers/Microsoft.Authorization/roleDefinitions/36243c78-bf99-498c-9df9-86d9f8d28608"
        ]
      }
    }
  },
  "parameters": {}
}

See comments for creation date: https://techcommunity.microsoft.com/t5/core-infrastructure-and-security/tagging-azure-resources-with-a-creator/ba-p/1479819?wt.mc_id=MVP_323223