How to create conditional copy in Ansible based on network (subnet) membership

巧了我就是萌 提交于 2019-12-01 19:47:52

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:

  • 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 to 192.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. >- is used to define multiline string and strip any newlines, otherwise src will be set to files/myfile.vs2\n.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!