我想将一个版本的文件复制到服务器(如果它有特定子网中的接口),或者如果它没有该子网中的接口则复制到另一个版本。下面是一个工作,但我认为不是最佳的解决方案。我希望有更好的方法符合以下标准......
工作版......
- 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")
...
答案 0 :(得分:4)
一些jinja2忍者技巧,你在这里:
- 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
P.S。 >-
用于定义多行字符串并删除任何换行符,否则src
将设置为files/myfile.vs2\n
。