运行 来自使用服务主体的发布管道的 Azure CLI 脚本 - invalid_client

Running Azure CLI script from release pipeline using Service Principal - invalid_client

我有一个 Azure CLI 脚本,它 运行 在云中运行得非常好 Shell 但是当我尝试将它包含在 devops 发布管道中时,我 运行 遇到了麻烦。出于调试目的,我已将脚本简化为以 Service Principal 身份登录,然后检索版本...

az login --service-principal -u http://[Service Principal name] -p [Service Principal password] --tenant [Service Principal tenant GUID]
az --version

...但还是报同样的错误

这是我的 Azure CLI 任务的属性:

脚本类型:Shell
脚本位置:Inline script
内联脚本:[同上]
脚本参数:
在脚本中访问服务主体详细信息:false
使用全局 Azure CLI 配置:false
工作目录:
标准错误失败:false
已启用:true
出现错误继续:false*
环境变量:

错误是:

2020-06-15T12:46:39.8710944Z ##[error]Error Code: [1]
2020-06-15T12:46:39.8724737Z ##[error]Error: Azure login failed
2020-06-15T12:46:39.8728448Z ##[error]Script failed with error: Get Token request returned http error: 401 and server response: {"error":"invalid_client","error_description":"AADSTS7000222: The provided client secret keys are expired. Visit the Azure Portal to create new keys for your app, or consider using certificate credentials for added security: https://docs.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials
Trace ID: d0f42793-739e-4ce9-9118-5049086aa800
Correlation ID: 2ad50471-9c2a-4c02-a4d0-189efad2f0c8
Timestamp: 2020-06-15 12:46:39Z","error_codes":[7000222],"timestamp":"2020-06-15 12:46:39Z","trace_id":"d0f42793-739e-4ce9-9118-5049086aa800","correlation_id":"2ad50471-9c2a-4c02-a4d0-189efad2f0c8","error_uri":"https://login.microsoftonline.com/error?code=7000222"}

我能够使用 Azure 云 Shell 作为此 服务主体 进行身份验证,所以我很困惑为什么我显然不能从在发布管道中。

* 我试过 Continue on error: true 虽然任务完成了,但输出中出现了同样的错误。

我认为这与我之前遇到的问题非常相似,当客户端密码中有特殊字符时会发生这种情况。

一种解决方法是转到 Azure 门户并不断生成新的机密,直到您获得其中没有特殊字符的机密。

https://github.com/ansible/ansible/issues/54914

在Azure CLI 中使用服务主体,无需手动登录。

正确的方法,请按照以下步骤操作。

1.From 错误消息,您的服务主体的 client secret(即 client key)已过期。所以你需要先检查它,导航到 azure portal -> Azure Active Directory -> App registrations -> All applications -> 找到与你的服务主体相关的 AD App -> Certificates & secrets -> 检查密钥是否过期。如果已过期,只需单击New client secret创建一个新的并保存值。

2.In devops,导航到 Project Settings -> Service connections -> New service connection -> Azure Resource Manager -> Service principal (manual).

然后用您的服务主体修复选项,您可以从您的 AD 应用在应用注册页面中获取值。 Service Principal Id就是Application (client) IDService principal key就是client secret

Subscription IdSubscription Name 是您要使用 Azure CLI 访问的,您可以在 azure 门户中找到它们。

输入值后 -> Verify -> Verify and save.

3.In 您的 Azure CLI 任务 -> Azure Resource Manager connection -> select 步骤 2 中的服务连接。在我的示例中,我测试在我的订阅是az webapp show --name xxxx --resource-group xxxx(注意:不需要手动使用az login,它将自动使用在服务连接中配置的服务主体登录)。

然后运行它并检查结果,它工作正常。