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...
working version...
- 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")
...
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
Explanation:
ansible_interfaces
ansible_
to become (ansible_eth0
, etc)hostvars
ipv4
is definedipv4.network
equals to 192.168.0.0
files/myfile.vs1
files/myfile.vs2
otherwiseP.S. >-
is used to define multiline string and strip any newlines, otherwise src
will be set to files/myfile.vs2\n
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With