Ansible KVM Router Lab Part 2
This is Part 2 of a multi-part series of blog posts for building a router lab automatically using a series of bash scripts and ansible.
Ansible KVM Router Lab Part 1 is an overview.
In this post I begin breaking down the bash scripts which build the router lab, beginning with build_vms.bash.
In Ansible KVM Router Lab Part 5, I explain the ansible playbook tasks used to finish building the lab.
begins by making sure that it is run as the root user. This is because root is required to
ssh into the clones to change their hostnames, machine-ids, and host-ssh-keys. You can call
sudo bash build_vms.bash.
For this same reason,
~/.ssh/known_hosts is useless so it is deleted (and then rebuilt).
build_vms, which loops over the array of MACHINES, which is an
array that holds that names of the lab clients, passing each name in turn
create_vm creates the virtual machine if it does not already exist, using
start_vm to start it.
start_vm is exported from
and per parsing the output of
virsh list --inactive, starts the virtual machine if it is not running.
set_hostnames, which simultaneously calls
set_hostname on the entire MACHINES array.
in turn waits for the virtual machine to be fully booted, then updates the files
/etc/hosts, and then reboots the virtual machine to apply the new hostname.
confirm_hostnames simultaneously calls
confirm_hostname against the entire MACHINES array.
confirm_hostname waits for the virtual machine to be fully booted, then confirms the correct
confirm_hostnames_in_hosts works almost exactly the same as
confirm_hostnames, but this time
/etc/hosts on the virtual machine is grepped for the proper hostname, and corrected
reset_hosts_ssh_keys simultaneously calls
reset_host_ssh_keys against the MACHINES array,
which in turn compares the host_ssh_key of the virtual machine against the bas3 virtual
machine, and if necessary deletes
/etc/ssh/ssh_host_*, generates new host_ssh_keys, restarts
sshd on the virtual machine, removes
~/.ssh/known_hosts, and then reruns itself in
order to confirm the new host_ssh_keys.
reset_machine_ids simultaneously calls
reset_machine_id against the entire MACHINES array,
which in turn checks the machine-id of the virtual machine to make sure that it is different
than the machine-id of the base virtual machine, and if necessary deletes
/var/lib/dbus/machine-id and recreates them.