
    Vhai                         d dl mZmZmZ eZdZdZdZd dl	m
Z
 d dlmZ d dlmZmZ d dlmZmZmZ d d	lmZmZ 	 d d
lmZmZ ddZd Zedk(  r e        yy# e$ r d d
lmZmZ Y $w xY w)    )absolute_importdivisionprint_functiona#  
module: netconf_config
author:
  - Leandro Lisboa Penz (@lpenz)
  - Ganesh Nalawade (@ganeshrn)
short_description: netconf device configuration
description:
  - Netconf is a network management protocol developed and standardized by the IETF.
    It is documented in RFC 6241.
  - This module allows the user to send a configuration XML file to a netconf device,
    and detects if there was a configuration change.
version_added: 1.0.0
extends_documentation_fragment:
  - ansible.netcommon.network_agnostic
options:
  content:
    description:
      - The configuration data as defined by the device's data models, the value can
        be either in xml string format or text format or python dictionary representation of JSON format.
      - In case of json string format it will be converted to the corresponding xml string using
        xmltodict library before pushing onto the remote host.
      - In case the value of this option isn I(text) format the format should be supported by remote Netconf server.
      - If the value of C(content) option is in I(xml) format in that case the xml value should
        have I(config) as root tag.
    type: raw
    aliases:
      - xml
  target:
    description:
      Name of the configuration datastore to be edited. - auto, uses candidate
      and fallback to running - candidate, edit <candidate/> datastore and then commit
      - running, edit <running/> datastore directly
    default: auto
    type: str
    choices:
      - auto
      - candidate
      - running
    aliases:
      - datastore
  source_datastore:
    description:
      - Name of the configuration datastore to use as the source to copy the configuration
        to the datastore mentioned by C(target) option. The values can be either I(running),
        I(candidate), I(startup) or a remote URL
    type: str
    aliases:
      - source
  format:
    description:
      - The format of the configuration provided as value of C(content).
      - In case of json string format it will be converted to the corresponding xml string using
        xmltodict library before pushing onto the remote host.
      - In case of I(text) format of the configuration should be supported by remote Netconf server.
      - If the value of C(format) options is not given it tries to guess the data format of
        C(content) option as one of I(xml) or I(json) or I(text).
      - If the data format is not identified it is set to I(xml) by default.
    type: str
    choices:
      - xml
      - text
      - json
  lock:
    description:
      - Instructs the module to explicitly lock the datastore specified as C(target).
        By setting the option value I(always) is will explicitly lock the datastore
        mentioned in C(target) option. It the value is I(never) it will not lock the
        C(target) datastore. The value I(if-supported) lock the C(target) datastore
        only if it is supported by the remote Netconf server.
    type: str
    default: always
    choices:
      - never
      - always
      - if-supported
  default_operation:
    description:
      - The default operation for <edit-config> rpc, valid values are I(merge), I(replace)
        and I(none). If the default value is merge, the configuration data in the C(content)
        option is merged at the corresponding level in the C(target) datastore. If the
        value is replace the data in the C(content) option completely replaces the configuration
        in the C(target) datastore. If the value is none the C(target) datastore is
        unaffected by the configuration in the config option, unless and until the incoming
        configuration data uses the C(operation) operation to request a different operation.
    type: str
    choices:
      - merge
      - replace
      - none
  confirm:
    description:
      - This argument will configure a timeout value for the commit to be confirmed
        before it is automatically rolled back. If the C(confirm_commit) argument is
        set to False, this argument is silently ignored. If the value of this argument
        is set to 0, the commit is confirmed immediately. The remote host MUST support
        :candidate and :confirmed-commit capability for this option to .
    type: int
    default: 0
  confirm_commit:
    description:
      - This argument will execute commit operation on remote device. It can be used
        to confirm a previous commit.
    type: bool
    default: no
  error_option:
    description:
      - This option controls the netconf server action after an error occurs while editing
        the configuration.
      - If I(error_option=stop-on-error), abort the config edit on first error.
      - If I(error_option=continue-on-error), continue to process configuration data
        on error. The error is recorded and negative response is generated if any errors
        occur.
      - If I(error_option=rollback-on-error), rollback to the original configuration
        if any error occurs. This requires the remote Netconf server to support the
        I(error_option=rollback-on-error) capability.
    default: stop-on-error
    type: str
    choices:
      - stop-on-error
      - continue-on-error
      - rollback-on-error
  save:
    description:
      - The C(save) argument instructs the module to save the configuration in C(target)
        datastore to the startup-config if changed and if :startup capability is supported
        by Netconf server.
    default: false
    type: bool
  backup:
    description:
      - This argument will cause the module to create a full backup of the current C(running-config)
        from the remote device before any changes are made. If the C(backup_options)
        value is not given, the backup file is written to the C(backup) folder in the
        playbook root directory or role root directory, if playbook is part of an ansible
        role. If the directory does not exist, it is created.
    type: bool
    default: no
  delete:
    description:
      - It instructs the module to delete the configuration from value mentioned in
        C(target) datastore.
    type: bool
    default: no
  commit:
    description:
      - This boolean flag controls if the configuration changes should be committed
        or not after editing the candidate datastore. This option is supported only
        if remote Netconf server supports :candidate capability. If the value is set
        to I(False) commit won't be issued after edit-config operation and user needs
        to handle commit or discard-changes explicitly.
    type: bool
    default: true
  validate:
    description:
      - This boolean flag if set validates the content of datastore given in C(target)
        option. For this option to work remote Netconf server should support :validate
        capability.
    type: bool
    default: false
  backup_options:
    description:
      - This is a dict object containing configurable options related to backup file
        path. The value of this option is read only when C(backup) is set to I(yes),
        if C(backup) is set to I(no) this option will be silently ignored.
    suboptions:
      filename:
        description:
          - The filename to be used to store the backup configuration. If the filename
            is not given it will be generated based on the hostname, current time and
            date in format defined by <hostname>_config.<current-date>@<current-time>
        type: str
      dir_path:
        description:
          - This option provides the path ending with directory name in which the backup
            configuration file will be stored. If the directory does not exist it will
            be first created and the filename is either the value of C(filename) or
            default filename as described in C(filename) options description. If the
            path value is not given in that case a I(backup) directory will be created
            in the current working directory and backup configuration will be copied
            in C(filename) within I(backup) directory.
        type: path
    type: dict
  get_filter:
    description:
      - This argument specifies the XML string which acts as a filter to restrict the
        portions of the data retrieved from the remote device when comparing the before
        and after state of the device following calls to edit_config. When not specified,
        the entire configuration or state data is returned for comparison depending
        on the value of C(source) option. The C(get_filter) value can be either XML
        string or XPath or JSON string or native python dictionary, if the filter is
        in XPath format the NETCONF server running on remote host should support xpath
        capability else it will result in an error.
    type: raw
requirements:
  - ncclient
notes:
  - This module requires the netconf system service be enabled on the remote device
    being managed.
  - This module supports devices with and without the candidate and confirmed-commit
    capabilities. It will always use the safer feature.
  - This module supports the use of connection=netconf
a8  
- name: use lookup filter to provide xml configuration
  ansible.netcommon.netconf_config:
    content: "{{ lookup('file', './config.xml') }}"

- name: set ntp server in the device
  ansible.netcommon.netconf_config:
    content: |
      <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
          <system xmlns="urn:ietf:params:xml:ns:yang:ietf-system">
              <ntp>
                  <enabled>true</enabled>
                  <server>
                      <name>ntp1</name>
                      <udp><address>127.0.0.1</address></udp>
                  </server>
              </ntp>
          </system>
      </config>

- name: wipe ntp configuration
  ansible.netcommon.netconf_config:
    content: |
      <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
          <system xmlns="urn:ietf:params:xml:ns:yang:ietf-system">
              <ntp>
                  <enabled>false</enabled>
                  <server operation="remove">
                      <name>ntp1</name>
                  </server>
              </ntp>
          </system>
      </config>

- name: configure interface while providing different private key file path (for connection=netconf)
  ansible.netcommon.netconf_config:
    backup: true
  register: backup_junos_location
  vars:
    ansible_private_key_file: /home/admin/.ssh/newprivatekeyfile

- name: configurable backup path
  ansible.netcommon.netconf_config:
    backup: true
    backup_options:
      filename: backup.cfg
      dir_path: /home/user

- name: "configure using direct native format configuration (cisco iosxr)"
  ansible.netcommon.netconf_config:
    format: json
    content:
      {
        "config":
          {
            "interface-configurations":
              {
                "@xmlns": "http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg",
                "interface-configuration":
                  {
                    "active": "act",
                    "description": "test for ansible Loopback999",
                    "interface-name": "Loopback999",
                  },
              },
          },
      }
    get_filter:
      {
        "interface-configurations":
          {
            "@xmlns": "http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg",
            "interface-configuration": null,
          },
      }

- name: "configure using json string format configuration (cisco iosxr)"
  ansible.netcommon.netconf_config:
    format: json
    content: |
      {
          "config": {
              "interface-configurations": {
                  "@xmlns": "http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg",
                  "interface-configuration": {
                      "active": "act",
                      "description": "test for ansible Loopback999",
                      "interface-name": "Loopback999"
                  }
              }
          }
      }
    get_filter: |
      {
            "interface-configurations": {
                "@xmlns": "http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg",
                "interface-configuration": null
            }
        }

# Make a round-trip interface description change, diff the before and after
# this demonstrates the use of the native display format and several utilities
# from the ansible.utils collection

- name: Define the openconfig interface filter
  set_fact:
    filter:
      interfaces:
        "@xmlns": "http://openconfig.net/yang/interfaces"
        interface:
          name: Ethernet2

- name: Get the pre-change config using the filter
  ansible.netcommon.netconf_get:
    source: running
    filter: "{{ filter }}"
    display: native
  register: pre

- name: Update the description
  ansible.utils.update_fact:
    updates:
      - path: pre.output.data.interfaces.interface.config.description
        value: "Configured by ansible {{ 100 | random }}"
  register: updated

- name: Apply the new configuration
  ansible.netcommon.netconf_config:
    content:
      config:
        interfaces: "{{ updated.pre.output.data.interfaces }}"

- name: Get the post-change config using the filter
  ansible.netcommon.netconf_get:
    source: running
    filter: "{{ filter }}"
    display: native
  register: post

- name: Show the differences between the pre and post configurations
  ansible.utils.fact_diff:
    before: "{{ pre.output.data|ansible.utils.to_paths }}"
    after: "{{ post.output.data|ansible.utils.to_paths }}"
# TASK [Show the differences between the pre and post configurations] ********
# --- before
# +++ after
# @@ -1,11 +1,11 @@
#  {
# -    "@time-modified": "2020-10-23T12:27:17.462332477Z",
# +    "@time-modified": "2020-10-23T12:27:21.744541708Z",
#      "@xmlns": "urn:ietf:params:xml:ns:netconf:base:1.0",
#      "interfaces.interface.aggregation.config['fallback-timeout']['#text']": "90",
#      "interfaces.interface.aggregation.config['fallback-timeout']['@xmlns']": "http://arista.com/yang/openconfig/interfaces/augments",
#      "interfaces.interface.aggregation.config['min-links']": "0",
#      "interfaces.interface.aggregation['@xmlns']": "http://openconfig.net/yang/interfaces/aggregate",
# -    "interfaces.interface.config.description": "Configured by ansible 56",
# +    "interfaces.interface.config.description": "Configured by ansible 67",
#      "interfaces.interface.config.enabled": "true",
#      "interfaces.interface.config.mtu": "0",
#      "interfaces.interface.config.name": "Ethernet2",
a^  
server_capabilities:
  description: list of capabilities of the server
  returned: success
  type: list
  sample:
    [
      "urn:ietf:params:netconf:base:1.1",
      "urn:ietf:params:netconf:capability:confirmed-commit:1.0",
      "urn:ietf:params:netconf:capability:candidate:1.0",
    ]
backup_path:
  description: The full path to the backup file
  returned: when backup is yes
  type: str
  sample: /playbooks/ansible/backup/config.2016-07-16@22:28:34
diff:
  description:
    If --diff option in enabled while running, the before and after configuration change are
    returned as part of before and after key.
  returned: when diff is enabled
  type: dict
  sample:
    "after": "<rpc-reply>
<data>
<configuration>
<version>17.3R1.10</version>...<--snip-->"
    "before": "<rpc-reply>
<data>
<configuration>
 <version>17.3R1.10</version>...<--snip-->"

)to_text)AnsibleModule)
ConnectionConnectionError)get_capabilities
get_configsanitize_xml)dict_to_xmlvalidate_and_normalize_data)
fromstringtostringc           
          |dk(  r;	 t        |      }|j                  j                  d      s| j                  d       y y y # t        $ r,}| j                  d|dt        |d             Y d }~y d }~ww xY w)	NxmlconfigzEcontent value should have XML string with config tag as the root nodemsgz@Value of content option is invalid as per the identified format z , validation failed with error: surrogate_then_replaceerrors)r   tagendswith	fail_json	Exceptionr   )moduler   formatrootexcs        t/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/ansible/netcommon/plugins/modules/netconf_config.pyvalidate_configr"     s    
	f%D88$$X.  _ !  /   	73/GHJ 	s   8A 	A7"A22A7c            
      @   t        t               t        d            } t        d\i dt        dgd      dt        g d	d
dg      dt        dg      dt        g d      dt        g dd      dt        g d      dt        dd      dt        dd      d t        g d!d"      d#t        dd      d$t        d%| &      d't        dd      d(t        dd      d)t        dd*      d+t        dd      d,t        d      }d-g}d-g}t        |||d*.      }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d(   }	|j                  d   }
|j                  d   }|j                  d+   }|j                  d'   }|j                  d,   }|j                  d   }	 t        |      \  }}dk(  rd1}nK|d2k(  r	 t              }d1}n7|d3k(  rn1|d1}|j                  d4       nn|j                  d5|d6|/       t        |j                        }t        |      }|d7   }|j                  d8d      }|j                  d9d      }|j                  d:d      }|d;k(  r|s|j                  d</       n;|d=k(  r|s|j                  d>/       n!|d
k(  r|rd;}n|rd=}n|j                  d?/       |r|s|j                  d@|z  /       |
r$|j                  dAd      s|j                  dB/       |dkD  r'|j                  dAd      s|j                  dC|z  /       |r$|j                  dDd      s|j                  dE/       |d3k(  r'|j                  dFd      s|j                  dG|z  /       |r||fnd0}|dHk(  rd}n0||j                  dIg       v rd*}n|j                  dJ|z         |dk(  }d|j                  dKg       dL}d0}d0}d}	 |j                  d#   rFt        ||||M      }t        t        |      dNO      j                         }|j                         |dP<   |r|j!                  |       |r%|j"                  s|j%                  ||       d*|dQ<   nM|	r$|j"                  s|j'                  |       d*|dQ<   n'|
r#|j"                  s|j)                          d*|dQ<   n|r|j"                  r*|s(|j                  dR       d*|dQ<    |j*                  d\i | |r|j-                  |S       d*}|,t        |j                  ||T      dNO      j                         }|dUk7  r<	 t        ||      \  } }!!d2k(  r	 t               }d}n|!d}|j                  dV       n|!}t/        |||       |||j                  d   |j                  d    |dW}" |j0                  d\i |" |rz|j                  d)   rkt        |j                  d;|T      dNO      j                         }|j"                  s#|dkD  r|nd0}#|#rd*nd}$|j)                  |$|#X       n|j3                          |,t        |j                  d=|T      dNO      j                         }t5        |      }%t5        |      }&|%|&k7  rd*|dQ<   |dQ   r4|r|j"                  s|j7                  |dY       |j8                  r|%|&dZ|d[<   |r|j=                  |S       	  |j*                  d\i | y0# t        $ r&}|j                  t        |      /       Y d0}~Jd0}~ww xY w# t        $ r&}|j                  t        |      /       Y d0}~cd0}~ww xY w# t        $ r&}|j                  t        |      /       Y d0}~&d0}~ww xY w# t        $ r&}|j                  t        |      /       Y d0}~Gd0}~ww xY w# t:        $ r6}'|j                  t        |'dNO      j                         /       Y d0}'~'*d0}'~'ww xY w# |r|j=                  |S       w w xY w)]z%main entry point for module executionpath)type)filenamedir_pathcontentr   raw)aliasesr%   target)auto	candidaterunningr,   	datastore)choicesdefaultr*   source_datastoresource)r*   r   )r   textjson)r0   lock)neveralwayszif-supportedr8   )r0   r1   default_operation)mergereplacenoneconfirmintr   )r%   r1   confirm_commitboolFerror_option)stop-on-errorzcontinue-on-errorzrollback-on-errorrB   backupbackup_optionsdict)r%   optionssavedeletecommitTvalidate
get_filter)r(   r2   rH   r?   )argument_specrequired_one_ofmutually_exclusivesupports_check_moder   Nsubtreer5   xpathzYThe data format of get_filter option value couldn't be identified, hence set to 'subtree'zInvalid filter type detected z for get_filter value device_operationssupports_commitsupports_writable_runningsupports_startupr-   z2:candidate is not supported by this netconf serverr.   z9:writable-running is not supported by this netconf serverzMneither :candidate nor :writable-running are supported by this netconf serverz@cannot copy <%s/> to <startup/>, while :startup is not supportedsupports_confirm_commitz1confirm commit is not supported by Netconf serverzQconfirm commit is not supported by this netconf server, given confirm timeout: %dsupports_validatez0validate is not supported by this netconf serversupports_xpathz?filter value '%s' of type xpath is not supported on this devicer7   lock_datastorez=lock operation on '%s' source is not supported on this deviceserver_capabilities)changedrZ   )r6   r   r   
__backup__r[   zOcheck mode not supported as Netconf server doesn't support candidate capability)r+   )r3   filterr4   zRThe data format of content option value couldn't be identified, hence set to 'xml')r   r+   r9   rA   r   )	confirmedtimeoutstartup)beforeafterdiff )rE   r   paramsr   r   r   r   r   warnr   _socket_pathr
   getr   r   striprJ   
check_modecopyrH   rI   	exit_jsonr6   r"   edit_configdiscard_changesr   copy_config_diffr	   unlock)(backup_specrL   rN   rM   r   r   r+   r6   r3   rH   r?   r=   rJ   rG   r]   r   filter_datafilter_typer    conncapabilities
operationsrS   rT   rU   filter_specexecute_lockresultra   rb   lockedresponse
config_objconfig_formatkwargsconfirm_timeoutconfirmed_commitsanitized_beforesanitized_afteres(                                           r!   mainr     s   61BCK eW514 M
 xj1 34 =xP 'CD %+ 7 
 $
* /+, =-. vu-/0 /12 .34 65156 U#7M< VVRSO#'- 	F ]]9%F]]8$F== D]]-.F]]8$F]]#34NmmI&G}}Z(H== D]]<(F]]8$F+#>v#F [ e			/ -F  				" $KKKk MXZ`a 	 	
 f))*D#F+L12J nn%6>O */JE R!~~&8%@ _QR	9	%>XY	6	 F&Fc  
 $RU[[ 	 	
 jnn-FNPQ!Z^^,EuMc 	 	

 
':EBOPgjnn5Eu&MQTZZ 	 	
 ,7;'DKw	:>>"2B7	7 	SV\\]x' +//0ErJF FEFi'=="!&&+LQHXh/8PQWWYF#)<<>F< MM&!$$		&&) $F9$$F# $F9$$ $F9  e %)y!   *6*			(~ OO6+OF3 %' 
 70KFTZ0[-J !F*;!,Z!8 #F"*"FKKl +FFFF3 ! %+]]3F%G &n = F D&v&6==#:OO;{OK3 %'  ((181g$O/>tE$KK*:OKT((*}OO9[OI3 %' 
  ,F3*51O?2$(y!i  1 1$$VY7<<"2!0&F6N KKvK&FvQ  +WS\**+  	/..	/z ! 7$$$667 % ;((WS\(::;n  RWQ/GHNNPQQR KKvK& s   [< *\. 8E_ ]  $_ *^ 5E_ <	\+\&&\+.	]7]] 	^)^
_ 
^_ 	_^<6_ <__ 	`+_>8` >`` `__main__N)r   )
__future__r   r   r   r%   __metaclass__DOCUMENTATIONEXAMPLESRETURNansible.module_utils._textr   ansible.module_utils.basicr   ansible.module_utils.connectionr   r	   Ransible_collections.ansible.netcommon.plugins.module_utils.network.netconf.netconfr
   r   r   Eansible_collections.ansible.netcommon.plugins.module_utils.utils.datar   r   
lxml.etreer   r   ImportErrorxml.etree.ElementTreer"   r   __name__rd       r!   <module>r      s    A @ IV`D
8 / 4 G 
;/
AH zF o  ;::;s   A A'&A'