Ansible playbook: load internal inventory file while running

Viewed 5710

I hava an inventory file in INI format:

for example:

[db]
8.8.8.8 ansible_user=root ansible_ssh_private_key_file=/keys/root-id_rsa.pem
....

I'm looking for a way to automatically load my inventory file while running without specify which inventory file path when I triggered my ansible-playbook command

ansible-playbook playbook.yml --inventory-file=hosts (I'm trying to avoid from this) -vv

I'm familiar with the "add_host" module but still I prefer to create an inventory file in INI format and somehow to let the playbook load it automatically. is that possible?

Edit:

Thanks to the users @techraf and @Jeff Hemmen I added more details to question

In addition, I don't want to use either the ansible.cfg file because I want to perform this inside the playbook.yml file itself and not from outside

something like:

- name: add_host {{environment_type}} db servers
  hosts: localhost
  vars_files:
     - vars/main.yml
  roles:
       - { role: my_role}
  inventory_file: (possible?)
     - inventory/hosts.ini (possible?)
3 Answers

I want to perform this inside the playbook.yml file itself and not from outside

You cannot set an inventory file inside the playbook. Playbook is a list of plays and plays must have hosts declaration. There is no way to refer from inside the playbook to the inventory before Ansible tries (and fails to) interpret hosts.

Specify inventory in the ansible.cfg file stored in the same directory as your playbook:

[defaults]
inventory = ./hosts

In your ansible.cfg, in the [defaults] section, there is a directive called inventory. Set that to your inventory file or directory.

Mine reads:

...
[defaults]

# some basic default values...

inventory      = inventory/
...

this is easy, make the playbook call another playbook with shell:

Shell: ansible-playbook -i inventory.ini yourplaybook.yml

delegate_to: localhost

in a nut shell, you could dynamically modify an inventory and prep it for run, then spawn a shell to run ansible again. this way the 2nd spawn of ansible will pick up the modified inventory and do the work. may even be possible to do this with one playbook with some creative uses of extra-vars but easier just to make 2 playbooks..

Related