Last Updated: February 25, 2016
·
6.117K
· skvidal

create a dynamic group from hosts or ips

If you get back a set of hostnames or ip addresses from another action and you want to use that as a group to operate on for a new play you can use the http://ansible.cc/docs/modules.html#add-host action.
It creates a temporary, in-memory group of hosts that only persists until the end of the playbook.

An example:

Get back the list of guests from a libvirt host, put them in a group named myvms_new and halt all of the guests directly, not using the virt interface. (we do this b/c sometimes some guests do not respond to the shutdown command from the virt host)

- name: find instances
  hosts: $vhost
  user: root   

  tasks:
  - name: get list of guests
    action: virt command=list_vms
    register: vmlist

  - name: add them to myvms_new group
    local_action: add_host hostname=$item groupname=myvms_new
    with_items: ${vmlist.list_vms}

- name: halt instances
  hosts: myvms_new
  user: root

 tasks:
  - name: echo-y
    action: command /sbin/halt -p
    ignore_errors: true

You can also use add_host with the ec2 module to have a list of ips to act on from just-created instances.