微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Azure自动化运行本工作流失去了AzContext

如何解决Azure自动化运行本工作流失去了AzContext

我已经编写了以下Runbook工作流程,但有时会在尝试启动或停止VM时看到错误

Start-AzVM:您的Azure凭据尚未设置或已过期,请运行Connect-AzAccount来设置您的Azure凭据 Azure凭据。 在StartStopVmByTag:46 char:46 + + CategoryInfo:CloseError :( :) [Start-AzVM],ArgumentException + FullyQualifiedErrorId:Microsoft.Azure.Commands.Compute.StartAzureVMCommand

我曾尝试传入$ azContext变量,但仍然遇到此问题,如何进一步调查?

workflow StartStopVmByTag {
    $connectionName = "AzRunAsConnection2042";

    try {
        # Get the connection "AzureRunAsConnection "
        $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName

        Write-Output "Logging in to Azure..."
        $null = Add-AzAccount `
            -ServicePrincipal `
            -TenantId $servicePrincipalConnection.TenantId `
            -ApplicationId $servicePrincipalConnection.ApplicationId `
            -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
    }
    catch {

        if (!$servicePrincipalConnection) {
            $ErrorMessage = "Connection $connectionName not found."
            throw $ErrorMessage
        }
        else {
            Write-Error -Message $_.Exception
            throw $_.Exception
        }
    }

    [DateTime]$Now = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date),'GMT Standard Time')
    $startTag = 'Start Schedule'

    Write-Output "*** $Now - Runbook Started  ***"

    # Get Subscriptions
    $Subscriptions = Get-AzSubscription

    ForEach ($Subscription in $Subscriptions) {
        $azContext = Set-AzContext -SubscriptionId $Subscription.Id

        # Get all VM's with a Start or Stop Schedule
        Write-Output "$($Subscription.Name): Getting VM's..."
        [Array]$taggedVms = Get-AzResource -TagName $startTag -ResourceType 'Microsoft.Compute/virtualMachines'
        $taggedVms = $taggedVms | sort-object -Property Name -Unique

        # For each VM,check if start schedule is valid for Now
        Foreach -Parallel ($taggedVm in $taggedVms) {
            Write-Output "$($Subscription.Name): Found Tagged VM: $($taggedVm.Name),$($startTag): $($taggedVm.Tags.$startTag -replace '\s','')"
            $WORKFLOW:null = Start-AzVM -ResourceGroupName $taggedVm.ResourceGroupName -Name $taggedVm.Name -DefaultProfile $azContext -Nowait
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。