Search code examples
azureazure-aksazure-cliazure-managed-identity

Check User Managed Identity Exists Azure Cli


I am trying to check whether user managed identity already exists or not. when I try to list the managed identity using the show command it shows the result in dictionary.

az vmss identity show --name name-vmss --resource-group rg-name                                                                                                                  
{                                                                          
  "principalId": null,
  "tenantId": null,
  "type": "UserAssigned",
  "userAssignedIdentities": {
    "resource_id_of_managed_identity": {
      "clientId": GUID,
      "principalId":  GUID
    },
    "reosurce_id_of_managed_identity": {
      "clientId":  GUID,
      "principalId":  GUID
    }
  }
}

I tried to query through

az vmss identity show --name name-vmss --resource-group rg-name   --query "userAssignedIdentities", its listing 
{
 "reosurce_id_of_managed_identity": {
      "clientId": GUID,
      "principalId":  GUID
    },
    "reosurce_id_of_managed_identity": {
      "clientId":  GUID,
      "principalId":  GUID
    }
}

I tried to do contains with just name as well as the managed identity resource, but it returns empty

az vmss identity show --name name-vmss --resource-group rg-name  --query "[?contains(userAssignedIdentities,'mid-name')]" 

az vmss identity show --name name-vmss --resource-group rg-name  --query "[?contains(userAssignedIdentities,'reosurce_id_of_managed_identity')]" 

I tried to access through default key value pair, it fails.

az vmss identity show --name name-vmss --resource-group rg-name  --query "userAssignedIdentities['reosurce_id_of_managed_identity']"

How to check whether the resource already has particular managed identity assigned or not.


Solution

  • I tried to do contains with just name as well as the managed identity resource, but it returns empty.

    az vmss identity show --name name-vmss --resource-group rg-name  --query "[?contains(userAssignedIdentities,'mid-name')]" 
    
    az vmss identity show --name name-vmss --resource-group rg-name  --query "[?contains(userAssignedIdentities,'reosurce_id_of_managed_identity')]"
    

    To check the resource already has particular managed identity assigned or not, you can use --query parameter with filter to check with Managed Identity Name.

    Here is the updated command.

    az vmss identity show --name <VMSS-Name> --resource-group <RG-NAME> -o json | jq '.userAssignedIdentities | with_entries(select(.key | contains("VMSSidentity-Name")))'
    

    I have used jq to filter the userAssignedIdentities dictionary, keeping only the entries that contain VMSSidentity-Name in the key.

    Output:

    enter image description here