如何在 Ansible 的剧本期间访问动态清单中的主机变量?
How to access host variable in a dynamic inventory during a playbook in Ansible?
我想写一个简单的 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 将连接到 backbone1_linux 并 ping 到组服务器的所有剩余成员
谁能帮我解决这个问题?
调试任务应显示 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
我想写一个简单的 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 将连接到 backbone1_linux 并 ping 到组服务器的所有剩余成员
谁能帮我解决这个问题?
调试任务应显示 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