Can I change the Ansible target in-flight?

0

I run KVM virtual machines on bare metal hosts. To spin up new VMs, I would:

  1. virt-clone a template
  2. virt-sysprep the clone to make some basic changes
  3. Start the cloned VM
  4. Use Ansible for further configuration

Currently, the first 3 steps are done using 1 Ansible script, and the last step is done with another. The first script acts on the bare metal host and the second script acts on the VM.

My question is, can this be performed in 1 script? One possibility is to change the inventory_hostname in-flight in a playbook to target the VM after Step 3. However, I believe this isn't possible.

Is there a better way to do this? Thanks in advance!

Eugene Chow

Posted 2017-08-08T09:34:50.133

Reputation: 111

Answers

0

The solution is simpler than I thought - use delegate_to. In my Ansible role, some of the tasks were directed to the physical host that runs the VM. The rest were targeted at the virtual host.

In this example, a single script creates the VM on bare metal, and then provisions the VM itself. delegate_to executes the virt-clone command on the VM's metal host.

- name: Clone template's KVM definition
  command: virt-clone -o {{ template_name }} -n {{ clone_name }} -f {{ clone_lvm }}
  delegate_to: "{{ metal_host }}"

- name: "Wait for VM to bootup"
  local_action: wait_for host="{{ ansible_host }}" port=22 timeout=60

- name: Gather facts for first time
  setup:

- name: Install packages
  apt:
    name: auditd,ntp,apache2
    state: present

Eugene Chow

Posted 2017-08-08T09:34:50.133

Reputation: 111