Учетные данные Azure не были настроены или устарели, запустите Connect-AzAccount - PullRequest
0 голосов
/ 01 марта 2019

Относится к следующему вопросу ( Azure DevOps - пользовательская задача - PowerShell с аутентификацией Azure ). Сейчас я использую Connect-AzAccount для входа в систему с помощью пользовательской задачи Azure DevOps.

ВНа следующем этапе я хочу запустить несколько заданий параллельно, чтобы сначала манипулировать, а затем развертывать определенные ресурсы Azure с помощью шаблонов.При работе с AzureRM это работало без проблем, но после перехода на Az я всегда получаю сообщение об ошибке

Ваши учетные данные Azure не настроены или устарели, запустите Connect-AzAccount, чтобы настроить учетные данные Azure.

Я уже обновил модули Az до последней версии.

Вот как я это делаю:

Аутентификация

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)

    Connect-AzAccount -ServicePrincipal -TenantId $tenantId -Credential $credentials
    Select-AzSubscription -SubscriptionId $subscriptionId -Tenant $tenantId

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

Развертывание параллельно

foreach ($armTemplateFile in $armTemplateFiles) {
    $logic = {
        Param(
            [object] 
            [Parameter(Mandatory=$true)]
            $ctx,

            [object] 
            [Parameter(Mandatory=$true)]
            $armTemplateFile,

            [string] 
            [Parameter(Mandatory=$true)]
            $resourceGroupName
        )

        ####################################################################
        # Functions
        function Format-ValidationOutput {
            param ($ValidationOutput, [int] $Depth = 0)
            Set-StrictMode -Off
            return @($ValidationOutput | Where-Object { $_ -ne $null } | ForEach-Object { @('  ' * $Depth + ': ' + $_.Message) + @(Format-ValidationOutput @($_.Details) ($Depth + 1)) })
        }

        ####################################################################
        # Logic

        # Some template manipulation


        $paramFileContent | ConvertTo-Json -Depth 100 | Set-Content -Path $paramTemplateFile.FullName
        $templateFileContent | ConvertTo-Json -Depth 100 | Set-Content -Path $armTemplateFile.FullName

        ####################################################################
        # Test Deployment
        $ErrorMessages = Format-ValidationOutput (Test-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName `
                                                                                        -TemplateFile $armTemplateFile.FullName `
                                                                                        -TemplateParameterFile $paramTemplateFile.FullName `
                                                                                        -DefaultProfile $ctx)
        if ($ErrorMessages) {
            Write-Host '', 'Validation returned the following errors:', @($ErrorMessages), '', 'Template is invalid.'
        }
        else { # Deploy

            New-AzResourceGroupDeployment -Name (($armTemplateFile.Name).Split(".")[0] + ((Get-Date).ToUniversalTime()).ToString('MMddHHmm')) `
                                                -ResourceGroupName $resourceGroupName `
                                                -TemplateFile $armTemplateFile.FullName `
                                                -TemplateParameterFile $paramTemplateFile.FullName `
                                                -Force `
                                                -ErrorVariable ErrorMessages `
                                                -DefaultProfile $ctx
            if ($ErrorMessages) {
                Write-Host '', 'Template deployment returned the following errors:', @(@($ErrorMessages) | ForEach-Object { $_.Exception.Message.TrimEnd("`r`n") })
            }
        }
    }
    Start-Job $logic -ArgumentList (Get-AzContext), $armTemplateFile, $ResourceGroupName
}

While (Get-Job -State "Running")
{
    Start-Sleep 10
    Write-Host "Jobs still running..."
}

Get-Job | Receive-Job

Ответы [ 2 ]

0 голосов
/ 20 марта 2019

По какой-то причине (я не знаю) передача контекста в фоновое задание больше не работает, так как переход на модули Az (также с самой последней версией (1.4.0)).Я попытался использовать Save-AzContext с Import-AzContext или получить контекст через Get-AzContext и передать его фоновому заданию (с Set-AzContext или напрямую с помощью -DefaultProfile (этот подход работал с модулями AzureRm)).

Обходной путь, который мне подходит сейчас, - это аутентификация каждой фоновой работы индивидуально.

Для определения задания:

foreach ($armTemplateFile in $armTemplateFiles) {
    $logic = {
        Param(
            [object] 
            [Parameter(Mandatory=$true)]
            $endpointInput,

            [object] 
            [Parameter(Mandatory=$true)]
            $armTemplateFile,

            [string] 
            [Parameter(Mandatory=$true)]
            $resourceGroupName
        )

        ###########################
        #Login
        Write-Host "Authenticating..."
        try {
            $endpoint = $endpointInput
            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)

            Connect-AzAccount -ServicePrincipal -TenantId $tenantId -Credential $credentials
            Select-AzSubscription -SubscriptionId $subscriptionId -Tenant $tenantId

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

Для запускаработа:

Start-Job $logic -Name $jobName -ArgumentList $endpoint, $armTemplateFile, $ResourceGroupName
0 голосов
/ 01 марта 2019

Я лично использую эту команду:

Connect-AzureRmAccount

Сначала я регистрируюсь напрямую, используя консоль ISE , затем сеанс сохраняется, и я могу запускать любые сценарии без каких-либо проблем (без использованияэта команда внутри скрипта).

Надеюсь, она вам поможет.

РЕДАКТИРОВАТЬ.

Я вижу, вы также выбираете подписку, это однаЯ использую.

Select-AzureRmSubscription -Subscription 'Subscription ID'
...