Sort IP addresses through Jinja2 template

I have a problem with sorting IP addresses through Jinja2 and Ansible. Here are my variables and jinja2 code for the available templates.

Roles / DNS / Vary / main.yml:

---
DC1:
   srv1:
     ip: 10.2.110.3
   srv2:
     ip: 10.2.110.11
   srv3:
     ip: 10.2.110.19
   srv4:
     ip: 10.2.110.24

DC2:
   srv5:
     ip: 172.26.158.3
   srv6:
     ip: 172.26.158.11
   srv7:
     ip: 172.26.158.19
   srv8:
     ip: 172.26.158.24

Roles / DNS / Templates / db.example.com.j2:

$TTL 86400
@       IN SOA                  example.com. root.example.com. (
                                2014051001  ; serial
                                      3600  ; refresh
                                      1800  ; retry
                                    604800  ; expire
                                     86400  ; minimum
)

; Name server
                       IN      NS      dns01.example.com.

; Name server A record
dns01.example.com.        IN      A       10.2.110.92


; 10.2.110.0/24 A records in this Domain
{% for hostname, dnsattr in DC1.iteritems() %}
{{hostname}}.example.com.   IN      A       {{dnsattr.ip}}


; 172.26.158.0/24 A records in this Domain
{% for hostname, dnsattr in DC2.iteritems() %}
{{hostname}}.example.com.   IN      A       {{dnsattr.ip}}

Roles / DNS / Tasks / main.yml:

- name: Update DNS zone file db.example.com 
  template: 
    src: db.example.com.j2
    dest: "/tmp/db.example.com"
  with_items: "{{DC1,DC2}}"

- name: Restart DNS Server
  service:
    name: named
    state: restarted

DNS zone files are created correctly, but IP addresses are not sorted numerically. I tried using the following with no luck:

Sort by node name in alphabetical order

{% for hostname, dnsattr in center.iteritems() | sort %}

Cannot find dnsattr attribute

{% for hostname, dnsattr in center.iteritems() | sort(attribute='dnsattr.ip') %}

Cannot find ip attribute

{% for hostname, dnsattr in center.iteritems() | sort(attribute='ip') %}
+4
source share
1 answer

To sort IP addresses, you can implement and use your own filter plugin (by the way, I would be interested in any other solution):

In ansible.cfgadd filter_plugins = path/to/filter_plugins.

path/to/filter_plugins/ip_filters.py:

#!/usr/bin/python

def ip_sort(ip1, ip2):
    # Sort on the last number 
    return int(ip1.split('.')[-1]) - int(ip2.split('.')[-1])

class FilterModule(object):
    def filters(self):
        return {
            'sort_ip_filter': self.sort_ip_filter,
        }

    def sort_ip_filter(self, ip_list):
        return sorted(ip_list, cmp=ip_sort)

Ansible:

- name: "Sort ips"
  debug:
    msg: vars='{{ my_ips | sort_ip_filter }}'

ipaddr, :

- name: "Sort ips"
  debug:
    msg: vars='{{ my_ips | ipaddr | sort_ip_filter }}'
0

Source: https://habr.com/ru/post/1680159/


All Articles