Skip to content

Instantly share code, notes, and snippets.

@smarteist
Last active November 2, 2023 15:23
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 smarteist/1a7353ec175215755a7853d0c5ac3b51 to your computer and use it in GitHub Desktop.
Save smarteist/1a7353ec175215755a7853d0c5ac3b51 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
cpucores="2"
ram="2G"
disk="30G"
username="vm"
password="111111"
vm_name="VM1"
ver="22.04"
img="ubuntu-${ver}-server-cloudimg-amd64.img"
qcow="ubuntu-${ver}.qcow2"
cloud_init_cfg="cloud-init.yaml"
cloud_init_iso="cloud-init.iso"
port_mapping=(
"2222-:22"
"3333-:3306"
"4443-:443"
"3003-:3003"
"3128-:3128"
"1500-:500"
"4500-:4500"
"1701-:1701"
"1194-:1194"
)
# sudo apt-get install cloud-image-utils qemu libguestfs-tools
if [ ! -f "$img" ] && [ ! -f "$qcow" ]; then
wget "https://cloud-images.ubuntu.com/releases/${ver}/release/${img}"
fi
if [ ! -f "$qcow" ]; then
# This is already in qcow2 format.
# sparse resize: does not use any extra space, just allows the resize to happen later on.
# https://superuser.com/questions/1022019/how-to-increase-size-of-an-ubuntu-cloud-image
qemu-img resize $img $disk
echo "Installing ..."
qemu-img convert -f qcow2 -O qcow2 $img $qcow
# rm $img
fi
if [ ! -f "$cloud_init_iso" ]; then
# For the password.
cat >$cloud_init_cfg <<EOF
#cloud-config
system_info:
default_user:
# name: ${username}
name: root
# home: /home/${username}
home: /root
password: ${password}
chpasswd: { expire: False }
hostname: ${vm_name}
# configure sshd to allow users logging in using password
# rather than just keys
ssh_pwauth: True
ssh_deletekeys: false
disable_root: false
runcmd:
- sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
- service ssh restart
EOF
cloud-localds $cloud_init_iso $cloud_init_cfg
fi
netid="rtl8139,netdev=net0"
netdev="user,id=net0"
for i in "${port_mapping[@]}"; do
netdev="$netdev,hostfwd=tcp::$i"
done
qemu-system-x86_64 \
-drive "file=${qcow},format=qcow2" \
-drive "file=${cloud_init_iso},format=raw" \
-device $netid \
-smp $cpucores \
-m $ram \
-netdev $netdev \
-serial mon:stdio \
-vga virtio \
-enable-kvm \
-nographic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment