Ansible跨host_vars文件共享网络DNS配置默认值方案咨询
问题:集中管理Linux System Roles网络配置中的DNS参数
我正在使用linux-system-roles.network角色配置多台主机的网络,当前配置可正常运行。我希望将环境专属的DNS配置集中定义在一处,供各host_vars文件引用。尝试过YAML锚点,但锚点无法跨文件使用;还尝试通过变量合并字典的方式实现,但遇到问题,现寻求可行的实现方案。
现有正常配置(host_vars/host-01.example.com.yml)
network_connections: - name: ens18 type: ethernet state: up ip: address: - 10.188.202.32/24 gateway4: 10.188.202.1 dns: - 10.188.202.20 - 10.188.202.21 dns_search: - example.com
期望的集中配置方式
host_vars/all.yml(集中定义DNS配置)
env_ip_settings: dns: - 10.188.202.20 - 10.188.202.21 dns_search: - example.com
期望的host_vars/host-01.example.com.yml(引用集中配置)
network_connections: - name: ens18 type: ethernet state: up ip: address: - 10.188.202.32/24 gateway4: 10.188.202.1 << 引用env_ip_settings
已尝试的失败方案
host_ip_settings: address: - 10.188.202.32/24 gateway4: 10.188.202.1 network_connections: - name: ens18 type: ethernet state: up ip: "{{ env_ip_settings + host_ip_settings }}"
可行解决方案
Ansible中合并字典不能用+运算符(这是列表合并的方式),需要使用combine过滤器来合并两个字典。具体配置如下:
修改后的host_vars/host-01.example.com.yml
host_ip_settings: address: - 10.188.202.32/24 gateway4: 10.188.202.1 network_connections: - name: ens18 type: ethernet state: up ip: "{{ host_ip_settings | combine(env_ip_settings) }}"
如果需要让主机专属配置覆盖集中配置(当存在重复键时),可以调整combine的顺序:
ip: "{{ env_ip_settings | combine(host_ip_settings) }}"
另一种写法(直接在ip节点内合并)
如果不想单独定义host_ip_settings,也可以直接在ip字段内使用combine:
network_connections: - name: ens18 type: ethernet state: up ip: "{{ {'address': ['10.188.202.32/24'], 'gateway4': '10.188.202.1'} | combine(env_ip_settings) }}"
这种方式可以直接把主机专属的IP参数写成字典,再和集中的DNS配置合并,同样能达到集中管理DNS的目的。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

