que*_*tzt 1 authentication powershell azure azure-devops
到目前为止,我使用 Azure PowerShell 任务在 Azure 上下文 ( https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/azure-powershell?view=vsts ) 中执行 PowerShell 脚本。由于泛化工作,我现在想创建一个运行 PowerShell 脚本的自定义任务(参见例如http://www.donovanbrown.com/post/how-do-i-upload-a-custom-task-for-build)在 Azure 上下文中,即针对 Azure DevOps 中的连接端点进行身份验证。
我怎样才能做到这一点?
首先,您需要一个服务主体(参见例如https://docs.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-1.1.0)和一项服务连接(参见例如https://docs.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."
}
]
Run Code Online (Sandbox Code Playgroud)
在任务(powershell 脚本)中,您通过
$serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
$serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
Run Code Online (Sandbox Code Playgroud)
然后进行身份验证:
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)..."
}
Run Code Online (Sandbox Code Playgroud)
编辑:
清除脚本开头和结尾的上下文很有用。你可以通过
Clear-AzureRmContext -Scope Process
Disable-AzureRmContextAutosave
Run Code Online (Sandbox Code Playgroud)
在开始和
Disconnect-AzureRmAccount -Scope Process
Clear-AzureRmContext -Scope Process
Run Code Online (Sandbox Code Playgroud)
在末尾。
| 归档时间: |
|
| 查看次数: |
2951 次 |
| 最近记录: |