How to use host inventory file as a variable in playbook?

Lets say I have a playbook with the following code

  • name: Check port
    command: nc -z -v {{asdf_servers}} 8089
    ignore_errors: true

in the group var

asdf_servers: localhost

Is there a way to use the entire host inventory file as a variable in the play book? Or can I enter multiple values for the asdf_servers variable, separated by , or ; ?

Hi Benjamin,

Can you explain what you mean by “use the entire host inventory file as a variable?”

There are things like using the host selector (“hosts: groupname”) and even stuff like:

  • hosts: monitored_servers
    tasks:
  • shell: /usr/bin/foo --server={{ item }}
    delegate_to: “{{ item }}”

with_items: groups.monitoring_servers

That natively use inventory data.

The path to the inventory file is available as a variable, though in general you should not be updating that during an ansible run – if you have that kind of use case, dynamic inventory may be appropriate.

I guess it depends on the usage - so let us know more and we’d be glad to give more details.

Thanks!

–Michael

Hi Michael,

I think that would work for me, using a dynamic inventory.

I basically have my inventory file setup with 2 stanzas that are receivers and senders. I am using Ansible to log into all the senders and do a net cat to verify ACL. In my playbook I do not want to have a command for every single sender host.

Basically have the asdf_servers variable equal to my host inventory [asdf_servers] stanza.

Ok, I’m so this doesn’t seem like a dynamic inventory question to me, but just a good example to use “delegate_to” combined with “with_items”, as you want all servers in one group to talk to the other group.

Dynamic inventory would be orthogonal to that particular question – still useful, but not the same thing.