# How to use "add\_host" (or "group\_by" and/or "set\_facts") to dynamically add new hosts to existing/new groups in the playbook inventory (to running play or play's following it in the same run)?

**URL:** <https://forum.ansible.com/t/how-to-use-add-host-or-group-by-and-or-set-facts-to-dynamically-add-new-hosts-to-existing-new-groups-in-the-playbook-inventory-to-running-play-or-plays-following-it-in-the-same-run/23003>\
**Category:** Ansible Project\
**Created:** [November 10, 2016, 3:46pm UTC](https://forum.ansible.com/t/how-to-use-add-host-or-group-by-and-or-set-facts-to-dynamically-add-new-hosts-to-existing-new-groups-in-the-playbook-inventory-to-running-play-or-plays-following-it-in-the-same-run/23003 "2016-11-10T15:46:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![LXC-dev\_Koha-Lappi](https://avatars.discourse-cdn.com/v4/letter/l/edb3f5/32.png) [@LXC-dev\_Koha-Lappi](https://forum.ansible.com/u/LXC-dev_Koha-Lappi)\
**Post date:** [November 10, 2016, 3:46pm UTC](https://forum.ansible.com/t/how-to-use-add-host-or-group-by-and-or-set-facts-to-dynamically-add-new-hosts-to-existing-new-groups-in-the-playbook-inventory-to-running-play-or-plays-following-it-in-the-same-run/23003/1 "2016-11-10T15:46:21Z")

</div>

As suggested by @jimi-c (`https://github.com/jimi-c), `I post here the follow-up discussion of this ticket: [https://github.com/ansible/ansible/issues/6912](https://github.com/ansible/ansible/issues/6912), which concerns the inability and issues to use `add_host` or group\_by/set\_fact to “dynamically add new hosts to playbook inventory and groups for many hosts and not only the first host in the inventory”

I have encountered this problem in my playbook (see the follwing code), where `add_host` does not see the whole inventory when I try to use it to add new hosts to playbook inventory and groups. Someone posted there an idea to use set\_fact and group-by to do this, but I still don’t understand how to achieve the same dynamic behavior where new hosts should be added to groups using `set_facts` and `group-by`… Specifically, I would like toi know which facts should I set to achieve the same as with `add_host`, that in my case is used like this:

---

<div class="post-metadata">

**Author:** ![Brian\_Coca](https://avatars.discourse-cdn.com/v4/letter/b/6de8d8/32.png) [@Brian\_Coca](https://forum.ansible.com/u/Brian_Coca)\
**Post date:** [February 10, 2017, 3:36am UTC](https://forum.ansible.com/t/how-to-use-add-host-or-group-by-and-or-set-facts-to-dynamically-add-new-hosts-to-existing-new-groups-in-the-playbook-inventory-to-running-play-or-plays-following-it-in-the-same-run/23003/2 "2017-02-10T03:36:10Z")

</div>

Loop over the hosts, not the results of the first host:

with\_items: '{{groups['all']}}'

item is now the 'inventory\_hostname' and you can use  
hostvars[item][.... to access the rest of the data
