Roles目录结构
Vars 文件 (roles/manage_routes/vars/main.yml)
点击查看代码
routes:
- network: "192.168.1.0"
netmask: "255.255.255.0"
gateway: "192.168.1.1"
- network: "10.0.0.0"
netmask: "255.255.0.0"
gateway: "10.0.0.1"
Tasks 文件 (roles/manage_routes/tasks/main.yml)
点击查看代码
---
- name: Gather network facts
setup:
gather_subset:
- network
- name: Determine the interface for each route
set_fact:
route_interface: "{{ ansible_interfaces | map('regex_replace', '^', 'ansible_') | map('extract', hostvars[inventory_hostname]) | selectattr('ipv4', 'defined') | selectattr('ipv4.address', 'equalto', item.gateway) | map(attribute='interface') | first }}"
loop: "{{ routes }}"
- name: Add static route in CentOS 6
command: "route add -net {{ item.network }} netmask {{ item.netmask }} gw {{ item.gateway }} dev {{ route_interface }}"
when: ansible_distribution == 'CentOS' and ansible_distribution_major_version == '6'
loop: "{{ routes }}"
- name: Add static route in CentOS 7 or Ubuntu 20
command: "ip route add {{ item.network }}/24 via {{ item.gateway }} dev {{ route_interface }}"
when: (ansible_distribution == 'CentOS' and ansible_distribution_major_version == '7') or (ansible_distribution == 'Ubuntu' and ansible_distribution_version is version('20', '='))
loop: "{{ routes }}"
- name: Add static route in Ubuntu 18
command: "ip route add {{ item.network }}/24 via {{ item.gateway }} dev {{ route_interface }}"
when: ansible_distribution == 'Ubuntu' and ansible_distribution_version is version('18', '=')
loop: "{{ routes }}"
使用 Role
点击查看代码
- hosts: all
roles:
- manage_routes