首先,您需要一个服务主体(参见例如https://learn.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-1.1.0 https://learn.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-1.1.0)和服务连接(参见例如https://learn.microsoft.com/en-us/azure/devops/pipelines/library/connect-to-azure?view=vsts https://learn.microsoft.com/en-us/azure/devops/pipelines/library/connect-to-azure?view=vsts).
在自定义任务中task.json
添加一个输入以便能够选择服务连接:
"inputs": [
{
"name": "ConnectedServiceName",
"type": "connectedService:AzureRM",
"label": "Azure RM Subscription",
"defaultValue": "",
"required": true,
"helpMarkDown": "Select the Azure Resource Manager subscription for the deployment."
}
]
在任务(powershell 脚本)中,您通过以下方式获取此输入
$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)..."
}
Edit:
清除脚本开头和结尾处的上下文很有用。你可以通过以下方式做到这一点
Clear-AzureRmContext -Scope Process
Disable-AzureRmContextAutosave
在开始时和
Disconnect-AzureRmAccount -Scope Process
Clear-AzureRmContext -Scope Process
在最后。