Ansible Linux Networking

Thu 05 October 2017

Recently i needed to setup a bunch of static routes on large number of linux machines

The orignal playbook had a bunch of hard coded interface values, it worked but was not very portable. Since then i have upgraded it to dyanmicly pull the network information from facts and groupvars.

You will want a group_vars with networking info and the new route information.

---
net: 10.100.100.0
gateway: 10.100.100.1
route: 10.100.101.0
route_sub: 255.255.255.0

This is the part that will scrape the interface networks and compare to your group_vars

---

- name: configure | set interface fact
  set_fact:
    interface: "{{ item }}"
  when: (hostvars[inventory_hostname]['ansible_%s' | format(item)]['ipv4'] is defined) and (hostvars[inventory_hostname]['ansible_%s' | format(item)]['ipv4']['network'] == net)
  with_items: "{{ ansible_interfaces }}"

The first part of the when clause is there to catch interfaces that dont have the network info, which for machines with eth0:0 etc it will not. Otherwise you get a nasty fail when it looks for an attribute that does not exist.

In debian world I copy a little ifup script into /etc/network/if-up.d/

I just called it route and made it executable so its run when interface comes up.

/sbin/route add -net {{ route }} netmask {{ route_sub }} gw {{ gateway }} dev {{ interface }}

I was only adding one but if you have a bunch might be better with a dict in your group vars and looping over them. Something like below.

routes:
  dcEU:
    gateway: 192.168.1.1
    net: 192.168.1.0
    route: 10.100.101.0
    route_sub: 255.255.255.0
  dcUS:
    gateway: 10.100.101.1
    net: 10.100.101.0
    route: 192.168.1.0
    route_subnet: 255.255.255.0
{% for r in routes %}
  /sbin/route add -net {{ r.route }} netmask {{ r.route_sub }} gw {{ r.gateway }} dev {{ r.interface }}
{% endfor %}
blog comments powered by Disqus