【问题标题】:Check if Azure VM name exists before deploying arm template在部署 arm 模板之前检查 Azure VM 名称是否存在
【发布时间】:2019-08-21 20:25:59
【问题描述】:

我正在尝试使用 Azure powershell 获取 VM 名称(例如:demovm01,其中 VM 名称为 demovm,后缀为 01

如果01 已经存在,我想获取输出并自动追加02 的新后缀。

获取虚拟机名称的示例脚本:

$getvm = Get-AzVM -Name "$vmname" -ResourceGroupName "eodemofunction" -ErrorVariable notPresent -ErrorAction SilentlyContinue
if ($notPresent) {
    Write-Output "VM not found. Creating now"
}
else {
    Write-Output "VM exists."
    return $true    
}

我希望能够将这个新的 vm 名称注入到要部署的 arm 部署中

【问题讨论】:

    标签: azure azure-devops azure-powershell


    【解决方案1】:

    应该这样做。将递增直到找不到 VM 并使用简单的 -replace 注入到您的 json 文件中。还将返回 Azure 中已存在的所有 thr VM 值

    $i=1
    $vmname_base = "vmserver"
    $VMexists = @()
    
    do {
        #invert int value to double digit string
        $int = $i.tostring('00')
        $getvm = Get-AzVM -Name "$vmname_base$int" -ResourceGroupName "eodemofunction" -ErrorVariable notPresent -ErrorAction SilentlyContinue
        if ($notPresent) {
            Write-Output "VM not found. Creating now"
            Write-Output "VM created name is $vmname_base$int"
            #Set condition to end do while loop
            VMcreated = "true"
            #commands to inject to json here. I always find replace method the easiest
            $JSON = Get-Content azuredeploy.parameters.json
            $JSON = $JSON -replace ("Servername","$vmname_base$int")
            $JSON | Out-File azuredeploy.parameters.json -Force
        }
        else {
            Write-Output "VMexists."
            # Add existing VM to array
            $VMexists += "$vmname_base$int"
            # Increment version, ie. 01 to 02 to 03 etc
            $i++
        }       
    } while ($VMcreated -ne "true")
    
    return $VMexists
    

    【讨论】:

    • 如果找到 vmserver01 会怎样?我希望它循环到下一个迭代 vmserver02 以查看它是否存在......等等。
    • 我刚刚删除了返回,但这就是 $i++ 增量在 else 块中所做的。
    • 虚拟机存在是否需要返回?如果是这样,你的 else 块可能看起来更像
    【解决方案2】:

    您的命令可能如下所示,$newvmname 就是您想要的。

    $vmname = "demovm01"
    $getvm = Get-AzVM -Name "$vmname" -ResourceGroupName "<group name>" -ErrorVariable notPresent -ErrorAction SilentlyContinue
    
    if ($notPresent) {
        Write-Output "VM not found. Creating now"
    }
    else {
        Write-Output "VM exists."  
    
        if($getvm.Name -like '*01'){
            $newvmname = $vmname.TrimEnd('01')+"02"
        } 
        Write-Output $newvmname
      return $true
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 2019-06-29
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多