---

- hosts: localhost
  gather_facts: no
  tasks:
    - name: add the host to group 'vm_provisioner'
      add_host:
        hostname: "{{ host_ip }}"
        groupname: vm_provisioner

- hosts: vm_provisioner
  gather_facts: no
  tasks:
    - name: print playbook_dir path
      debug:
        msg: "{{ playbook_dir }}"

    - name: copy create kvm script
      copy:
        src: "{{ playbook_dir }}/kvm_create.sh"
        dest: "/root/kvm_create.sh"
        mode: 0700

    - name: start to create kvm
      command: /root/kvm_create.sh "{{ item|trim }}"
      with_items: "{{ instance_names.split(',') }}"

    - name: get kvm ip address
      kvm_ipaddress_facts:
        vm_names: "{{ instance_names }}"
      register: raw_vm_ip_list

    - name: raw kvm ip list info
      debug:
        msg: "{{ raw_vm_ip_list }}"

    - set_fact:
        vm_ip_list: "{{ raw_vm_ip_list.result }}"

    - name: Add instances to host group
      add_host:
        hostname: "{{ item.ip }}"
        groupname: "waitfor_hosts"
      with_items: "{{ vm_ip_list }}"

    - name: Template the inventory
      template:
        src: ../templates/inventory-kvm.j2
        dest: "{{ inventory_path }}"
      delegate_to: localhost

- name: Wait for instances
  hosts: waitfor_hosts
  gather_facts: false
  tasks:
    - name: Wait for SSH to come up.
      connection: local
      wait_for:
        host: "{{inventory_hostname}}"
        port: 22
        delay: 60
        timeout: 240
        state: started
