Search code examples
ansibleansible-2.xansible-template

Ansible jinja template using with_dict


So i'm still pretty new to Ansible, and i'm trying to generate a DHCP config file as my first real world Ansible project.

I'm using ansible 2.2.1.0 on RHEL7.

I'm coming unstuck as I have all of my config stored in yaml

---
dhcp_subnets:
  windows:
    description: "Windows Hosts"
    network: 10.33.7.0
    subnet: 255.255.255.0
    interface_name: eth0.152
    range_start: 10.33.7.32
    range_end:  10.33.7.250
    gateway:  10.33.7.254
    domain_name: "testlab.home"
    domain_name_servers:
      - 10.33.11.21
    ntp_servers:
      - 10.33.11.1
    hosts:
      152-rhevm:
        - description: "RHEV-M"
        - mac: "00:30:48:30:5B:1A"
        - address: "10.33.7.20"

  Linux:
    description: "Linux Hosts"
    network: 10.33.7.0
    subnet: 255.255.255.0
    interface_name: eth0.152
    range_start: 10.33.7.32
    range_end:  10.33.7.250
    gateway:  10.33.7.254
    domain_name: "testlab.home"
    domain_name_servers:
      - 10.33.11.21

    ntp_servers:
      - 10.33.11.1
    hosts:
      152-rhevm:
        - description: "RHEV-M"
        - mac: "00:30:48:30:5B:1A"
        - address: "10.33.7.20"

In the ansible playbook itself I can use the following code to print the attributes of each item

- debug:
  msg: "{{item.value.description}}"

with_dict: "{{ dhcp_subnets }}"

tags:
  - debug

However as i'm using this to generate a config file that contains these attributes, I have no idea how to do this. I can't see a with_dict option for jinja2.

I had hoped to use the template within a with_dict loop and have a template similar to the following

###############################################################
# DHCP client file - Managed by Ansible
###############################################################

ddns-update-style interim;
ignore client-updates;

{# Here I want to iterate over dhcp_subnets #}
subnet {{ item.value.network }} netmask {{ item.value.subnet }} {
    # {{ item.value.description }}

    interface "{{ item.value.interface_name }}";
    range               {{ item.value.range_start }} {{ item.value.range_end }};

        option subnet-mask              {{ item.value.subnet }};
        option routers                  {{ item.value.gateway }};

        option domain-name              "{{ item.value.domain_name }}";
        option domain-name-servers      {{ item.value.domain_name_servers }};
    option ntp-servers              {{ item.value.ntp_servers }};

}

Am I trying to solve this problem the wrong way ?

I've read some of the similar questions, but they seem to involve having to flatten out the dictionaries, and I'm keen to avoid that if possible.

Any advice would be greatly appreciated.

Thanks


Solution

  • You can iterate over a dict in Jinja with this syntax:

    {% for (key,value) in dhcp_subnets.iteritems() %}
        {{key}}={{value}}
    {% endfor %}