已归录
这儿给出三个方法:使用系统角色 rhel-system-roles.network 、nmcli 模块、自定义 shell 脚本。
方法一:通过系统提供的 rhel-system-roles.network 来配置网络
# cat demo.yml
---
- name: demo of rhel-system-roles.network
hosts: web
vars:
network_provider: nm
network_connections:
- name: mycon
persistent_state: present
type: ethernet
autoconnect: yes
mac: 52:54:00:00:fa:0a
ip:
address:
- 172.25.250.20/24
roles:
- rhel-system-roles.network
注意:角色里面使用的一些变量依赖于早期形式的 facts 变量,所以 inject_facts_as_vars 需要设置为 True,否则会报如下错误:
TASK [rhel-system-roles.network : Install packages] ************************************************************
fatal: [servera.lab.example.com]: FAILED! => {"msg": "The conditional check 'not network_packages is subset(ansible_facts.packages.keys())' failed. The error was: error while evaluating conditional (not network_packages is subset(ansible_facts.packages.keys())): 'ansible_python' is undefined\n\nThe error appears to be in '/usr/share/ansible/roles/rhel-system-roles.network/tasks/main.yml': line 21, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n# Therefore install packages only when rpm does not find them\n- name: Install packages\n ^ here\n"}
方法二:通过 nmcli 模块来配置网络
- name: NIC configuration
nmcli:
conn_name: mycon
ifname: ens4
type: thernet
ip4: 172.25.250.30/24
gw4: 172.25.250.254
state: present
方法三:自己写 shell 脚本来配置
假设需要将第二张网卡的 IP 配置为 172.25.0.X,X 是现有 IP 的最后一位。
剧本如下,该剧本会把模版文件复制到受控主机作为配置脚本并运行之。
---
- hosts: web
vars:
NIC: ens37
IP:
- 172.25.0
GATEWAY: 172.25.0.254
DNS: 172.25.0.254
tasks:
- name: copy script template
template:
src: net_conf.sh.j2
dest: /root/net_conf.sh
- name: execute shell script
shell: source /root/net_conf.sh
模版文件如下:
#!/bin/bash
file_name=`nmcli connection show | grep {{ NIC }} | awk '{print $1}'`
if [ "$file_name" == {{ NIC }} ]; then
echo "do nothing"
else
rm -rf /etc/sysconfig/network-scripts/ifcfg-$file_name
nmcli connection add type ethernet con-name {{ NIC }} ifname {{ NIC }}
fi
nmcli connection modify {{ NIC }} ipv4.method manual
VALUE=`ip addr show ens33 | grep 192 | awk '{print $2}' | cut -d "/" -f 1 | cut -d "." -f 4`
nmcli connection modify {{ NIC }} ipv4.addresses {{ IP }}.$VALUE ipv4.gateway {{ GATEWAY }} ipv4.dns {{ DNS }}
nmcli connection down {{ NIC }}
nmcli connection up {{ UP }}