How To Find the Default Active Ethernet Interface in a Salt State

Posted on Thu 04 February 2016 in Salt

Recently, I was working with my friend Bobby, and we needed a way to find out the default ethernet interface on a host. We were trying to dynamically configure an iptables rule (forwarding port 80 requests to 8153) to use the host's active port when applying a Salt state. We also wanted to avoid using nginx as a hammer to fix Yet Another Routing Problem.

Here's what we came up with:

{{ salt['network.default_route']('inet')[0]['interface'] }}

We saw this work in a Salt state by creating a dummy cmd.run block:

iface-file:
  cmd.run:
    - name: echo {{ salt['network.default_route']('inet')[0]['interface'] }}

Which had a nice output of:

----------
          ID: iface-file
    Function: cmd.run
        Name: echo eth0
      Result: True
     Comment: Command "echo eth0" run
     Started: 06:00:17.170601
    Duration: 8.831 ms
     Changes:
              ----------
              pid:
                  4255
              retcode:
                  0
              stderr:
              stdout:
                  eth0

This can also be run on the command line, though we couldn't find a way to just get the token without resorting to grep|sed|cut:

$ salt-call --local network.default_route inet

local:
    |_
      ----------
      addr_family:
          inet
      destination:
          0.0.0.0
      flags:
          UG
      gateway:
          10.0.2.2
      interface:
          eth0
      netmask:
          0.0.0.0

NOTE: The --local and inet parameters are optional. The --local prevents from looking at master, and according to Github, the only valid values are inet or inet6.

This method was preferable to us rather than looping through ip4_interfaces with grains.get, because doing so would ignore the server's existing configuration (as set through iptables).