Forum Discussion
dkappelle
Sep 20, 2024Copper Contributor
Adding VM Instance View Details, e.g. osName, to the VM Resource Object JSON (for Custom Policy Use)
I'm requesting to add more details to the JSON of the VM resource object, particularly from the VM instance view data. This is to include operating system information, such as the name and version (...
Kidd_Ip
Jan 02, 2025MVP
Try below:
Step 1: Retrieve VM Instance View Data
You can use Azure CLI or PowerShell to retrieve the VM instance view data, which includes the operating system information.
Using Azure CLI:
az vm get-instance-view --resource-group <ResourceGroupName> --name <VMName> --query instanceView
Using PowerShell:
Get-AzVM -ResourceGroupName <ResourceGroupName> -Name <VMName> -Status
Step 2: Add Custom Tags or Metadata
You can add custom tags or metadata to your VM resource object to include the operating system information. This can be done using Azure CLI, PowerShell, or directly in the ARM template.
Using Azure CLI:
az vm update --resource-group <ResourceGroupName> --name <VMName> --set tags.osName=<OSName> tags.osVersion=<OSVersion>
Using PowerShell:
Set-AzVM -ResourceGroupName <ResourceGroupName> -Name <VMName> -Tag @{osName="<OSName>"; osVersion="<OSVersion>"}
Step 3: Create or Update ARM Template
Modify your ARM template to include the custom tags or metadata. Here’s an example snippet:
{
"type": "Microsoft.Compute/virtualMachines",
"apiVersion": "2021-07-01",
"location": "[resourceGroup().location]",
"properties": {
"osProfile": {
"computerName": "[parameters('vmName')]",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPassword')]"
},
"tags": {
"osName": "[parameters('osName')]",
"osVersion": "[parameters('osVersion')]"
}
}
}
Step 4: Create a Custom Policy
Create a custom Azure Policy to enforce the presence of these tags. Here’s an example policy definition:
{
"properties": {
"displayName": "Ensure VMs have OS information tags",
"policyType": "Custom",
"mode": "Indexed",
"parameters": {},
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Compute/virtualMachines"
},
{
"field": "tags.osName",
"exists": "false"
},
{
"field": "tags.osVersion",
"exists": "false"
}
]
},
"then": {
"effect": "deny"
}
}
}
}
Step 5: Assign the Policy
Assign the custom policy to your subscription or resource group to ensure compliance.