gpt4 book ai didi

Ansible:合并多次使用的项目变量

转载 作者:行者123 更新时间:2023-12-04 10:01:34 25 4
gpt4 key购买 nike

我为 ansible 编写了一个 nftables 角色,为我的服务器打开端口。我想要某种等级制度。我想定义应该在每个主机上打开的规则,但有些规则只能应用于一组主机。

存货

---
myservers:
hosts:
server1:
server2:
server3:
server4:
groupa:
hosts:
server1:
server2:
groupb:
hosts:
server3:
server4:

这些是我的 group_vars:
我的服务器.yml
---
nftablesopen:
- dport: "22"
comment: "SSH"
proto: tcp

groupa.yml
---
nftablesopen:
- dport: "123"
comment: "NTP"
proto: "udp"

groupb.yml
---
nftablesopen:
- dport: "80"
comment: "HTTP"
proto: "udp"

当我运行剧本时,可变的优先级开始起作用,并且只应用了我定义的一部分。
Ansible 中处理此问题的最佳方法是什么?
我不想将大量不同的变量合并为一个变量,因为例如,当我添加一组新主机时,我不想更新我的任务。我不能将项目附加到已经存在的项目列表中,就像用不同的编程语言完成一样吗?

最佳答案

我建议用组创建一个字典,让主机 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"
}
]
}

Q: "What if there are group names that I don't specify in the 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": []
}

Q: "(This way) I need to relate to the group by explicitly naming them instead of just putting the variable into the corresponding group."


A:把一个项目的常用变量放到一个目录下,例如global_vars
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
更改配置意味着修改目录中的单个文件。

关于Ansible:合并多次使用的项目变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61801661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com