首页 > 解决方案 > 如何使用 Ansible 正确处理网络接口配置文件?

问题描述

我希望能够使用 Ansible 完全管理我的 /etc/network/interfaces.d/ 配置文件。

我已经将 ansible 用于很多功能,包括 apache 文件、数据库和日志文件,但是我找不到正确添加/更新/删除网络接口配置文件的方法。

我的服务器上有几个不同的项目使用不同的接口,我希望我的 ansible 能够在我可以部署我的项目的任何服务器上工作。

我已经找到了一种使用下一个免费界面创建新文件的方法,如下所示:

- name: calc next free interface
    set_fact:
      nextFreeIf: "
      {%- set ifacePrefix = vars.ansible_default_ipv4.alias -%}
      {%- set ifaceNum = { 'cnt': 0 } -%}
      {%- macro increment(dct, key, inc=1)-%}
        {%- if dct.update({key: dct[key] + inc}) -%}
        {%- endif -%}
      {%- endmacro -%}
      {%- for iface in ansible_interfaces|sort -%}
        {%- if iface| regex_search('^' ~ vars.ansible_default_ipv4.alias) -%}
          {{ increment(ifaceNum, 'cnt') }}
        {%- endif -%}
      {%- endfor -%}
      {{ifacePrefix}}:{{ifaceNum.cnt}}"
    tags: network

- name: "copy network interface configuration"
  template:
    src: "files/etc/network/interfaces.d/my-configuration.conf"
    dest: "/etc/network/interfaces.d/my-configuration.conf"
    owner: root
    group: root
    force: true
  notify: 'restart failover interface'
  tags: network

现在我需要找到一种方法来检查我的配置文件是否已经存在,这样我就不会在每次运行 ansible 时都重新创建新的配置文件。但如果它存在,仍然存在问题:

网络配置文件将如下所示

auto {{ interface }}
iface {{ interface }} inet static
    address {{ ip }}
    netmask 255.255.255.255

由于我不知道我的项目使用了哪个接口,因此我需要检查每个可用接口是否与实际文件匹配,如果不匹配则使用下一个免费接口进行更新。

我找不到使用 Ansible 的方法!

我希望你能帮助我。

标签: ansible

解决方案


好吧,我找到了一个很好的方法来做我想做的事:

如果是这样,我无法弄清楚正在使用什么接口。这就是为什么我想检查每个接口是否是好的接口。我试图通过比较每个接口获得的文件和现有文件来找出这一点。

但我知道使用哪个 IP 地址,或者将使用哪个 IP 地址。Ansible 对每个接口都有一个事实,我可以在其中找到对应的地址。所以我不需要比较文件,我只需要比较地址。

我只是更新了用于获取下一个免费接口的任务,以获取要使用的实际接口,它可以是下一个免费接口,也可以是已经在使用的接口。

- name: find interface to use
  set_fact:
    interface: "
    {%- set ifacePrefix = vars.ansible_default_ipv4.alias -%}
    {%- set ifaceNum = { 'cnt': 1 } -%}
    {%- macro increment(dct, key, inc=1)-%}
        {%- if dct.update({key: dct[key] + inc}) -%}
        {%- endif -%}
    {%- endmacro -%}
    {%- for iface in ansible_interfaces|sort -%}
        {%- if ifacePrefix + '_' + ifaceNum.cnt|string in ansible_interfaces -%}
            {{ increment(ifaceNum, 'cnt') }}
        {%- endif -%}
    {%- endfor -%}
    {%- for iface in ansible_interfaces|sort -%}
        {%- if iface.startswith(ifacePrefix) and ansible_facts[iface]['ipv4']['address'] == ip_failover -%}
            {{ ifaceNum.update({'cnt': iface.split('_')[-1]}) }}
        {%- endif -%}
    {%- endfor -%}
    {{ifacePrefix}}:{{ifaceNum.cnt}}"
  tags: network

对于信息,第一个 for 循环是获取第一个空闲接口,即使接口编号存在间隙,当有人关闭某些接口时可能会发生这种情况。


推荐阅读