CosmoCode (Formerly TeachMeSelenium)

How to dynamically add hosts to group in Ansible

If you work with Ansible, you probably know that we generally provide hosts and groups in a hosts file or inventory. However, at times we might not know all hosts on which we want to run a play. We may decided it at the run time which either comes as an output of another script execution or we want to explicitly specify certain hosts when executing the playbook. This is called in-memory inventory for the playbook.

For these scenarios, we can use ansible.builtin.add_host module.

name: add host to existing group
  add_host:
    name: "{{ external_ip }}"
    groups: my_group

When you run the playbook you can provide the value for the external_ip using --extra-vars or -e option.

ansible-playbook --extra-vars "external_ip=ip"

Exit mobile version