Skip to content

Instantly share code, notes, and snippets.

@quonic
Created March 16, 2022 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quonic/67cd16b2872aaf02f3494f658f2df9b8 to your computer and use it in GitHub Desktop.
Save quonic/67cd16b2872aaf02f3494f658f2df9b8 to your computer and use it in GitHub Desktop.
PowerShell script that creates a Ubuntu VM template.
#!/bin/bash
wget https://packages.microsoft.com/config/debian/11/packages-microsoft-prod.deb
dpkg -i packages-microsoft-prod.deb
apt-get update -y
apt-get install -y powershell
# pwsh -c ". ./New-QemuTemplate.ps1"
#!/usr/bin/pwsh
[CmdletBinding()]
param (
[Parameter()]
[string]
$ReleaseName = "focal",
[Parameter()]
[string]
$Architecture = "amd64",
[Parameter()]
[string]
$IsoFolder = "/var/lib/vz/template/iso",
[Parameter()]
[string]
$TemplateName = "ubuntu-2004-cloudinit-template",
[Parameter()]
[int]
$Memory = 4096,
[Parameter()]
[int]
$Cores = 2,
[Parameter()]
[string]
$NetworkDriver = "virtio",
[Parameter()]
[string]
$NetworkBridge = "vmbr1",
[Parameter()]
[string]
$StorageName = "local-zfs",
[Parameter()]
[string[]]
$Packages = "qemu-guest-agent"
)
$Arch = $Architecture
$ImageFileName = "$ReleaseName-server-cloudimg-$Arch.img"
$Template = [PSCustomObject]@{
Name = $TemplateName
Memory = $Memory
Cores = $Cores
Net = [PSCustomObject]@{
Driver = $NetworkDriver
Bridge = $NetworkBridge
}
}
$Packages = $Packages -join ','
$LastVMId = Get-ChildItem -Path "/etc/pve/nodes/pve/qemu-server/" |
Select-Object -Property Name |
ForEach-Object { $_.Name -replace '.conf' } |
Select-Object -Last 1
$VmId = ($LastVMId -as [int]) + 1
$QmPath = (Get-Command -Name "qm").Source
$VirtCustomizePath = (Get-Command -Name "virt-customize").Source
$AptGet = (Get-Command -Name "apt-get").Source
# download the cloud image
$Splat = @{
Uri = "https://cloud-images.ubuntu.com/$ReleaseName/current/$ImageFileName"
OutFile = "$IsoFolder/$ImageFileName"
}
Invoke-WebRequest @Splat
. $AptGet -y install libguestfs-tools
. $VirtCustomizePath -a $ImageFileName --install $Packages
. $QmPath create $VmId --name $Template.Name --memory $Template.Memory --cores $Template.Cores --net0 $Template.Net.Driver, bridge=$Template.Net.Bridge
. $QmPath importdisk $VmId $ImageFileName $StorageName
. $QmPath set $VmId --scsihw virtio-scsi-pci --scsi0 $($StorageName):vm-$VmId-disk-0
. $QmPath set $VmId --ide2 $($StorageName):cloudinit
. $QmPath set $VmId --boot c --bootdisk scsi0
. $QmPath set $VmId --serial0 socket --vga serial0
# Setting agent to 1 might error out
. $QmPath set $VmId --agent enabled=1, type=virtio
"If no errors, run the following to convert the VM to a template:"
"qm template $VmId"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment