
    VhW                         d dl mZmZmZ eZdZdZdZdZ	d dl
Z
d dlZd dlmZ d dlmZmZ  G d	 d
e      Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functionzAbinash Mishraa
  
---
module: provision_intent
short_description: Resource module for provision functions
description:
  - Manage operation related to wired and wireless provisioning
  - API to re-provision provisioned devices
  - API to un-provision provisioned devices
version_added: '6.6.0'
extends_documentation_fragment:
  - cisco.dnac.intent_params
author: Abinash Mishra (@abimishr)
options:
  config_verify:
    description: Set to True to verify the Cisco Catalyst Center config after applying
      the playbook config.
    type: bool
    default: false
  state:
    description: The state of DNAC after module completion.
    type: str
    choices: [merged, deleted]
    default: merged
  config:
    description:
      - List of details of device being managed.
    type: list
    elements: dict
    required: true
    suboptions:
      management_ip_address:
        description: Management Ip Address .
        type: str
        required: true
      site_name:
        description: Name of site where the device needs to be added.
        type: str
      managed_ap_locations:
        description: Location of the sites allocated for the APs
        type: list
        elements: str
      dynamic_interfaces:
        description: Interface details of the controller
        type: list
        elements: dict
        suboptions:
          interface_ip_address:
            description: Ip Address allocated to the interface
            type: str
          interface_netmask_in_c_i_d_r:
            description: Ip Address allocated to the interface
            type: int
          interface_gateway:
            description: Ip Address allocated to the interface
            type: str
          lag_or_port_number:
            description: Ip Address allocated to the interface
            type: int
          vlan_id:
            description: Ip Address allocated to the interface
            type: int
          interface_name:
            description: Ip Address allocated to the interface
            type: str
requirements:
  - dnacentersdk == 2.4.5
  - python >= 3.9
notes:
  - SDK Methods used are sites.Sites.get_site, devices.Devices.get_network_device_by_ip,
    task.Task.get_task_by_id, sda.Sda.get_provisioned_wired_device, sda.Sda.re_provision_wired_device,
    sda.Sda.provision_wired_device, wireless.Wireless.provision
  - Paths used are get /dna/intent/api/v1/site get /dna/intent/api/v1/network-device/ip-address/{ipAddress}
    get /dna/intent/api/v1/task/{taskId} get /dna/intent/api/v1/business/sda/provision-device
    put /dna/intent/api/v1/business/sda/provision-device post /dna/intent/api/v1/business/sda/provision-device
    post /dna/intent/api/v1/wireless/provision
a  
- name: Create/Modify a new provision
  cisco.dnac.provision_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log: true
    state: merged
    config:
      - site_name: string
        management_ip_address: string
        managed_ap_locations: list
        dynamic_interfaces:
          - vlan_id: integer
            interface_name: string
            interface_ip_address: string
            interface_gateway: string
            interface_netmask_in_c_i_d_r: integer
            lag_or_port_number: integer
a  
# Case_1: Successful creation/updation/deletion of provision
response_1:
  description: A dictionary with details of provision is returned
  returned: always
  type: dict
  sample: >
    {
      "response":
      {
        "response": String,
        "version": String
        },
      "msg": String
    }
# Case_2: Error while creating a provision
response_2:
  description: A list with the response returned by the Cisco DNAC Python SDK
  returned: always
  type: list
  sample: >
    {
      "response": [],
      "msg": String
    }
# Case_3: Already exists and requires no update
response_3:
  description: A dictionary with the exisiting details as returned by the Cisco DNAC Python SDK
  returned: always
  type: dict
  sample: >
    {
      "response": String,
      "msg": String
    }
N)AnsibleModule)DnacBasevalidate_list_of_dictsc                   \     e Zd ZdZ fdZd Zd ZddZddZd Z	d Z
d	 Zd
 Zd Z xZS )DnacprovisionzH
    Class containing member attributes for provision intent module
    c                 $    t         |   |       y N)super__init__)selfmodule	__class__s     o/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/cisco/dnac/plugins/modules/provision_intent.pyr   zDnacprovision.__init__   s         c                 X   | j                   sd| _        d| _        | S ddddddddddddd	dd
}t        | j                   |      \  }}|r.dj	                  dj                  |            | _        d| _        | S || _        | j                  t        |             d| _        d| _        | S )aH  
        Validate the fields provided in the playbook.
        Checks the configuration provided in the playbook against a predefined specification
        to ensure it adheres to the expected structure and data types.
        Args:
            self: The instance of the class containing the 'config' attribute to be validated.
        Returns:
            The method returns an instance of the class with updated attributes:
                - self.msg: A message describing the validation result.
                - self.status: The status of the validation (either 'success' or 'failed').
                - self.validated_config: If successful, a validated version of the
                  'config' parameter.
        Example:
            To use this method, create an instance of the class and call 'validate_input' on it.
            If the validation succeeds, 'self.status' will be 'success' and
            'self.validated_config' will contain the validated configuration. If it fails,
            'self.status' will be 'failed', and 'self.msg' will describe the validation issues.
        z0config not available in playbook for validattionsuccessstrT)typerequiredlistF)r   r   elementsdict)management_ip_address	site_namemanaged_ap_locationsdynamic_interfacesz#Invalid parameters in playbook: {0}
failedzSuccessfully validated input)	configmsgstatusr   formatjoinvalidated_configlogr   )r   provision_specvalid_provisioninvalid_paramss       r   validate_inputzDnacprovision.validate_input   s    * {{IDH#DKK /4%F"'T:-316%8+1u/5#7
 +AKK+
' <CC		.)+DH"DKK /_%&1r   c                      | j                   d   ddd| j                  d   d   id      }|j                  d	      }|d
   }|dk(  rd}|S |dv rd}|S d}|S )a  
        Fetches the type of device (wired/wireless)

        Parameters:
          - self: The instance of the class containing the 'config' attribute
                  to be validated.
        Returns:
          The method returns an instance of the class with updated attributes:
          - device_type: A string indicating the type of the
                       device (wired/wireless).
        Example:
          Post creation of the validated input, we this method gets the
          type of the device.
        execdevicesget_network_device_by_ip
ip_addressr   r   Tfamilyfunctionparamsop_modifiesresponser3   zWireless Controllerwireless)zSwitches and HubsRouterswiredN)
dnac_applyr'   get)r   dev_responsedev_dictdevice_familydevice_types        r   get_dev_typezDnacprovision.get_dev_type   s      /tv./ $"7"7":;R"ST	
  ##J/ *11$K
 	 >>!K  Kr   c                 
   d}d|i}	  | j                   d   dd|d      }|j                  }|j                  d      s5t        j                  d	|j                  d
      t        j
                        r>dj                  ||j                  d            }| j                  j                  |       y|j                  d
      dk7  rd}nt        j                  d       | j                  j                  t        |             |S )a  
        Fetches the status of the task once any provision API is called

        Parameters:
          - self: The instance of the class containing the 'config' attribute
                  to be validated.
        Returns:
          The method returns an instance of the class with updated attributes:
          - result: A dict indiacting wheter the task was succesful or not
        Example:
          Post creation of the provision task, this method fetheches the task
          status.

        Ftask_idTr.   taskget_task_by_idr2   isErrorr!   progress)flagsz:Discovery task with id {0} has not completed - Reason: {1}failureReason)r#   zIn Progress   )discovery_task)r;   r7   r<   research
IGNORECASEr%   r   	fail_jsontimesleepresultupdater   )r   rC   rR   r5   r7   r#   s         r   get_task_statuszDnacprovision.get_task_status   s     W%.tv.) 	H  ((H||I&"))(,,z2"--+ SYYX\\/:<%%#%.||J'=8JJqM) * 	4x89r   c                 x   	  | j                   d   ddd|id      }ro| j	                  t        |             |j                  d	      }|d
   j                  d      }|D ]+  }|d   dk(  s|j                  d      j                  d      }- S # t        $ r  | j                  j                  dg        Y w xY w)a  
        Fetches the type of site

        Parameters:
          - self: The instance of the class containing the 'config' attribute
                  to be validated.
        Returns:
          The method returns an instance of the class with updated attributes:
          - site_type: A string indicating the type of the
                       site (area/building/floor).
        Example:
          Post creation of the validated input, we this method gets the
          type of the site.
        r.   sitesget_sitenameTr2   zSite not foundr#   r7   r7   r   additionalInfo	nameSpaceLocation
attributesr   )r;   	Exceptionr   rO   r(   r   r<   )r   r   r7   sitesite_additional_infoitem	site_types          r   get_site_typezDnacprovision.get_site_type  s     	E.tv.#	* 	H HHS]#<<
+D#'7;;/?#@ , C$
2 $ 6 : :6 BIC   	EKK!!&6!D	Es   B &B98B9c                 h    | j                   d   d   | j                   d   j                  d      d}|S )a  
        Prepares the payload for provisioning of the wired devices

        Parameters:
          - self: The instance of the class containing the 'config' attribute
                  to be validated.
        Returns:
          The method returns an instance of the class with updated attributes:
          - wired_params: A dictionary containing all the values indicating
                          management IP address of the device and the hierarchy
                          of the site.
        Example:
          Post creation of the validated input, it fetches the required
          paramters and stores it for further processing and calling the
          parameters in other APIs.
        r   r   r   )deviceManagementIpAddresssiteNameHierarchy)r'   r<   )r   wired_paramss     r   get_wired_paramszDnacprovision.get_wired_paramsB  s@    & *.)>)>q)ABY)Z!%!6!6q!9!=!=k!J

 r   c           	         | j                   d   j                  d      | j                   d   j                  d      dg}|d   d   D ]5  }| j                  |      dk7  s| j                  j	                  dg 	       7 g |d   d
<   | j                   d   j                  d      D ]|  }|j                  d      |j                  d      |j                  d      |j                  d      |j                  d      |j                  d      d}|d   d
   j                  |       ~  | j                  d   ddd| j                   d   d   id      }|j                  d      d   j                  d      |d   d<   |S )a   
        Prepares the payload for provisioning of the wireless devices

        Parameters:
          - self: The instance of the class containing the 'config' attribute
                  to be validated.
        Returns:
          The method returns an instance of the class with updated attributes:
          - wireless_params: A list of dictionary containing all the values indicating
                          management IP address of the device, hierarchy
                          of the site, AP Location of the wireless controller and details
                          of the interface
        Example:
          Post creation of the validated input, it fetches the required
          paramters and stores it for further processing and calling the
          parameters in other APIs.
        r   r   r   )r_   managedAPLocationsrj   )r   floorz#Managed AP Location must be a floorrY   dynamicInterfacesr   interface_ip_addressinterface_netmask_in_c_i_d_rinterface_gatewaylag_or_port_numbervlan_idinterface_name)interfaceIPAddressinterfaceNetmaskInCIDRinterfaceGatewaylagOrPortNumbervlanIdinterfaceNamer.   r/   r0   r   Tr2   r7   hostname
deviceName)r'   r<   rc   r   rO   appendr;   )r   wireless_paramsap_loc	interfaceinterface_dictr7   s         r   get_wireless_paramsz!Dnacprovision.get_wireless_params[  s   * --a044[A&*&;&;A&>&B&BCY&Z
 &a()=> 	^F!!F!3w>%%*OZ\%]	^ 35./..q1556JK 		KI&/mm4J&K*3--8V*W$-MM2E$F#,==1E#F#--	2!*/?!@N A23::>J		K +4??6*/+T-B-B1-EF]-^_	
 ,4<<
+CA+F+J+J:+V<(r   c                 L   i | _         | j                         | j                   d<   | j                   d   dk(  r| j                         | j                   d<   nA| j                   d   dk(  r| j                         | j                   d<   n| j	                  d       d| _        d| _        | S )a  
        Get all provision related informantion from the playbook
        Args:
            self: The instance of the class containing the 'config' attribute to be validated.
            config: validated config passed from the playbook
        Returns:
            The method returns an instance of the class with updated attributes:
                - self.want: A dictionary of paramters obtained from the playbook
                - self.msg: A message indicating all the paramters from the playbook are
                collected
                - self.status: Success
        Example:
            It stores all the paramters passed from the playbook for further processing
            before calling the APIs
        r@   r:   prov_paramsr8   z4Passed devices are neither wired or wireless deviceszBSuccessfully collected all parameters from playbook for comparisonr   )wantrA   rh   r   r(   r#   r$   )r   s    r   get_wantzDnacprovision.get_want  s    " 	#'#4#4#6		- 99]#w.'+'<'<'>DIIm$YY}%3'+'?'?'ADIIm$HHKLr   c                    | j                   j                  d      }|dk(  r	  | j                  d   dddd| j                  d   d	   i
      }|j                  d      }|dk(  r' | j                  d   ddd| j                   d   
      }n | j                  d   ddd| j                   d   
      }nY|dk(  r' | j                  d   ddd| j                   d   
      }n-d| j
                  d<   | j                   d   | j
                  d<   | S |j                  d      }| j                  |      }d| j
                  d<   d| j
                  d<   | j                  | j
                  d<   || j
                  d<   | S # t        $ r i }Y 6w xY w)aF  
        Add to provision database
        Args:
            self: An instance of a class used for interacting with Cisco DNA Center.
        Returns:
            object: An instance of the class with updated results and status
            based on the processing of differences.
        Description:
            The function processes the differences and, depending on the
            changes required, it may add, update,or resynchronize devices in
            Cisco DNA Center. The updated results and status are stored in the
            class instance for further use.
        r@   r:   r.   sdaget_provisioned_wired_deviceTz4device_management_                        ip_addressr   r   r3   r4   r6   r5   r$   r   re_provision_wired_devicer   provision_wired_devicer8   	provisionz+Passed device is neither wired nor wirelessr#   r7   taskIdrC   changedzProvision done Successfullydiff)r   r<   r;   r'   r^   rR   rT   )r   r@   status_responser$   r7   rC   provision_infos          r   get_diff_mergedzDnacprovision.get_diff_merged  s    iimmM2'!%"9$//&"9 ; $$--a01HI		# %((2F"24??62 8 $99]3	 34??62 5 $99]3	 J&.tv.!$ yy/	H "ODKK&*ii&>DKK
#K,,x(--g->!%I:E"33F")JQ  %"$%s   +E5 5FFc                    | j                   j                  d      }|dk7  rd| j                  d<   | S 	  | j                  d   dddd	| j                  d
   d   i      }|j                  d      }|dk7  r-d| j                  d<   | j                   d   | j                  d<   | S  | j                  d   dddd| j                  d
   d   i      }|j                  d      }| j                  |      }d| j                  d<   d| j                  d<   | j                  | j                  d<   || j                  d<   | S # t
        $ r i }Y w xY w)a  
        Delete from provision database
        Args:
            self: An instance of a class used for interacting with Cisco DNA Center
        Returns:
            self: An instance of the class with updated results and status based on
            the deletion operation.
        Description:
            This function is responsible for removing devices from the Cisco DNA Center PnP GUI and
            raise Exception if any error occured.
        r@   r:   z%APIs are not supported for the devicer#   r.   r   r   Tz0device_management_                    ip_addressr   r   r   r$   r   z$Passed IP address is not provisionedr   r7   delete_provisioned_wired_devicez,device_management_                ip_addressr   r   r   zDeletion done Successfullyr   )r   r<   rR   r;   r'   r^   rT   )r   r@   r   r$   r7   rC   deletion_infos          r   get_diff_deletedzDnacprovision.get_diff_deleted  sn    iimmM2'!!HDKKK	!5doof57  ))!,-DE		O !$$X.Y!GDKK&*ii&>DKK
#K*4??6*6%%a()@A		
 ,,x(,,W,=!%I9E"33F")J9  	! O	!s   +D7 7EEr   )__name__
__module____qualname____doc__r   r,   rA   rT   rc   rh   r   r   r   r   __classcell__)r   s   @r   r
   r
      sA    !0d D'R"H20d>DL;r   r
   c                     i ddddddddddd	d
gdddddddddddddddddddddddddddddddddddddddddddd dd!dddd"dd#d$d%d&d'd'd(gd)} t        | d*      }t        |      }|j                  j                  d&      }||j                  vr-d+|_        d,j                  |      |_        |j                          |j                         j                          |j                  D ]R  }|j                          |j                         j                           |j                  |          j                          T  |j                  d.i |j                   y-)/z/
    main entry point for module execution
    	dnac_hostTr   )r   r   	dnac_port443)r   defaultdnac_usernameadminuser)r   r   aliasesdnac_password)r   no_logdnac_verifyboolTruednac_versionz2.2.3.3
dnac_debugFdnac_logdnac_log_levelWARNINGdnac_log_file_pathzdnac.logdnac_log_appendconfig_verifydnac_api_task_timeoutinti  dnac_task_poll_interval   validate_response_schemar"   r   r   )r   r   r   statemergeddeleted)r   choices)argument_specsupports_check_modeinvalidzState {0} is invalidN )r   r
   r5   r<   supported_statesr$   r%   r#   check_return_statusr,   r'   reset_valuesr   get_diff_state_apply	exit_jsonrR   )element_specr   dnac_provisionr   r"   s        r   mainr   0  s   KdE!B %E!B#eU[T\%] $et%D "Fv#F	
 #Uy$I !6e"D E B %u&K )5Z*P &4'H $f%G ,e-M .!/L /D0Q 4VT  x>ST!L$ /46F"6*N!!%%g.EN333 )3::5A**,!!#779 11 K##%!5572++E24HHJK
 F-~,,-r   __main__)
__future__r   r   r   r   __metaclass__
__author__DOCUMENTATIONEXAMPLESRETURNrP   rL   ansible.module_utils.basicr   8ansible_collections.cisco.dnac.plugins.module_utils.dnacr   r   r
   r   r   r   r   r   <module>r      si   
 A @
KX0#
H  	 4TH Tn).X zF r   