newvm: Configure VM for dynamic inventory

This commit adds a new `--group` argument to the `newvm` script, which
adds the host to an Ansible group by listing it in the _libvirt_ domain
metadata.  Multiple groups can be specified by repeating the argument.
Additionally, the VM title is now always set to machine's FQDN, which
is what the dynamic inventory plugin uses to determine the inventory
hostname.

The dynamic inventory plugin parses the _libvirt_ domain metadata and
extracts group membership from the `<dch:groups>` XML element.  Each
`<dch:group>` sub-element specifies a group to which the host belongs.

Unfortunately, `virt-install` does not support modifying the
`<metadata>` element in the _libvirt_ domain XML document, so we have
to resort to using `virsh`.  To ensure the metadata are set before the
guest OS boots and tries to access them, we fork and run `virsh` in
a separate process.
unifi-restore
Dustin 2025-02-07 18:34:26 -06:00
parent 7ff18ab75e
commit 4d30798f54
1 changed files with 18 additions and 1 deletions

View File

@ -1,6 +1,8 @@
#!/bin/sh #!/bin/sh
# vim: set sw=4 ts=4 sts=4 et : # vim: set sw=4 ts=4 sts=4 et :
METADATA_XMLNS='http://du5t1n.me/xmlns/libvirt/metadata/'
memory=2048 memory=2048
vcpus=2 vcpus=2
disk_size=16 disk_size=16
@ -73,6 +75,13 @@ while [ $# -gt 0 ]; do
--domain=*) --domain=*)
dnsdomain=${1#=*} dnsdomain=${1#=*}
;; ;;
--group)
shift
groups_xml="${groups_xml}<group name=\"${1}\"/>"
;;
--group=*)
groups_xml="${groups_xml}<group name=\"${1#*=}\"/>"
;;
--no-console|--noconsole) --no-console|--noconsole)
console=false console=false
;; ;;
@ -139,6 +148,7 @@ extra_args="${extra_args} inst.notmux quiet systemd.show_status=1 console=ttyS0"
set -- \ set -- \
--name ${name} \ --name ${name} \
--metadata title=${hostname} \
--memory ${memory} \ --memory ${memory} \
--cpu host \ --cpu host \
--location ${location} \ --location ${location} \
@ -159,4 +169,11 @@ else
set -- "$@" --noautoconsole --wait -1 set -- "$@" --noautoconsole --wait -1
fi fi
exec virt-install "$@" (
virsh event --event lifecycle --loop | awk '/Started/{exit}'
virsh metadata ${name} --live --config ${METADATA_XMLNS} dch \
"<metadata><groups>${groups_xml}</groups></metadata>"
) &
virt-install "$@"
wait