开发测试实验室虚拟机自动启动

DevTest Labs Virtual Machine Auto-start

有没有办法在开发测试实验室虚拟机上启用自动启动功能作为创建的一部分,即是否可以将其添加到 VM 的 ARM 模板中?

我目前通过 Azure 门户手动启用此功能,但我发现当从 Team Services 进行后续部署时它会被禁用。

解决方案

受下面 Ashok 接受的答案的启发,我设法将 PowerShell 脚本调整并简化为以下内容...

Param([string] $resourceId)

$tags = (Get-AzureRmResource -ResourceId $resourceId).Tags

if (-Not ($tags) -Or -Not($tags.ContainsKey('AutoStartOn'))) {
  $tags += @{ AutoStartOn=$true; }
}

if (-Not ($tags) -Or -Not($tags.ContainsKey('AlwaysOn'))) {
  $tags += @{ AlwaysOn=$true; }
}

Set-AzureRmResource -ResourceId $resourceId -Tag $tags -Force

自动启动策略要求您明确 select VM 并在启用该策略后从其上下文菜单应用该策略。这样您就不会轻易 运行 遇到不需要的 VM 意外自动启动并导致意外支出的情况。

详情请参考以下文章:

https://azure.microsoft.com/en-us/updates/azure-devtest-labs-schedule-vm-auto-start/

更新:

您可以试试下面的PS功能。请注意,标签集合必须全部替换。这就是为什么您会看到确保仅附加到集合或更改现有值(如果已经存在)的逻辑。否则,您将删除其他标签。

    function Enable-AzureDtlVmAutoStart
{
    [CmdletBinding()]
    param(
        [string] $ResourceId,
        [switch] $AlwaysOn
    )

    $autoStartOnTagName = 'AutoStartOn'
    $alwaysOnTagName = 'AlwaysOn'

    $labVm = Get-AzureRmResource -ResourceId $ResourceId
    $tags = $labVm.Tags

    # Undefined tags collection can happen if the Lab VM never had any tags set.
    if (-not $tags)
    {
        $tags = @(@{},@{})
    }

    # Update the tags if they already exist in the collection.
    $tags | % {
        if ($_.Name -eq $autoStartOnTagName)
        {
            $_.Value = $true
        }
        if ($_.Name -eq $alwaysOnTagName)
        {
            $_.Value = $true
        }
    }
    # Otherwise, create new tags.
    if (-not ($tags | ? { $_.Name -eq $autoStartOnTagName }))
    {
        $tags += @{Name=$autoStartOnTagName;Value=$true}
    }
    if (-not ($tags | ? { $_.Name -eq $alwaysOn }))
    {
        $tags += @{Name=$alwaysOnTagName;Value=$AlwaysOn}
    }

    Set-AzureRmResource -ResourceId $ResourceId -Tag $tags -Force
}