gpt4 book ai didi

powershell - VSTS 构建和 PowerShell 以及 AzureAD 身份验证

转载 作者:行者123 更新时间:2023-12-02 20:23:39 27 4
gpt4 key购买 nike

我有一个 VSTS 项目,通过服务主体通过 Azure 资源管理器终结点连接到 Azure 订阅。这对于我通过模板化、参数驱动的部署配置 ARM 资源的构建来说效果很好。

我还有一个额外要求,即在构建过程中设置 Azure AD 组。我有一个可以在本地计算机上正常运行的脚本。当我通过构建部署它并在托管构建 Controller 上执行时,脚本最初找不到 AzureAD 模块。我通过将脚本包含在 git Repo 中并通过以下方式访问它来解决这个问题:

$adModulePath = $PSScriptRoot + "\PsModules\AzureAD\2.0.0.131\AzureAD.psd1"
Import-Module $adModulePath

但是,我现在在运行 New-AzureADGroup 时遇到了另一个问题。该脚本要求在发出命令之前运行 Connect-AzureAD。通过对凭据进行硬编码可以很好地工作,但我不想这样做,我希望它在创建的 SPN 的上下文中运行,该 SPN 在托管构建 Controller 上运行脚本。

因此,问题是,我能否获取 Azure PowerShell 执行 SPN 的当前上下文并将其传递给 Connect-AzureAD 以避免以纯文本形式存储凭据?我错过了一个技巧吗?还有其他选择吗?

我当前的代码如下,注释连接在命令中工作正常,就像硬编码值一样。不带参数的调用会显示登录 UI,该 UI 会终止构建,因为它显然不是交互式的。

## Login to Azure
#$SecurePassword = ConvertTo-SecureString $AdminPassword -AsPlainText -Force
#$AdminCredential = New-Object System.Management.Automation.PSCredential ($AdminUserEmailAddress, $SecurePassword)
#Connect-AzureAD -Credential $AdminCredential

Connect-AzureAD

Write-Output "------------------ Start: Group Creation ------------------"

$TestForAdminGroup = Get-AzureADGroup -SearchString $AdminGroup
$TestForContributorGroup = Get-AzureADGroup -SearchString $ContributorGroup
$TestForReaderGroup = Get-AzureADGroup -SearchString $ReaderGroup

谢谢

最佳答案

这是可能的。今天为我自己工作了VSTS extension我不久前发布的。我的扩展使用 Azure 资源管理器端点 作为输入。

现在使用以下代码在 Microsoft 托管的 Visual Studio 2017 代理池上运行它。更多信息请参阅我的post on how to use AzureAD PowerShell cmdlets on VSTS agent .

Write-Verbose "Import AzureAD module because is not on default VSTS agent"
$azureAdModulePath = $PSScriptRoot + "\AzureAD\2.0.1.16\AzureAD.psd1"
Import-Module $azureAdModulePath

# Workaround to use AzureAD in this task. Get an access token and call Connect-AzureAD
$serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Require
$serviceName = Get-VstsInput -Name $serviceNameInput -Require
$endPointRM = Get-VstsEndpoint -Name $serviceName -Require

$clientId = $endPointRM.Auth.Parameters.ServicePrincipalId
$clientSecret = $endPointRM.Auth.Parameters.ServicePrincipalKey
$tenantId = $endPointRM.Auth.Parameters.TenantId

$adTokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$resource = "https://graph.windows.net/"

$body = @{
grant_type = "client_credentials"
client_id = $clientId
client_secret = $clientSecret
resource = $resource
}

$response = Invoke-RestMethod -Method 'Post' -Uri $adTokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body
$token = $response.access_token

Write-Verbose "Login to AzureAD with same application as endpoint"
Connect-AzureAD -AadAccessToken $token -AccountId $clientId -TenantId $tenantId

关于powershell - VSTS 构建和 PowerShell 以及 AzureAD 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46554136/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com