如何根据网络(子网)成员资格在 Ansible 中创建条件副本 [英] How to create conditional copy in Ansible based on network (subnet) membership

查看:16
本文介绍了如何根据网络(子网)成员资格在 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 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

附言>- 用于定义多行字符串并去除任何换行符,否则 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆