Created
September 18, 2024 21:39
-
-
Save 4r7if3x/265a96199edcd1ad300af05e3aaaf9ff to your computer and use it in GitHub Desktop.
Create Ubuntu Clone Template VM on Proxmox via Cloud-Init
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# ╔══════════════════════════════════════════════════════════════════════════╗ | |
# ║ Copyright © 2024 The Artifex (4r7if3x). Published under the MIT License. ║ | |
# ╚══════════════════════════════════════════════════════════════════════════╝ | |
# Initializing | |
set -e; echo | |
# Setting variables | |
CLOUD_IMAGE_URL="https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img" | |
CLOUD_IMAGE_FILE=/tmp/$(basename "$CLOUD_IMAGE_URL") | |
VM_ID=1000 | |
STORAGE_ID="local-lvm" | |
BRIDGE_ID=1 | |
USERNAME=ubuntu | |
PASSWORD=$(< /dev/urandom tr -dc 'A-Za-z0-9_@#%^' | head -c 24) | |
SSH_KEYS_FILE=$(mktemp) | |
cat <<-EOF > "$SSH_KEYS_FILE" | |
ssh-ed25519 ... user@example.com | |
EOF | |
# Downloading and converting the image | |
wget -nc -P /tmp "$CLOUD_IMAGE_URL" | |
qemu-img resize "$CLOUD_IMAGE_FILE" 32G | |
# Creating the VM | |
# Using serial interface: --vga serial0 --serial0 socket | |
# Setting VLAN number: --net0 virtio,bridge="vmbr${BRIDGE_ID},tag=1 | |
sudo qm create "$VM_ID" --name "ubuntu-template" --ostype l26 \ | |
--cpu host --socket 1 --cores 1 \ | |
--memory 1024 \ | |
--vga virtio \ | |
--net0 virtio,bridge="vmbr${BRIDGE_ID}" \ | |
--bios ovmf --machine q35 --efidisk0 "${STORAGE_ID}:0,pre-enrolled-keys=0" \ | |
--agent 1 | |
# Configuring hardware | |
sudo qm importdisk "$VM_ID" "$CLOUD_IMAGE_FILE" "$STORAGE_ID" | |
sudo qm set "$VM_ID" --scsihw virtio-scsi-pci --virtio0 "${STORAGE_ID}:vm-${VM_ID}-disk-1,discard=on" # 'discard' should be enabled on SSDs | |
sudo qm set "$VM_ID" --boot order=virtio0 | |
sudo qm set "$VM_ID" --scsi1 "${STORAGE_ID}:cloudinit" | |
# Creating the vendor.yaml file for CloudInit | |
mkdir -p /var/lib/vz/snippets | |
cat <<EOF | sudo tee /var/lib/vz/snippets/vendor.yaml | |
#cloud-config | |
runcmd: | |
- apt update | |
- apt install -y qemu-guest-agent | |
- systemctl enable qemu-guest-agent | |
- timedatectl set-timezone UTC | |
- reboot | |
EOF | |
# Configuring CloudInit | |
sudo qm set "$VM_ID" --cicustom "vendor=local:snippets/vendor.yaml" | |
#sudo qm set "$VM_ID" --tags cloud-init,template,ubuntu-server,24.04-lts | |
sudo qm set "$VM_ID" --ciuser "$USERNAME" | |
sudo qm set "$VM_ID" --cipassword "$PASSWORD" | |
sudo qm set "$VM_ID" --sshkeys "$SSH_KEYS_FILE" | |
sudo qm set "$VM_ID" --ipconfig0 ip=dhcp | |
# Converting to template | |
sudo qm template "$VM_ID" | |
# Finalizing | |
echo -e "\nDone! Password: ${PASSWORD}\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment