Search code examples
ansiblejinja2

Ansible Populate Template File with Dynamic Variables


I'm having the following jinja template:

# Configure static IP for Ubuntu 22.04 machine
network:
  ethernets:
    eth0:
      addresses:
        - {{ item.new_static_ip }}/24
      nameservers:
        addresses: [{{ item.netplan_name_servers }}] # Populate this list with the DNS servers necessary.
      renderer: networkd
      routes:
        - to: default
          via: {{ item.netplan_router_gateway }}
  version: 2

In my task, I have the following:

- name: Copy the template 00-installer-config.yaml over
  template:
    src: 00-netplan-static-ip-config-ubuntu.j2
    dest: /etc/netplan/00-installer-config.yaml
    owner: root
    group: root
    mode: 0644
    backup: yes
  with_items:
    - { new_static_ip: "{{ ansible_default_ipv4.address }}", netplan_name_servers: "1.1.1.1", netplan_router_gateway: "{{ router_gateway_address }}" }

I get an error like this:

FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'new_static_ip' is undefined

Is there anything that I'm missing here?


Solution

  • Fixed it by using vars like this:

    # Set Static IP using netplan
    - name: Copy the template 00-installer-config.yaml over
      vars:
        new_static_ip: "{{ ansible_default_ipv4.address }}"
        netplan_name_servers: "1.1.1.1"
        netplan_router_gateway: "{{ router_gateway_address }}"
      template:
        src: 00-netplan-static-ip-config-ubuntu.j2
        dest: /etc/netplan/00-installer-config.yaml
        owner: root
        group: root
        mode: 0644
        backup: yes