我建议创建一个包含组的字典并让主机extract 进行配置。例如
shell> cat hosts
[myservers]
test_01
test_02
[groupa]
test_01
[groupb]
test_02
nftablesopen:
myservers:
- dport: "22"
comment: "SSH"
proto: tcp
groupa:
- dport: "123"
comment: "NTP"
proto: "udp"
groupb:
- dport: "80"
comment: "HTTP"
proto: "udp"
- set_fact:
my_open: "{{ group_names|
map('extract',nftablesopen)|
list|flatten }}"
- debug:
var: my_open
给
ok: [test_01] => {
"my_open": [
{
"comment": "NTP",
"dport": "123",
"proto": "udp"
},
{
"comment": "SSH",
"dport": "22",
"proto": "tcp"
}
]
}
ok: [test_02] => {
"my_open": [
{
"comment": "HTTP",
"dport": "80",
"proto": "udp"
},
{
"comment": "SSH",
"dport": "22",
"proto": "tcp"
}
]
}
问:“如果有我没有在 nftabblesopen 中指定的组名怎么办?”
答:intersect 键和组的列表。例如
- set_fact:
my_open: "{{ nftablesopen.keys()|
list|
intersect(group_names)|
map('extract',nftablesopen)|
list|flatten }}"
使用三个主机运行 playbook
shell> cat hosts
[myservers]
test_01
test_02
[groupa]
test_01
[groupb]
test_02
[groupc]
test_03
- hosts: test_01, test_02, test_03
给予
ok: [test_02] => {
"my_open": [
{
"comment": "SSH",
"dport": "22",
"proto": "tcp"
},
{
"comment": "HTTP",
"dport": "80",
"proto": "udp"
}
]
}
ok: [test_01] => {
"my_open": [
{
"comment": "SSH",
"dport": "22",
"proto": "tcp"
},
{
"comment": "NTP",
"dport": "123",
"proto": "udp"
}
]
}
ok: [test_03] => {
"my_open": []
}
问:“(这种方式)我需要通过显式命名来与组相关联,而不是仅仅将变量放入相应的组中。”
A:将项目的常用变量放入目录,例如:全局变量
shell> cat global_vars/nftablesopen.yml
nftablesopen:
myservers:
- dport: "22"
comment: "SSH"
proto: tcp
groupa:
- dport: "123"
comment: "NTP"
proto: "udp"
groupb:
- dport: "80"
comment: "HTTP"
proto: "udp"
将此目录链接到项目的每个 host_vars。例如
shell> tree host_vars/
host_vars/
├── test_01
│ └── global_vars -> ../../global_vars
├── test_02
│ └── global_vars -> ../../global_vars
└── test_03
└── global_vars -> ../../global_vars
更改配置意味着修改目录中的单个文件。