order list from ansible network interfaces

967 views Asked by At

i'm trying to setup an linux docker host w/ ansible. as already known docker creates network interfaces. my machine has also two network interfaces for networking w/ diffrent networks. the playbook snippet looks like this:

    - name: Dump grep matching interfaces from ansible_interfaces
      set_fact:
         interfaces_list: "{{ ansible_interfaces | select('match', '^(ens)[0-9]+') | list
         }}"
    
    - name: Push 50-net.yaml
      template:
        src: netplan.j2
        dest: "/etc/netplan/50-net.yaml"
        owner: root
        group: root
        mode: u=rw,g=r,o=r

the netplan.j2 template like this

network:
    ethernets:
        {{ interfaces_list[0] }}:
          addresses: [{{ prod_net_ip }}/24]
          gateway4: <gateway-ip>
          nameservers:
            addresses: [<dns-server-ip>]
          dhcp4: no
        {{ interfaces_list[1] }}:
          addresses: [{{ storage_net_ip }}/24]
          dhcp4: no
    version: 2

this is just to understand what i'm trying to do.

interfaces_list can look like this
"['ens224','ens192']"

but the networks are defined manually not w/ dhcp, so i need the list in proper order.
"['ens192','ens224']"

How can i order the interfaces_list in the first step or even in another step?

1

There are 1 answers

0
Moon On BEST ANSWER

How can i order the interfaces_list in the first step or even in another step?

List can be sorted using sort jinja2 filter on the set_fact step itself like so,

- set_fact:
    interfaces_list: "{{ ansible_interfaces | select('match', '^(ens)[0-9]+') | sort | list }}"

debug gives,

ok: [localhost] => 
  interfaces_list:
  - ens192
  - ens224