Home > Back-end >  How to fill netplan config file with routes via ansible
How to fill netplan config file with routes via ansible

Time:10-28

I'm trying to manage netplan by using ansible. That worked well in the past, where I used the following template:

network:
  version: 2
  renderer: networkd
  ethernets:
    {{ ansible_default_ipv4.interface }}:
      match:
          macaddress: {{ ansible_default_ipv4.macaddress }}
      dhcp4: false
      dhcp6: false
  bridges:
    br0:
      macaddress: {{ ansible_default_ipv4.macaddress }}
      interfaces:
        - {{ ansible_default_ipv4.interface }}
      dhcp4: no
      dhcp6: no
      addresses: [{{ ansible_default_ipv4.address }}/32]
      routes:
        - to: 0.0.0.0/0
          via: {{ ansible_default_ipv4.gateway }}
          on-link: true
      nameservers:
        addresses:
          - {{ DNS1 }}
          - {{ DNS2 }}
          - {{ DNS3 }}

Now I have to add several lines to the route section:

...
  bridges:
    br0:
      routes:
        - to: 0.0.0.0/0
          via: {{ ansible_default_ipv4.gateway }}
          on-link: true
        - to: {{ IP1 }}/32
          scope: link
        - to: {{ IP2 }}/32
          scope: link
...

Now here comes the part, where I struggle.

Due to the fact, that my local routes differs from host to host, I can't use a static template. So I tried to create a list in the host vars file, that contains a list of ips.

ROUTES:
  - ip: "aaa.AAA.aaa.AAA"
  - ip: "bbb.BBB.bbb.BBB"
  - ip: "ccc.CCC.ccc.CCC"
  - ip :"...."
  - n

I wanted to insert this list into my netplan file while looping over this list.

But I dont get it working. Do you have any hint or advice? Thx in advance

CodePudding user response:

you add loop over ROUTES variable

- name: vartest
  hosts: localhost
  vars:
    ROUTES:
      - ip: "aaa.AAA.aaa.AAA"
      - ip: "bbb.BBB.bbb.BBB"
      - ip: "ccc.CCC.ccc.CCC" 
  tasks: 
    - name: display
      template:
        src: test.j2 
        dest: test.conf

template file:

        :
      routes:
        - to: 0.0.0.0/0
          via: {{ ansible_default_ipv4.gateway }}
          on-link: true
{% for rec in ROUTES %}
        - to: {{ rec.ip }}/32
          scope: link
{% endfor %}

be careful to begin the loop jinja2 at the begining of line to avoid whitespace before the string

result in result file:

  routes:
    - to: 0.0.0.0/0
      via: 10.0.2.2
      on-link: true
    - to: aaa.AAA.aaa.AAA/32
      scope: link
    - to: bbb.BBB.bbb.BBB/32
      scope: link
    - to: ccc.CCC.ccc.CCC/32
      scope: link
  • Related