Collection-Scripts/create_proxmox_template.sh

98 lines
2.4 KiB
Bash

#!/bin/bash
# Function to handle script termination
function cleanup {
echo "Script aborted."
exit 1
}
# Register the cleanup function to be called on script termination
trap cleanup SIGINT
# Check if a parameter is provided
if [[ -z $1 ]]; then
echo "Usage: ./create_template.sh <qcow2_file>"
exit 1
fi
# Set the qcow2 file parameter
qcow2_file=$1
vmid=9000
# Prompt for VMID
read -p "Enter the VMID(9000 press enter): " vmid
# Check if VMID is already in use
if qm config "$vmid" &> /dev/null; then
read -p "VMID $vmid is already in use. Do you want to set a new VMID (n), delete the current VMID (d), or abort the script (a)? " response
case $response in
n)
read -p "Enter the new VMID: " new_vmid
vmid="$new_vmid"
;;
d)
qm stop "$vmid"
qm destroy "$vmid"
;;
a)
echo "Script aborted."
exit 1
;;
*)
echo "Invalid response. Script aborted."
exit 1
;;
esac
fi
datastore=vm
# Prompt for datastore
read -p "Enter the datastore (vm press enter): " datastore
template_name=debian-12-cloudinit-template
# Prompt for template name
read -p "Enter the template name (debian-12-cloudinit-template press enter): " template_name
# Proxmox
# apt-get install -y cloud-init libguestfs-tools
packages=("cloud-init" "libguestfs-tools")
for package in "${packages[@]}"; do
dpkg -s "$package" >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "$package is not installed. Installing..."
apt-get install -y "$package"
else
echo "$package is already installed."
fi
done
# Install qemu-guest-agent
echo "installing QEMU Guest Agent"
virt-customize --install qemu-guest-agent -a $qcow2_file
# Create VM
echo "Creating VM $vmid..."
qm create "$vmid" --name "$template_name" --memory 2048 --net0 virtio,bridge=vmbr0
# Import disk
echo "Importing disk..."
qm importdisk "$vmid" "$qcow2_file" "$datastore"
# Set SCSI controller
echo "Setting SCSI controller..."
qm set "$vmid" --scsihw virtio-scsi-pci --scsi0 "$datastore:vm-$vmid-disk-0"
# Set cloud-init
echo "Setting cloud-init..."
qm set "$vmid" --ide2 "$datastore:cloudinit"
# Set boot disk
echo "Setting boot disk..."
qm set "$vmid" --boot c --bootdisk scsi0
# Create template
echo "Creating template..."
qm template "$vmid"
echo "Script execution completed successfully."