Ansible nmcli模块能否直接管理设备而非网络连接?
核心结论
Ansible nmcli模块(现归属community.general集合)确实仅支持connection维度的配置管理,不覆盖nmcli device modify对应的设备级即时操作场景,你认为枚举关联连接再逐改的方案过于繁琐的判断是准确的。
现有实现的优化
你当前使用command模块的实现思路可行,但可以补充幂等判断,避免每次执行都跑无意义的命令,同时解决changed_when: false无法反馈真实变更状态的问题:
- name: 采集系统服务事实 service_facts: - name: 查询目标网卡当前IPv6配置状态 become: yes command: /bin/nmcli -g ipv6.method device show {{ ansible_default_ipv4.interface }} register: current_nm_ipv6_conf when: ansible_facts.services["NetworkManager.service"] is defined changed_when: false check_mode: false - name: 设备级禁用目标网卡IPv6 become: yes command: /bin/nmcli device modify {{ ansible_default_ipv4.interface }} ipv6.method disabled when: - ansible_facts.services["NetworkManager.service"] is defined - current_nm_ipv6_conf.stdout | trim != "disabled"
更规范的持久化配置方案
如果你的需求是永久禁用IPv6(绝大多数生产场景的要求),不需要手动枚举设备关联的所有连接,直接通过Ansible内置的ansible_default_ipv4.connection事实就能拿到网卡对应的活跃连接名,用nmcli模块实现非常简洁,完全不需要额外的遍历逻辑:
- name: 连接级永久禁用默认网卡IPv6 community.general.nmcli: conn_name: "{{ ansible_default_ipv4.connection }}" type: ethernet method6: disabled state: present become: yes when: ansible_facts.services["NetworkManager.service"] is defined
注意:
nmcli device modify修改的是设备当前运行态配置,网卡重连、主机重启后配置会丢失;如果需要永久生效,要么使用上面的connection级模块配置,要么在device修改完成后额外执行配置持久化操作。
方案选择参考
- 仅需要临时修改运行态配置:使用补充了幂等判断的
command模块方案即可,逻辑最简洁 - 需要配置永久生效:优先使用
community.general.nmcli模块方案,原生支持幂等,符合Ansible的最佳实践
内容的提问来源于stack exchange,提问作者sebastien chanson
相关产品推荐
相关产品推荐

