有什么方法可以在库存列表中找到另一个主机,并将其用于剧本中的一些任务作为值?



我正在编写Ansible playbook来添加ufw防火墙规则。现在我进入的问题是假设我有2个节点,需要允许它们之间的访问,所以我试图在另一个主机IP中添加一个主机IP,反之亦然。我如何实现它?

[machines]
IP-ADDR-A
IP-ADDR-B

所以为了更清楚,我想添加B的IP地址,当主机A运行剧本任务时,反之亦然。

- name: Allow to another nginx server
ufw:
rule: allow
proto: tcp
src: XX.XX.XX.A
from_port: 1
to_port: 65535
comment: Another nginx nodes

|extract过滤器的例子几乎显示了您确切的用例

- debug:
msg: >-
{{ groups['machines'] | map('extract', hostvars, 'inventory_hostname') | list }}

,然后您可以按原样使用列表,这将为主机a添加额外的ufw允许规则,或者使用| reject过滤器

将其从列表中排除
- debug:
msg: >-
{{ groups['machines']
| map('extract', hostvars, 'inventory_hostname') 
| reject('eq', inventory_hostname) 
| list
}}