Using Ansible to add a NetworkManager connection

The Virtual Machine has two interfaces, but only one is connected to a network. How can I connect the second one?

To check the status of the networks with NetworkManagers Command Line Interface (nmcli) run:

$ sudo nmcli device
eth0    ethernet  connected     System eth0 
eth1    ethernet  disconnected  --          
lo      loopback  unmanaged     --

To bring it up manually:

$ sudo nmcli connection add type ethernet ifname eth1  con-name ethernet-eth1
Connection 'ethernet-eth1' (a13aeb2c-630f-4de6-b735-760264927263) successfully added.

To Automate the same thing via Ansible, we can use the command: module, but that will execute every time unless we check that the interface has an IP address. If it does; we want to skip it. We can check that using the predfined facts variables. Each interface has a variable in the form of ansible_interface, which is a dictionary containing details about the host. Here is what my host has for the interfaces:

        "ansible_eth0": {
            "active": true,
            "device": "eth0",
            "ipv4": {
                "address": "",
                "netmask": "",
                "network": ""
            "ipv6": [
                    "address": "fe80::f816:3eff:fed0:510f",
                    "prefix": "64",
                    "scope": "link"
            "macaddress": "fa:16:3e:d0:51:0f",
            "module": "virtio_net",
            "mtu": 1500,
            "promisc": false,
            "type": "ether"
        "ansible_eth1": {
            "active": true,
            "device": "eth1",
            "macaddress": "fa:16:3e:38:31:71",
            "module": "virtio_net",
            "mtu": 1500,
            "promisc": false,
            "type": "ether"

You can see that, while eth0 has an ipv4 section, eth1 has no such section. Thus, to gate the playbook task on the present of the variable, use a when clause.

Here is the completed task:

  - name: Add second ethernet interface
    command: nmcli connection  add type ethernet ifname eth1  con-name ethernet-eth1
    when: ansible_eth1.ipv4 is not defined

Now, there is an Ansible module for Network Manager, but it is in 2.0 version of Ansible which is not yet released. I want this using the version of Ansible I (and my team) have installed on Fedora 22. Once 2.0 comes out, many of these “one-offs” will use the core modules.

Leave a Reply

Your email address will not be published. Required fields are marked *