Search code examples
ansibleopenstackansible-inventory

Ansible print created hosts


I wrote an Ansible Playbook that creates multiple VMs. The Playbook is split in two files. Main.yaml and vars.yaml. Its creating the VMs and it seems to work nicely. Im not getting any errors so i assume it successfully added the created hosts to the Inventory. I want to check if the created hosts were added to the Inventory. How can i print/list the Hosts of the inventory? My goal is to run scripts at a later stage on the created VMs. Thanks.

**Main.yaml**
#########CREATING VM#########
---
- hosts: localhost
  vars:
    http_port: 80
max_clients: 200
  vars_files:
   - vars.yaml
  tasks:
  - name: create VM
    os_server:
      name: "{{ item.name }}"
      state: present
      image: "{{ item.image }}"
      boot_from_volume: True
      security_groups: ssh
      flavor: "{{ item.flavor }}"
      key_name: mykey
      region_name: "{{ lookup('env', 'OS_REGION_NAME') }}"
      nics:
        - net-name: private
      wait: yes
    register: instances
    with_items: "{{ instance_definitions }}"
 ############################################
  - name: whait 15 seconds
    pause: seconds=15
    when: instances.changed
######DEBUG#################################
  - name: display results
    debug:
      msg: "{{ item }}"
    with_items: "{{ instances.results }}"
############################################
  - name: Add new VM to ansible Inventory
    add_host:
      name: "{{ item.server.name}}"
      ansible_host: "{{item.server.public_v4}}"
      ansible_user: "{{ansible_user}}"
      ansible_ssh_common_args: -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
      groups: just_created
    with_items: "{{ instances.results }}"



**vars.yaml**
---
  instance_definitions:
     - { name: Debian Jessie, image: Debian Jessie 8, flavor: c1.small, loginame: debian }
     - { name: Debian Stretch, image: Debian Stretch 9, flavor: c1.small, loginame: debian }

Solution

  • This is what magic variables are for.

    All your hosts will be in a list:

    groups['just_created']