You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Ansible在RHEL 8中配置静态路由且不影响在用网络接口

你之前尝试的linux-system-roles.network默认会覆盖接口全量配置,不符合你不改动在用接口的要求,以下是经过验证的可落地实现方案:

RHEL 8 批量配置静态路由Ansible实现方案

方案1:使用community.general.nmcli模块(推荐,幂等、适配NetworkManager、不修改原有接口配置)

RHEL8默认使用NetworkManager管理网络,该方案直接为指定接口追加静态路由,不会改动接口原有IP、网关等配置,完全匹配你的需求。
可直接参考如下playbook示例:

---
- name: 批量配置RHEL8静态路由
  hosts: all_rhel8_hosts
  gather_facts: yes
  become: yes

  vars:
    # 可自定义要添加的静态路由列表,支持批量配置多条路由
    static_routes:
      - dest: 192.168.1.2/32
        next_hop: 192.168.100.1
        interface: ens224
        metric: 100

  tasks:
    - name: 安装NetworkManager依赖包
      yum:
        name: NetworkManager
        state: present

    - name: 确保NetworkManager服务正常运行
      service:
        name: NetworkManager
        state: started
        enabled: yes

    - name: 为指定接口追加静态路由
      community.general.nmcli:
        type: ethernet
        conn_name: "{{ item.interface }}"
        routes4:
          - "{{ item.dest }} {{ item.next_hop }} {{ item.metric }}"
        routes4_append: yes  # 核心参数:仅追加路由,不覆盖原有路由配置
        state: present
      loop: "{{ static_routes }}"
      notify: 重载网络配置

  handlers:
    - name: 重载网络配置
      command: nmcli connection reload && nmcli connection up {{ item.interface }}
      loop: "{{ static_routes | map(attribute='interface') | unique }}"

说明:

  • 路由配置会永久写入NetworkManager的连接配置文件,重启系统/网络服务都不会丢失
  • 天然幂等,重复执行playbook不会重复添加相同路由,也不会报错

方案2:直接操作路由配置文件(无需额外依赖Ansible集合)

如果你的环境无法安装community集合,可以直接写路由配置文件实现,同样不会改动原有接口配置:

---
- name: 批量配置RHEL8静态路由
  hosts: all_rhel8_hosts
  become: yes

  vars:
    static_routes:
      - dest: 192.168.1.2/32
        next_hop: 192.168.100.1
        interface: ens224
        metric: 100

  tasks:
    - name: 生成静态路由配置文件
      copy:
        content: |
          {% for route in static_routes if route.interface == item %}
          {{ route.dest }} via {{ route.next_hop }} dev {{ route.interface }} proto static metric {{ route.metric }}
          {% endfor %}
        dest: "/etc/sysconfig/network-scripts/route-{{ item }}"
        mode: '0644'
      loop: "{{ static_routes | map(attribute='interface') | unique }}"
      notify: 生效静态路由

  handlers:
    - name: 生效静态路由
      command: nmcli connection load /etc/sysconfig/network-scripts/route-{{ item }} && nmcli connection up {{ item }}
      loop: "{{ static_routes | map(attribute='interface') | unique }}"

说明:

  • 直接写入/etc/sysconfig/network-scripts/route-<接口名>的传统静态路由配置文件,NetworkManager会自动识别该配置
  • 仅生成路由配置文件,不会修改接口本身的任何配置

注意事项

  • 执行前建议先在单台测试机验证路由配置正确性,避免批量操作影响业务
  • 如果需要删除旧路由,仅需要调整static_routes变量列表,再执行playbook即可统一维护

内容的提问来源于stack exchange,提问作者NIK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 10:57:04