如何在Ansible中管理nmcli的ethtool属性?
在Ansible中管理NetworkManager连接的ethtool属性的优化方案
方案1:优化Shell模块,避免每次标记changed
直接使用shell模块时,可先检查当前属性状态,仅在需要修改时执行命令,并通过changed_when控制变更标记,只有真正修改时才会显示changed状态。
示例Playbook:
- name: 检查并设置ethtool UDP隧道分段属性 shell: | # 获取当前属性值 CURRENT_TX_SEG=$(nmcli connection show 03da7500-2101-c722-2438-d0d006c28c73 | grep ethtool.feature-tx-udp_tnl-segmentation | awk '{print $2}') CURRENT_TX_CSUM_SEG=$(nmcli connection show 03da7500-2101-c722-2438-d0d006c28c73 | grep ethtool.feature-tx-udp_tnl-csum-segmentation | awk '{print $2}') # 仅当属性不为off时执行修改 if [ "$CURRENT_TX_SEG" != "off" ]; then nmcli connection modify 03da7500-2101-c722-2438-d0d006c28c73 ethtool.feature-tx-udp_tnl-segmentation off fi if [ "$CURRENT_TX_CSUM_SEG" != "off" ]; then nmcli connection modify 03da7500-2101-c722-2438-d0d006c28c73 ethtool.feature-tx-udp_tnl-csum-segmentation off fi changed_when: > (ethtool_check.stdout_lines | select('search', 'ethtool.feature-tx-udp_tnl-segmentation') | first | split() | last != "off") or (ethtool_check.stdout_lines | select('search', 'ethtool.feature-tx-udp_tnl-csum-segmentation') | first | split() | last != "off") register: ethtool_check
方案2:使用community.general.nmcli模块的options参数
community.general.nmcli模块支持通过options字典传递所有NetworkManager连接属性,包括ethtool.*类属性,可自动检查当前状态并仅在需要时变更。
示例Playbook:
- name: 配置NetworkManager连接的ethtool属性 community.general.nmcli: conn_name: 03da7500-2101-c722-2438-d0d006c28c73 state: present options: ethtool.feature-tx-udp_tnl-segmentation: 'off' ethtool.feature-tx-udp_tnl-csum-segmentation: 'off'
该模块会自动对比当前属性值与目标值,仅在不一致时执行修改,正确标记changed状态,是替代shell模块的最优方案。
方案3:直接使用ethtool模块(临时生效)
若无需通过NetworkManager永久保存配置,仅需临时生效,可使用community.general.ethtool模块直接修改网卡属性:
- name: 临时设置网卡ethtool UDP隧道分段属性 community.general.ethtool: interface: eth0 # 替换为实际网卡名称 features: tx-udp_tnl-segmentation: off tx-udp_tnl-csum-segmentation: off
注意:此方法的修改为临时生效,系统重启或NetworkManager重新接管网卡后会失效,适合临时调试场景。
内容的提问来源于stack exchange,提问作者RubenLaguna
相关产品推荐
相关产品推荐

