且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Azure DevOps-自定义任务-具有Azure身份验证的PowerShell

更新时间:2023-09-17 19:17:34

首先,您需要服务主体(请参见例如 https://docs.microsoft.com/zh-cn/azure/devops/pipelines/library/connect-to-azure?view=vsts ).

First of all you need a service principal (see e.g. https://docs.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-1.1.0) and a service connection (see e.g. https://docs.microsoft.com/en-us/azure/devops/pipelines/library/connect-to-azure?view=vsts).

task.json中的自定义任务中,添加输入以能够选择服务连接:

In the custom task in task.json add an input to be able to select the service connection:

"inputs": [
        {
            "name": "ConnectedServiceName",
            "type": "connectedService:AzureRM",
            "label": "Azure RM Subscription",
            "defaultValue": "",
            "required": true,
            "helpMarkDown": "Select the Azure Resource Manager subscription for the deployment."
        }
]

在任务(powershell脚本)中,您通过以下方式获取输入

In the task (the powershell script) you get this input via

$serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
$serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)

然后进行身份验证:

try {
    $endpoint = Get-VstsEndpoint -Name $serviceName -Require
    if (!$endpoint) {
        throw "Endpoint not found..."
    }
    $subscriptionId = $endpoint.Data.SubscriptionId
    $tenantId = $endpoint.Auth.Parameters.TenantId
    $servicePrincipalId = $endpoint.Auth.Parameters.servicePrincipalId
    $servicePrincipalKey = $endpoint.Auth.Parameters.servicePrincipalKey

    $spnKey = ConvertTo-SecureString $servicePrincipalKey -AsPlainText -Force
    $credentials = New-Object System.Management.Automation.PSCredential($servicePrincipalId,$spnKey)

    Add-AzureRmAccount -ServicePrincipal -TenantId $tenantId -Credential $credentials
    Select-AzureRmSubscription -SubscriptionId $subscriptionId -Tenant $tenantId

    $ctx = Get-AzureRmContext
    Write-Host "Connected to subscription '$($ctx.Subscription)' and tenant '$($ctx.Tenant)'..."
} catch {
    Write-Host "Authentication failed: $($_.Exception.Message)..." 
}

清除脚本开头和结尾处的上下文很有用.您可以通过

It is useful to clear the context at the beginning respectively the end of the script. You can do that via

Clear-AzureRmContext -Scope Process
Disable-AzureRmContextAutosave

开头和

Disconnect-AzureRmAccount -Scope Process
Clear-AzureRmContext -Scope Process

最后.