如何基于网络(子网)成员资格在Ansible中创建条件副本 [英] How to create conditional copy in Ansible based on network (subnet) membership
本文介绍了如何基于网络(子网)成员资格在Ansible中创建条件副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果文件的一个版本在特定子网中具有接口,我想将文件的一个版本复制到服务器,或者如果该子网中没有接口,则要将文件的另一个版本复制到服务器.下面是一个可行的方法,但我认为不是最佳解决方案.我希望有一种更好的方法可以满足以下条件...
I want to copy one version of a file to a server if it has an interface in a specific subnet, or a different version if it does not have an interface in that subnet. Below is a working, but I think less than optimal solution. I'm hoping there is a better way that meets the following criteria...
- 保持动态(使用事实,我不想为每个服务器手动设置变量,而不必为子网中或不在子网中的服务器手动创建组)
- 重复性较低(可以在一项任务中处理吗?)
- 不必列出所有可能的接口名称(例如eth0,eth1,...,bond0,bond1等)
工作版本...
- name: copy file version 1 to server
copy:
src: files/myfile.vs1
dest: /etc/myfile
when: (ansible_eth0.network == "192.168.0.0") or
(ansible_eth1.network == "192.168.0.0") or
(ansible_eth2.network == "192.168.0.0")
...
- name: copy file version 2 to server
copy:
src: files/myfile.vs2
dest: /etc/myfile
when: (ansible_eth0.network != "192.168.0.0") and
(ansible_eth1.network != "192.168.0.0") and
(ansible_eth2.network != "192.168.0.0")
...
推荐答案
一些jinja2忍者技巧,您在这里:
Some jinja2 ninja tricks and here you are:
- copy:
src: >-
{{ (
ansible_interfaces |
map('regex_replace','^','ansible_') |
map('extract',hostvars[inventory_hostname]) |
selectattr('ipv4','defined') |
selectattr('ipv4.network','equalto','192.168.0.0') |
list |
count > 0
) | ternary('files/myfile.vs1','files/myfile.vs2')
}}
dest: /etc/myfile
说明:
- 获取
ansible_interfaces
中可用接口的列表
- 在所有接口的名称前添加
ansible_
成为(ansible_eth0
等) - 从主机自己的
hostvars
中提取所有接口的事实
- 仅选择定义了
ipv4
的那些接口 - 仅选择
ipv4.network
等于192.168.0.0
的那些接口
- 转换为列表
- 计数
- 如果存在一个或多个此类接口,则返回
files/myfile.vs1
- 返回
files/myfile.vs2
否则
- take a list of available interfaces from
ansible_interfaces
- prepend all interfaces' names with
ansible_
to become (ansible_eth0
, etc) - extract all interfaces' facts from host own
hostvars
- select only those interfaces where
ipv4
is defined - select only those interfaces where
ipv4.network
equals to192.168.0.0
- convert to list
- count
- if there is one or more such interface return
files/myfile.vs1
- return
files/myfile.vs2
otherwise
P.S. >-
用于定义多行字符串并去除任何换行符,否则src
将设置为files/myfile.vs2\n
.
P.S. >-
is used to define multiline string and strip any newlines, otherwise src
will be set to files/myfile.vs2\n
.
这篇关于如何基于网络(子网)成员资格在Ansible中创建条件副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文