繁体   English   中英

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

[英]Azure DevOps - Custom Task - PowerShell with Azure Authentification

到目前为止,我已经使用Azure PowerShell任务在Azure上下文中执行PowerShell脚本( https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/azure-powershell?view=vsts )。 由于一般化的努力,我现在想创建一个运行PowerShell脚本的自定义任务(请参见例如http://www.donovanbrown.com/post/how-do-i-upload-a-custom-task-for-build )在Azure上下文中,即针对Azure DevOps中的连接终结点进行身份验证。

我该如何实现?

首先,您需要一个服务主体(请参见例如https://docs.microsoft.com/zh-cn/powershell/azure/create-azure-service-principal-azureps?view=azps-1.1.0 )和一个服务连接(请参见例如https://docs.microsoft.com/zh-cn/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)..." 
}

编辑:

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

Clear-AzureRmContext -Scope Process
Disable-AzureRmContextAutosave

在开始和

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

在末尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM