azure - 部署arm模板前检查Azure VM名称是否存在

标签 azure azure-devops azure-powershell

我尝试使用 Azure powershell 获取虚拟机名称(例如:demovm01,其中虚拟机名称为 demovm,后缀为 01 >.

我想要获取输出并自动附加新后缀 02(如果 01 已存在)。

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

$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    
}

我希望能够将这个新的虚拟机名称注入(inject)到arm部署中进行部署

最佳答案

这应该可以做到。将递增,直到找不到 VM 为止,并使用简单的 -replace 注入(inject)到您的 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

关于azure - 部署arm模板前检查Azure VM名称是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57598771/

相关文章:

visual-studio - 在 Visual Studio 中查看拉取请求的审阅评论

azure - ADF 在 git 模式下发布困惑

Azure管道: file-trigger for files on root level

azure - New-AzServiceBusRule cmdlet 随机失败并出现 "already exists"错误

python - Azure ML Pipeline禁止文件上传

c# - 为 Azure 媒体服务 Assets 创建按需定位器时出现异常

php - 调整目录结构,同时重命名所有文件以表示其原始路径

android - Azure -> Node.js 中的 Easy api -> 如何发送 Android 推送通知?

Azure SQL Server 防火墙规则使用 PowerShell 添加多个 IP 地址以进行数据库连接

azure-devops - Azure DevOps Azure PowerShell 任务输出变量