Search code examples
ansibleansible-inventory

How to access host variable in a dynamic inventory during a playbook in Ansible?


I want to write a simple Ping playbook, which takes IP Addresses from all YAML files in HOST_VARS and connected to Linux devices and ping all the collected IP Example: HOST_VARS: -server1.yml (contains an IP = 1.1.1.1) -server2.yml (contains an IP = 2.2.2). The playbook will connect to all linux devices and use the extracted IP's to test connectivity to those devcies (in this example 1.1.1.1 and 2.2.2.2)

This is what couldbe the solution, but something is missing:

- name: "Ping all Linux VMs"
    hosts: servers
    gather_facts: no

    tasks:  
      - debug:
          msg: "{{ hostvars['{{ item }}'].ansible_host }}"
        with_items: "{{ groups['servers'] }}"
        delegate_to: localhost

This is my Inventory:

[centos@Ansible silverpeak-cisco-poc-automation]$ ansible-inventory --graph
@all:
  |--@servers:
  |  |--backbone1_linux
  |  |--backbone2_linux
  |  |--linux1
  |  |--linux2
  |  |--linux3
  |  |--linux4
  |--@ungrouped:

Example:

Playbook will connect to backbone1_linux and ping to all remaining members of the group servers

Can anybody help me on this question?


Solution

  • The debug task should display the IP addresses

    - hosts: servers
      gather_facts: false
      tasks:
        - debug:
            msg: "{{ hostvars[item]['IP'] }}"
          loop: "{{ groups.servers }}"
          delegate_to: localhost
          run_once: true
    

    and the following command task should ping the IP addresses

        - command: "ping -c 1 {{ hostvars[item]['IP'] }}"
          loop: "{{ groups.servers }}"
          delegate_to: localhost
          run_once: true