To deploy another fresh Centos7 VM all i need to do is to “clone” the template VM, boot it and change its hostname, reboot it again.
Easy task, right ? But how to automate this with Ansible, so all i'll have to do is fire up just one command line and be flexible with the guests VM name and hostnames?
--- - hosts: localhost connection: local gather_facts: no tasks: - name: clone template vm command: VBoxManage clonevm centos7-template --mode all --name {{ newVmName }} --register - name: temp.start clone vm command: VBoxManage startvm {{ newVmName }} --type headless - name: add temp host to inventory (ram) add_host: hostname: "{{ newVmName }}.lan" - name: flush local dns cache command: systemd-resolve --flush-caches - name: wait for new vm to register/update dns hostname and come available shell: /ssd/VirtualBox\ VMs/wait-for-hostname-resolvable.sh centos7-template.lan 60 - name: wait for ssh@vm to be accessable wait_for: timeout: 90 sleep: 2 host: "centos7-template.lan" port: 22 - hosts: centos7-template.lan gather_facts: no remote_user: root tasks: - name: check connection again wait_for_connection: timeout: 60 - name: change vms hostname command: hostnamectl set-hostname "{{ newVmName }}.lan" - name: reboot vm reboot: - hosts: localhost gather_facts: no connection: local tasks: - name: flush local dns cache command: systemd-resolve --flush-caches - name: wait for new vm to register/update dns hostname and come available shell: /ssd/VirtualBox\ VMs/wait-for-hostname-resolvable.sh "{{ newVmName }}.lan" 60 - name: wait for ssh@vm to be accessable wait_for: timeout: 90 sleep: 2 host: "{{ newVmName }}.lan" port: 22 - hosts: "{{ newVmName }}.lan" gather_facts: no remote_user: root tasks: - name: show fqdn of new vm command: hostname -f
#!/bin/bash targetHostname="$1" timeOut="$2" if test -z "$targetHostname" ; then echo "ERROR: No hostname given." echo "Usage: $0 fqdn timeOutSeconds" exit -1 fi if test -z "$timeOut" ; then timeOut=60 fi for seconds in $(seq $timeOut -1 1) ; do systemd-resolve --flush-caches if host "$targetHostname" 1>/dev/null 2>&1 ; then if ping -c1 -w1 "$targetHostname" 1>/dev/null 2>&1 ; then break else #echo "${seconds}s left" continue fi else #echo "${seconds}s left" sleep 1 fi done if test $seconds -gt 1 ; then true else false fi
[templatevms] centos7-template.lan #[admin] #centos7admin.lan #[cluster] #centos7node1.lan #centos7node2.lan #centos7node3.lan
ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -v -i ansibleHosts -e newVmName=newVMsHostname deploy-centos7-from-template-on-virtualbox.yml