---
# Get XML stanzas from the running config of a router.
# stanzas must be supplied via extra_vars file.
# Example of extra_vars:
#### get_stanzas.yaml
# fetch_stanzas:
#   - name: policy-options
#   - name: service
#     children:
#       vprn:
#         keys:
#           service-name: IAS
#         children:
#           - bgp
#### get_stanzas.yaml
#
# Then the playbook can be called via:
# ansible-playbook -i <router_fqdn>, manual_config_get.yaml -e "@get_stanzas.yaml"
#
- name: Get XML config
  hosts: all
  gather_facts: false
  vars:
    ansible_connection: geant.gap_ansible.netconf
    ansible_network_os: geant.gap_ansible.sros
    play_storage_path: "/mnt/artefacts"
    netconf_filter: >
      <configure xmlns="urn:nokia.com:sros:ns:yang:sr:conf">
      {%- for stanza in fetch_stanzas %}
      {%- if stanza.children is defined and stanza.children %}
        <{{ stanza.name }}>
        {%- for cname, cval in stanza.children.items() %}
          {%- if cval.keys is defined and cval.keys %}
          <{{ cname }}>
            {%- for k, kv in cval.keys.items() %}
            <{{ k }}>{{ kv }}</{{ k }}>
            {%- endfor %}
            {%- for leaf in cval.children | default([]) %}
            <{{ leaf }}/>
            {%- endfor %}
          </{{ cname }}>
          {%- else %}
          <{{ cname }}/>
          {%- endif %}
        {%- endfor %}
        </{{ stanza.name }}>
      {%- else %}
        <{{ stanza.name }}/>
      {%- endif %}
      {%- endfor %}
      </configure>

  tasks:
    - name: Validate stanza names
      ansible.builtin.assert:
        that:
          - fetch_stanzas is defined
          - fetch_stanzas | length > 0
          - fetch_stanzas | map(attribute='name') | select('search', '[^a-z0-9-]') | list | length == 0
          - fetch_stanzas | map(attribute='name') | list | length > 0

    - name: Fetch specified stanzas from the running config of {{ inventory_hostname }}
      ansible.netcommon.netconf_get:
        source: running
        display: xml
        filter: "{{ netconf_filter }}"
      register: running_cfg

    - name: Sanity-check fetched data
      ansible.builtin.assert:
        that:
          - running_cfg.output is defined and running_cfg.output | length > 0
          - "'</configure>' in running_cfg.output"
          - "'<data/>' not in running_cfg.output"
        fail_msg: "Router returned empty <data/> — check stanza names / namespace in filter"

    - name: Verify each requested stanza returned
      ansible.builtin.assert:
        that:
          - stanza.name in running_cfg.output
        fail_msg: "Stanza {{ stanza.name }} not found in returned config - a typo?"
      loop: "{{ fetch_stanzas }}"
      loop_control:
        loop_var: stanza

    - name: Save fetched config to a file
      ansible.builtin.copy:
        content: "{{ running_cfg.output }}"
        dest: "{{ play_storage_path }}/audit_running_{{ inventory_hostname }}.xml"
      delegate_to: localhost
