gpt4 book ai didi

Ansible:如何继承变量?

转载 作者:行者123 更新时间:2023-12-04 21:12:26 32 4
gpt4 key购买 nike

我想在 Ansible 中实现变量继承。可以说我有:

group_vars/all

---
ifaces:
- name: eth0
adress: 10.107.13.236
netmask: 255.255.255.192
routes:
- {from: 10.108.100.34/31, via: 10.107.13.193}
- {from: 10.108.105.128/31, via: 10.107.13.193}
- name: eth1
adress: 10.112.13.236
netmask: 255.255.255.192
gateway: 10.112.13.193
routes:
- {from: 10.2.1.0/26, via: 10.112.13.254}

现在我想扩展eth0的路由,像这样:

group_vars/webserver
--- ifaces:
- name: eth0
routes:
- {from: 1.2.3.34, via: 5.6.7.8}
- {from: 9.9.9.9/9, via: 5.6.7.8}

我想要的结果是:
---
ifaces:
- name: eth0
adress: 10.107.13.236
netmask: 255.255.255.192
routes:
- {from: 10.108.100.34/31, via: 10.107.13.193}
- {from: 10.108.105.128/31, via: 10.107.13.193}
- {from: 1.2.3.34, via: 5.6.7.8}
- {from: 9.9.9.9/9, via: 5.6.7.8}
- name: eth1
adress: 10.112.13.236
netmask: 255.255.255.192
gateway: 10.112.13.193
routes:
- {from: 10.2.1.0/26, via: 10.112.13.254}

所以路由应该被扩展而不是被覆盖。我知道设置 hash_behaviour: mergeansible.cfg但这并不能满足我的需求,因为我想 附加 存储在路由中的列表的值。

背景是,我需要能够定义一些标准路线(注意:这不仅限于路线,这只是一个示例)并针对特定组增强这些标准而不是覆盖它们。

这在 Ansible 中可行吗?

最佳答案

我建议创建 lookup_plugin这将完成合并/附加变量的所有繁重工作。

例如:

lookup_plugins/myvars.py

import yaml
class LookupModule(object):
def __init__(self, basedir=None, **kwargs):
self.basedir = basedir
self.plugin_name = 'myvars'
def run(self, vars_file, variable=None, **kwargs):
all_routes = yaml.load(file('group_vars/all'))['ifaces'][0]['routes']
all_routes.extend(
yaml.load(file('group_vars/%s' % vars_file[0]))['ifaces'][0]['routes'])
return [all_routes]

剧本.yml
---
- hosts: webservers
gather_facts: no
connection: local
tasks:
- debug: msg=" Hey {{ item }}"
with_myvars:
- webservers

当然,它并不能完全解决您的问题,您仍然需要对其进行调整以使其正常工作。但是你应该从这个例子中了解如何实现这一点。

其输出应如下所示:
PLAY [webservers] ************************************************************* 

TASK: [debug msg=" Hey {{ item }}"] *******************************************
ok: [localhost] => (item=[{'via': '10.107.13.193', 'from': '10.108.100.34/31'}, {'via': '10.107.13.193', 'from': '10.108.105.128/31'}, {'via': '5.6.7.8', 'from': '1.2.3.34'}, {'via': '5.6.7.8', 'from': '9.9.9.9/9'}]) => {
"item": [
{
"from": "10.108.100.34/31",
"via": "10.107.13.193"
},
{
"from": "10.108.105.128/31",
"via": "10.107.13.193"
},
{
"from": "1.2.3.34",
"via": "5.6.7.8"
},
{
"from": "9.9.9.9/9",
"via": "5.6.7.8"
}
],
"msg": " Hey [{'via': '10.107.13.193', 'from': '10.108.100.34/31'}, {'via': '10.107.13.193', 'from': '10.108.105.128/31'}, {'via': '5.6.7.8', 'from': '1.2.3.34'}, {'via': '5.6.7.8', 'from': '9.9.9.9/9'}]"
}

PLAY RECAP ********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0

所以你可以看到它返回了一个路由列表,所以你可以轻松地放置 {{ item }}在您需要的任何地方。

关于Ansible:如何继承变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31739517/

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