如何在Ansible中的剧本期间访问动态清单中的主机变量?

时间:2020-09-02 22:28:19

标签: ansible ansible-inventory

我想写一个简单的Ping剧本,它从HOST_VARS中的所有YAML文件中获取IP地址,并连接到Linux设备并ping所有收集的IP 例: HOST_VARS: -server1.yml(包含IP = 1.1.1.1) -server2.yml(包含IP = 2.2.2)。 该剧本将连接到所有linux设备,并使用提取的IP来测试与这些设备的连接(在此示例中为1.1.1.1和2.2.2.2)

这可能是解决方案,但缺少一些东西:

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

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

这是我的清单:

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

示例:

Playbook将连接到ribs1_linux并ping通组服务器的所有其余成员

有人可以帮助我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

调试任务应显示IP地址

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

和以下命令任务应该ping IP地址

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