Skip to content

Instantly share code, notes, and snippets.

@dmuth
Created January 16, 2022 00:36
Show Gist options
  • Save dmuth/1862e513b21e61122e5c6e30b32b721a to your computer and use it in GitHub Desktop.
Save dmuth/1862e513b21e61122e5c6e30b32b721a to your computer and use it in GitHub Desktop.
How to create multiple Multipass Ubuntu instances with name resolution between them using a custom /etc/hosts file
#!/bin/bash
#
# This script should run in a multipass VM.
# Take the hosts file that was written at creation and append it to /etc/hosts.
# This way, the hosts that we created can talk to each other by hostname.
#
# Errors are fatal
set -e
pushd $(dirname $0) > /dev/null
echo "# Adding to /etc/hosts..."
#
# Doing this with a here document because sudo won't otherwise work with redirection...
#
sudo bash << EOF
cat hosts >> /etc/hosts
EOF
#!/bin/bash
#
# Spin up our multipass instances
#
# Errors are fatal
set -e
# How many hosts to create?
NUM=3
# Change to the directory where this script lives
pushd $(dirname $0) > /dev/null
#
# Parse our command line arguments
#
function parse_args() {
while test "$1"
do
if test "$1" == "-h" -o "$1" == "--help"
then
echo "! Syntax: $0 [ num_hosts ]"
exit 1
else
NUM=$1
fi
shift
done
} # End of parse_args()
#
# Delete a host
#
function delete_host() {
local HOST=$1
echo "# Deleting host ${HOST}..."
multipass delete ${HOST} || true
} # End of delete_host()
#
# Create a host
#
function create_host() {
local HOST=$1
echo "# Creating host ${HOST}..."
multipass launch -c 2 -n ${HOST} --cloud-init ./cloud-config.yml
multipass mount . ${HOST}:/mnt
} # End of create_host()
#
# Create our hosts
#
function create_hosts() {
for I in $(seq -f %02g ${NUM})
do
delete_host k8s-${I}
done
multipass purge
for I in $(seq -f %02g ${NUM})
do
create_host k8s-${I}
done
} # End of create_hosts()
#
# Create our hosts file to glue on to /etc/hosts
#
function create_hosts_file() {
multipass list --format csv | awk '{FS=","; print $3 "\t" $1}' > hosts
for I in $(seq -f %02g ${NUM})
do
local HOST="k8s-${I}"
multipass exec ${HOST} /mnt/append-to-etc-hosts-in-vm.sh
done
} # End of create_hosts_file()
parse_args $@
echo "# Creating ${NUM} k8s hosts..."
create_hosts
multipass list
create_hosts_file
echo "# Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment