-1

My pseudocode:
1. Get the ntp server config from "sh run"
2. Store that to a list
3. Jinja template generates the required config. I am passing the ntp_server IPs via -e (extra variables).
4. Add the config from 3, compare 3 and 4 and remove the rest.

I am struggling on step 4 [comparison part]. How do I compare the current config with the config generated from the jinja template? I am using roles.

Please advise.

# Jinja Template

    {% for ntp_srv in ntp_servers %}
    ntp server {{ ntp_srv }}
    {% endfor %}

# tasks file for ansible-ios-ntp
---
  - name: Current Edge servers before
    ios_command:
      commands:
        - sh run | include ntp server
    register: runconfser

  - debug:
      var: runconfser

  # NTP SECTION - START

  - name: Set NTP servers
    ios_config:
      src: ntprequired.j2
    notify: Save Config

  - name: Remove the rest NTP Servers
    with_items: "{{ runconfser.stdout_lines[0] }}"
    when: (item not in {src: 'ntprequired.j2'} and (item!=""))
    ios_config:
      lines:
        - "no {{ item }}"
Chrysna
  • 117
  • 1
  • 1
  • 6

1 Answers1

0

If I understand your question correctly, I believe you'd want to extract the current IPs from the registered output, then capture the ones which are not in the ntp_servers list:

  - set_fact:
     need_ips: |
        {{ ntp_servers | difference(stdout_lines | join(" ") | regex_findall('[0-9.]+')) }}

Or you can obtain the "extra" ones by inverting the order of the difference:

  - set_fact:
     extra_ips: |
        {{ stdout_lines | join(" ") | regex_findall('[0-9.]+') | difference(ntp_servers) }}

I cheated by just searching for [0-9.]+ but you can, of course, make that expression less tolerant by being more specific (aka [1-9](.[0-9.]){3})

mdaniel
  • 31,240
  • 5
  • 55
  • 58
  • I was actually trying to compare the configs generated in ntprequired.j2 with the running-config (variable: runconfser). Is there a way to do that? – Chrysna Sep 26 '18 at 23:36
  • If I am understanding your followup question correctly, `- set_fact: foo: "{{ lookup('template', 'templates/ntprequired.j2') }}"` will assign the _rendered_ Jinja template to a variable, after which you can then carry out that diffing process above – mdaniel Sep 27 '18 at 04:08