You need to enable JavaScript to run this app. 如何使用PowerShell对AKS REST API进行身份验证并查询集群列表
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell对AKS REST API进行身份验证并查询集群列表

调用AKS REST API的身份验证及实现方案

方案1:直接使用Invoke-RestMethod传递服务主体参数实现

你可以按照以下步骤完成身份验证并调用API:

  1. 先通过Azure AD OAuth2端点获取访问令牌,直接将客户端ID、客户端密钥、租户ID作为请求参数传入
# 定义所需参数
$tenantId = "你的Azure AD租户ID"
$clientId = "你创建的应用注册客户端ID"
$clientSecret = "应用注册的客户端密钥"
$subscriptionId = "目标Azure订阅ID"

# 构造令牌请求
$tokenAuthUri = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$tokenRequestBody = @{
    grant_type = "client_credentials"
    client_id = $clientId
    client_secret = $clientSecret
    resource = "https://management.azure.com"
}

# 请求获取访问令牌
$tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenAuthUri -Body $tokenRequestBody
$accessToken = $tokenResponse.access_token
  1. 携带访问令牌调用AKS集群列表API
$aksListUri = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.ContainerService/managedClusters?api-version=2023-10-01"
$aksHeaders = @{
    Authorization = "Bearer $accessToken"
}

# 调用API获取集群列表
$aksClusterList = Invoke-RestMethod -Method Get -Uri $aksListUri -Headers $aksHeaders
# 输出集群信息
$aksClusterList.value | Select-Object name, location, kubernetesVersion

注意:生产环境不要硬编码客户端密钥,可通过环境变量、Azure Key Vault等方式存储读取

方案2:更优的替代实现(推荐)

以下方案无需手动拼接OAuth认证请求,稳定性和安全性更高:

  • 使用官方Azure PowerShell模块调用:安装Az.ContainerService模块后,直接用服务主体完成身份验证,再调用内置cmdlet即可获取集群列表,无需手动处理API认证逻辑
# 转换客户端密钥为安全凭证
$secureSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($clientId, $secureSecret)
# 用服务主体登录Azure
Connect-AzAccount -ServicePrincipal -Credential $psCred -Tenant $tenantId -Subscription $subscriptionId
# 直接获取AKS集群列表
Get-AzAksCluster | Select-Object Name, Location, KubernetesVersion
  • 使用Azure CLI调用:已安装Azure CLI的场景下,可直接执行az aks list获取集群列表,也可通过az account get-access-token --resource https://management.azure.com获取访问令牌后再传入Invoke-RestMethod使用
  • 敏感信息优化存储:生产环境客户端密钥建议存储在Azure Key Vault中,通过Get-AzKeyVaultSecret读取,避免明文泄露。

内容的提问来源于stack exchange,提问作者Sameer Mhaisekar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 09:36:06