我正在使用 Ansible 变量。我有这个
all.yml
---
port: 9001
inventory.yml
---
group1:
hosts:
server1:
ansible_host: www.server1.com
server2:
ansible_host: www.server2.com
vars:
port: 9002
group2:
hosts:
server5:
ansible_host: www.server5.com
group3:
hosts:
server7:
ansible_host: www.server7.com
我构建了一个剧本,my-playbook.yml
- hosts: localhost
gather_facts: no
tasks:
- name: Netcat server 5
shell: nc -zv {{ hostvars[item].ansible_host }} {{ port }}
with_items: "{{ groups['group2'] }}"
- name: Netcat server 1 only
shell: nc -zv {{ hostvars['server1']['ansible_host'] }} {{ hostvars[item].port }}
with_items: "{{ groups['group1'] }}"
当我运行我的 ansible 剧本时:
ansible-playbook -i inventory/inventory.yml playbook.yml
我希望将端口 9001
用于 server5
(位于 all.yml
中)和端口 9002
server1
的 code>(位于 list 中)。
但是,我可以看到它正在抓取两者的端口 9001
。
我做错了什么?
最佳答案
您正在点击 group precedence problem 。从全局来看,Ansible 中的优先级问题可能会变得非常棘手,尤其是当您尝试在不同位置定义变量时。这正是documentation的原因状态:
We suggest that you define each variable in one place: figure out where to define a variable, and keep it simple. For examples, see Tips on where to set variables.
在当前情况下,这是解决问题的一种方法:
- 决定所有服务器都有一个默认端口。使用
default_port: 9001
修改您的 - decide
port
只会出现在特定的组级别(因此永远不要将其放回您的all
文件中),并且仅为覆盖默认端口的组定义。< - 按如下方式修改您的任务:
- name: Netcat server 5 shell: nc -zv {{ hostvars[item].ansible_host }} {{ port | d(default_port) }} with_items: "{{ groups['group2'] }}" - name: Netcat server 1 only shell: nc -zv {{ hostvars['server1']['ansible_host'] }} {{ hostvars[item].port | d(default_port) }} with_items: "{{ groups['group1'] }}"
all
文件
如有必要请注明:d
is an alias to default
关于ansible - 库存优先顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75628469/