Ansible根据定义的变量从另一个组获取主机IP
Ansible fetch host IP from another group based on defined variable
我想根据变量名从 inventory
文件中的另一个组获取主机的 IP。
库存文件示例:
[master]
master-0.example.io
master-1.example.io
master-2.example.io
[replica]
replica-0.example.io master_host=master-0.example.io
replica-1.example.io master_host=master-1.example.io
replica-2.example.io master_host=master-2.example.io
稍后在 playbook 中我想 运行 一个命令,但是对于那个命令我需要 master 的 IP(FQDN 不起作用)。我试过以下,但这不起作用:
- name: Test run
shell: "echo {{ ansible_default_ipv4.address }}:{{ port }} {{ hostvars['master_host']['ansible_default_ipv4', 'address'] }}:{{ port }}"
知道是否有办法解决这个问题吗?或者如果有任何其他方法可以做到这一点 - 基本上我需要的是将 master-0
与 replica-0
等匹配,我不想将 IP 放入 inventory
文件中。
hostvars
是一个散列。哈希中的每个顶部条目都是清单中主机的名称。为了解决该散列,您使用的是 'master_host'
不存在的字符串。您想要的是为正在执行命令的特定主机使用变量 master_host
的值。
2 个可能的正确语法是:
{{ hostvars[master_host].ansbible_default_ipv4.address }}
{{ hostvars[master_host]['ansbible_default_ipv4']['address'] }}
...或点或括号语法之间的任何混合。
我想根据变量名从 inventory
文件中的另一个组获取主机的 IP。
库存文件示例:
[master]
master-0.example.io
master-1.example.io
master-2.example.io
[replica]
replica-0.example.io master_host=master-0.example.io
replica-1.example.io master_host=master-1.example.io
replica-2.example.io master_host=master-2.example.io
稍后在 playbook 中我想 运行 一个命令,但是对于那个命令我需要 master 的 IP(FQDN 不起作用)。我试过以下,但这不起作用:
- name: Test run
shell: "echo {{ ansible_default_ipv4.address }}:{{ port }} {{ hostvars['master_host']['ansible_default_ipv4', 'address'] }}:{{ port }}"
知道是否有办法解决这个问题吗?或者如果有任何其他方法可以做到这一点 - 基本上我需要的是将 master-0
与 replica-0
等匹配,我不想将 IP 放入 inventory
文件中。
hostvars
是一个散列。哈希中的每个顶部条目都是清单中主机的名称。为了解决该散列,您使用的是 'master_host'
不存在的字符串。您想要的是为正在执行命令的特定主机使用变量 master_host
的值。
2 个可能的正确语法是:
{{ hostvars[master_host].ansbible_default_ipv4.address }}
{{ hostvars[master_host]['ansbible_default_ipv4']['address'] }}
...或点或括号语法之间的任何混合。