Skip to content

Instantly share code, notes, and snippets.

@vpatel95
Last active November 7, 2024 19:43
Show Gist options
  • Save vpatel95/9aa80decd0b15c015bd273c1e02ff1a6 to your computer and use it in GitHub Desktop.
Save vpatel95/9aa80decd0b15c015bd273c1e02ff1a6 to your computer and use it in GitHub Desktop.
Build custom ubuntu image
#!/bin/bash
SOURCE_IMG=jammy-server-cloudimg-amd64.img
IMG_TEMPLATE_INTR=template-v1-intermediate.qcow2
IMG_TEMPLATE=template-v1.qcow2
IMG_TEMPLATE_VMDK=template-v1.vmdk
TEMPLATE_SZ=20G
DIR=`pwd`
if [[ ! -f ${DIR}/${SOURCE_IMG} ]]
wget https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64.img
fi
sudo rm ${IMG_TEMPLATE} ${IMG_TEMPLATE_VMDK}
sudo qemu-img create -f qcow2 -o preallocation=metadata ${IMG_TEMPLATE_INTR} ${TEMPLATE_SZ}
sudo virt-resize --expand /dev/sda1 ${SOURCE_IMG} ${IMG_TEMPLATE_INTR}
sudo virt-customize -a ${IMG_TEMPLATE_INTR} --run-command 'grub-install /dev/sda'
# Set the root password
sudo virt-customize -a ${IMG_TEMPLATE_INTR} --root-password password:passw0rd
# Enable root login with password
sudo virt-customize -a ${IMG_TEMPLATE_INTR} --run-command 'ssh-keygen -A'
sudo virt-customize -a ${IMG_TEMPLATE_INTR} --run-command 'echo PasswordAuthentication yes >> /etc/ssh/sshd_config'
sudo virt-customize -a ${IMG_TEMPLATE_INTR} --run-command 'echo PermitRootLogin yes >> /etc/ssh/sshd_config'
# Create a setup.sh script that installs packages in your template image
sudo virt-customize -a ${IMG_TEMPLATE_INTR} --run ${DIR}/setup.sh -v
# Copy files in the custom image
# sudo virt-customize -a ${IMG_TEMPLATE_INTR} --copy-in ${DIR}/file.txt:/home
# Uncomment below line to create a VMDK image for VMware
# sudo qemu-img convert -p -f qcow2 -O vmdk -o adapter_type=lsilogic,subformat=streamOptimized,compat6 ${IMG_TEMPLATE_INTR} ${IMG_TEMPLATE_VMDK}
# Compress the template image to reduce size.
sudo qemu-img convert -c -f qcow2 -O qcow2 ${IMG_TEMPLATE_INTR} ${IMG_TEMPLATE}
# Remove the intermediate uncompressed image.
sudo rm ${IMG_TEMPLATE_INTR}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment