Ansible批量部署Linux网络配置需满足四条件:控制机装对Ansible、目标机SSH免密通、主机清单写准、网络模块用对;缺一则ansible all -m ping或community.general.network_interface失败。

Ansible 能批量部署 Linux 网络配置,但不是写完 playbook 就能生效——控制机装对、目标机 SSH 免密通、主机清单写准、网络模块用对,四者缺一不可;任一环节出错,ansible all -m ping 或 ansible all -m community.general.network_interface 都会失败。
控制机安装 Ansible 要匹配系统源特性
Ubuntu/Debian 直接运行 sudo apt update && sudo apt install ansible 即可;若版本太旧(如 Ubuntu 20.04 默认仅 Ansible 2.9),又需新模块(如 community.general),建议改用 python3 -m pip install ansible,前提是 python3 --version ≥ 3.8。CentOS/RHEL 7 必须先配 EPEL 源:wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo && yum clean all && yum repolist,再 yum install ansible;跳过这步必报 “no package found”。CentOS/RHEL 8+ 改用 dnf install ansible,但需确认 PowerTools 仓库已启用,否则 community.general 等扩展模块无法加载。
目标机 SSH 免密必须验证认证链是否完整
-
/etc/ssh/sshd_config 中
PubkeyAuthentication yes必须开启,且AuthorizedKeysFile .ssh/authorized_keys保持默认路径,否则 sshd 不读公钥 - 目标机用户家目录
~/.ssh权限必须是700,~/.ssh/authorized_keys必须是600;权限不对,sshd 会静默拒绝 - 若已设
PasswordAuthentication no,需确保ssh-copy-id是在密码登录仍有效时执行的;否则公钥虽被写入,但后续认证失效 - 快速验证方式:
ssh -o ConnectTimeout=5 -o BatchMode=yes user@host—— 秒退说明连通性正常但认证失败,卡住则可能是防火墙或 SSH 服务未响应
主机清单要支持网络设备差异化分组
默认路径 /etc/ansible/hosts 容易被忽略;推荐在项目目录下单独建 inventory.ini 并显式用 -i inventory.ini 调用。格式必须严格:INI 风格只认 # 开头注释,// 或 ### 会导致解析失败;主机组名后不能有空格;IP 后不能跟中文括号或全角符号。支持变量内联,便于适配不同网络环境:
[eth0-servers] 192.168.1.10 ansible_user=admin ansible_ssh_private_key_file=~/.ssh/id_rsa_eth0 192.168.1.11 ansible_user=admin ansible_ssh_private_key_file=~/.ssh/id_rsa_eth0 <p>[bond0-servers] 192.168.2.20 ansible_user=ops ansible_ssh_private_key_file=~/.ssh/id_rsa_bond0
这样可对不同网卡类型、不同管理网段的机器分别下发网络配置。
网络配置模块选对才能真正生效
- 基础 IP 和路由用
community.general.network_interface(需提前ansible-galaxy collection install community.general);它支持 IPv4/IPv6 地址、子网掩码、网关、DNS、MTU、状态(up/down)等字段,比原生command更可靠、幂等 - 修改
/etc/sysconfig/network-scripts/ifcfg-*(RHEL/CentOS)或/etc/netplan/*.yaml(Ubuntu 18.04+)这类文件,优先用template模块生成并覆盖,避免手动拼接出错 - 重启网络服务不能硬写
systemctl restart network;应按发行版判断:when: ansible_facts['os_family'] == "RedHat"用service模块操作network,when: ansible_facts['os_family'] == "Debian"则用shell执行netplan apply - 所有网络变更后务必加验证任务,例如
- name: verify eth0 has expected IP+command: ip -4 addr show dev eth0 | grep -q "192.168.1.10",防止配置写入但未生效


















