在 Azure 中通过 Client ID 查找用户分配的托管身份(UAI)
用户分配的托管身份(User Assigned Identity,UAI)是可在多个 Azure 资源间共享的托管身份。很多场景中会用到 UAI 的 Object ID 来查找身份,但有时我们只知道该身份的 Client ID(客户端 ID),需要通过 Client ID 反查 UAI。Azure 门户并未提供跨订阅按 Client ID 搜索 UAI 的直接功能,因此需要借助命令行或资源查询来完成此操作。
使用 az identity list 命令 🔗
使用 az identity list 命令可以获取当前订阅下的所有 UAI 的列表;可通过传入 --query 参数来过滤出 Client ID 匹配的 UAI 信息。具体命令如下:
az identity list --query "[?clientId=='<Your client id>']"
但这个命令有个缺陷:如果不能确定 UAI 在哪个订阅中,就需要在每个订阅中都执行一次这个命令,效率非常低。
注意:az identity list 只在指定的订阅范围内搜索。你可以通过 --subscription 指定订阅,例如:
az identity list --subscription <subscription-id> --query "[?clientId=='<your-client-id>']"
当需要跨多个订阅搜索时,单独在每个订阅运行该命令会比较低效,此时推荐使用 Azure Resource Graph。
使用 Azure Resource Graph 查询 🔗
使用 Azure Resource Graph 查询,可以在所有订阅中查询 UAI 的信息。在 Azure 门户中打开 Resource Graph Explorer,使用如下查询语句即可:
resources
| where type == "microsoft.managedidentity/userassignedidentities"
| where properties.clientId == "Your client id"
| project name, resourceGroup, subscriptionId, id, location, properties.principalId
如果需要查询多个 Client ID 的 UAI 信息,可以使用 in 语句:
| where type == "microsoft.managedidentity/userassignedidentities"
| where properties.clientId in ("Your client id 1", "Your client id 2")
| project name, resourceGroup, subscriptionId, id, location, properties.principalId
除此之外,也可以在本地使用 Azure CLI 的 Resource Graph 扩展来运行该查询:
# 安装扩展(如尚未安装)
az extension add --name resource-graph
# 在所有可访问订阅中运行查询
az graph query -q "resources | where type == 'microsoft.managedidentity/userassignedidentities' | where properties.clientId == '<your-client-id>' | project name, resourceGroup, subscriptionId, id, location, properties.principalId"
如果需要一次查询多个 Client ID,可将 == 改为 in ("id1","id2")。查询返回的 principalId 即为该身份对应的对象 ID(Object ID)。
Resource Graph 的优点是可跨订阅、快速返回结果,适合在不知道目标订阅时定位 UAI。