bonafide
bonafide

Reputation: 368

Check if Azure VM name exists before deploying arm template

I am trying to use Azure powershell to get VM name (Eg: demovm01, where the VM name is demovm and the suffix is 01.

I want to get the output and automatically append a new suffix of 02 if 01 already exists.

Sample script to get vm name:

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

I want to be able to inject this new vm name to an arm deploy to deploy

Upvotes: 1

Views: 1588

Answers (2)

Bevan
Bevan

Reputation: 1424

This should do it. Will increment until no VM is found and use a simple -replace to inject to your json file. Will also return all thr VM values that are already present in Azure

$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

Upvotes: 1

Joy Wang
Joy Wang

Reputation: 42143

Your command could be like below, the $newvmname is that you want.

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

Upvotes: 0

Related Questions