如何从 Azure Powershell 中的 VSTS Build 并行运行 Start-AzureVM



我在 VSTS 中的 Azure Powershell 任务中运行了一个 PowerShell 脚本,该脚本在开发测试实验室中启动多个 Azure 虚拟机,但首先启动域控制器,等待它启动,然后依次启动其他虚拟机。

我想并行启动所有其他进程,我尝试使用 Start-Job 执行此操作,但这会产生一个新的 Powershell 进程,该进程没有 Azure 登录的安全上下文,因此失败。我正在尝试这样的事情:

[cmdletbinding()]
param (
    [ValidateSet("Start","Stop")][string]$Action,
    $labName = "DevTestLab",
    $labResourceGroup = "DevTestLabRG"
)
if ($Action -eq "Start") {
    Write-Verbose "Starting the domain controller first"
    Get-AzureRmResource | Where-Object {
        $_.Name -match "dc" -and 
        $_.ResourceType -eq "Microsoft.Compute/virtualMachines" -and
        $_.ResourceGroupName -match $labResourceGroup } | Start-AzureRmVM
    Write-Verbose "Starting other machines in the lab as background jobs"
    foreach ($AzureRMResource in Get-AzureRmResource | 
    Where-Object {
        $_.Name -notmatch "dc" -and 
        $_.ResourceType -eq "Microsoft.Compute/virtualMachines" -and
        $_.ResourceGroupName -match $labResourceGroup } )
        {
            Start-Job { 
                $myResource = $using:AzureRMResource                
                Start-AzureRMVM -Name $myResource.Name -ResourceGroupName $myResource.ResourceGroupName
               }            
        }
    # wait for all machines to start before exiting the session
    Get-Job | Wait-Job
    Get-Job | Remove-Job
}

正在使用托管代理来运行脚本,因此我不能同时运行许多代理,并且据我所知,VSTS 不支持并行任务。

关于如何解决这个问题的任何想法?

除了创建PowerShell脚本,您还可以使用Azure CLI。Azure CLI 有一个采用 ID 列表的vm startvm stop命令。您还可以使用 CLI 查询所需的所有 ID。下面是一个简单的 Bash 代码段,用于启动/停止 id 包含测试的所有 VM。

# example usage
az vm start --ids $(
    az vm list --query "[].id"
        -o tsv | grep "Test"
)
az vm stop --ids $(
    az vm list --query "[].id"
        -o tsv | grep "Test"
)

来源:Azure CLI 2.0:快速启动/停止所有 VM

还可以通过 Azure CLI 任务使用带有--no-wait参数的 az vm start 命令进行尝试。

最新更新