
    Vh                        d dl mZmZmZ e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 d dlmZmZ d d	lmZmZ d d
lmZmZ dZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%ddddddddd d!d"d#Z&d$ Z'd% Z(d& Z)d' Z*d( Z+d) Z,d* Z-d+ Z.d, Z/d- Z0d. Z1d/ Z2d0 Z3d1 Z4d2 Z5d3 Z6d4 Z7d5 Z8d6 Z9d7 Z:d8 Z;d9 Z<d>d:Z=d; Z>d< Z?e@d=k(  r e?        yy)?    )absolute_importdivisionprint_functiona  
---
module: ome_template
short_description: Create, modify, deploy, delete, export, import and clone a template on OpenManage Enterprise
version_added: "2.0.0"
description: "This module creates, modifies, deploys, deletes, exports, imports and clones a template on
OpenManage Enterprise."
extends_documentation_fragment:
  - dellemc.openmanage.ome_auth_options
options:
  command:
    description:
      - C(create) creates a new template.
      - C(modify) modifies an existing template.
      - C(deploy) creates a template-deployment job.
      - C(delete) deletes an existing template.
      - C(export) exports an existing template.
      - C(import) creates a template from a specified configuration text in SCP XML format.
      - C(clone) creates a clone of a existing template.
    choices: [create, modify, deploy, delete, export, import, clone]
    default: create
    aliases: ['state']
    type: str
  template_id:
    description:
      - ID of the existing template.
      - This option is applicable when I(command) is C(modify), C(deploy), C(delete), C(clone) and C(export).
      - This option is mutually exclusive with I(template_name).
    type: int
  template_name:
    description:
      - Name of the existing template.
      - This option is applicable when I(command) is C(modify), C(deploy), C(delete), C(clone) and C(export).
      - This option is mutually exclusive with I(template_id).
    type: str
  device_id:
    description:
      - >-
        Specify the list of targeted device ID(s) when I(command) is C(deploy). When I (command) is C(create),
        specify the ID of a single device.
      - Either I(device_id) or I(device_service_tag) is mandatory or both can be applicable.
    type: list
    elements: int
    default: []
  device_service_tag:
    description:
      - >-
        Specify the list of targeted device service tags when I (command) is C(deploy). When I(command) is C(create),
        specify the service tag of a single device.
      - Either I(device_id) or I(device_service_tag) is mandatory or both can be applicable.
    type: list
    elements: str
    default: []
  device_group_names:
    description:
      - Specify the list of groups when I (command) is C(deploy).
      - Provide at least one of the mandatory options I(device_id), I(device_service_tag), or I(device_group_names).
    type: list
    elements: str
    default: []
  template_view_type:
    description:
      - Select the type of view of the OME template.
      - This is applicable when I(command) is C(create),C(clone) and C(import).
    choices: [Deployment, Compliance, Inventory, Sample, None]
    type: str
    default: Deployment
  attributes:
    type: dict
    description:
      - >-
        Payload data for the template operations. All the variables in this option are added as payload for C(create),
        C(modify), C(deploy), C(import), and C(clone) operations. It takes the following attributes.
      - >-
        Attributes: List of dictionaries of attributes (if any) to be modified in the deployment template. This is
        applicable when I(command) is C(deploy) and C(modify). Use the I(Id) If the attribute Id is available.
        If not, use the comma separated I (DisplayName). For more details about using the I(DisplayName),
        see the example provided.
      - >-
        Name: Name of the template. This is mandatory when I(command) is C(create), C(import), C(clone), and
        optional when I(command) is C(modify).
      - >-
        Description: Description for the template. This is applicable when I(command) is C(create) or C(modify).
      - >-
        Fqdds: This allows to create a template using components from a specified reference server. One or more, of the
        following values must be specified in a comma-separated string: iDRAC, System, BIOS, NIC, LifeCycleController,
        RAID, and EventFilters. If none of the values are specified, the default value 'All' is selected.
        This is applicable when I (command) is C(create).
      - >-
        Options: Options to control device shutdown or end power state post template deployment. This is applicable
        for C(deploy) operation.
      - >-
        Schedule: Provides options to schedule the deployment task immediately, or at a specified time. This is
        applicable when I(command) is C(deploy).
      - >-
        NetworkBootIsoModel: Payload to specify the ISO deployment details. This is applicable when I(command) is
        C(deploy).
      - >-
        Content: The XML content of template. This is applicable when I(command) is C(import).
      - >-
        Type: Template type ID, indicating the type of device for which configuration is supported, such as chassis
        and servers. This is applicable when I(command) is C(import).
      - >-
        TypeId: Template type ID, indicating the type of device for which configuration is supported, such as chassis
        and servers. This is applicable when I(command) is C(create).
      - >-
        Refer OpenManage Enterprise API Reference Guide for more details.
  job_wait:
    type: bool
    description:
      - Provides the option to wait for job completion.
      - This option is applicable when I(command) is C(create), or C(deploy).
    default: true
  job_wait_timeout:
    type: int
    description:
      - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
      - This option is applicable when I(job_wait) is C(true).
    default: 1200
requirements:
    - "python >= 3.9.6"
author:
    - "Jagadeesh N V (@jagadeeshnv)"
    - "Husniya Hameed (@husniya_hameed)"
    - "Kritika Bhateja (@Kritika-Bhateja)"
notes:
    - Run this module from a system that has direct access to Dell OpenManage Enterprise.
    - This module supports C(check_mode).
a~)  
---
- name: Create a template from a reference device
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    device_id: 25123
    attributes:
      Name: "New Template"
      Description: "New Template description"

- name: Modify template name, description, and attribute value
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "modify"
    template_id: 12
    attributes:
      Name: "New Custom Template"
      Description: "Custom Template Description"
      # Attributes to be modified in the template.
      # For information on any attribute id, use API /TemplateService/Templates(Id)/Views(Id)/AttributeViewDetails
      # This section is optional
      Attributes:
        - Id: 1234
          Value: "Test Attribute"
          IsIgnored: false

- name: Modify template name, description, and attribute using detailed view
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "modify"
    template_id: 12
    attributes:
      Name: "New Custom Template"
      Description: "Custom Template Description"
      Attributes:
        # Enter the comma separated string as appearing in the Detailed view on GUI
        # NIC -> NIC.Integrated.1-1-1 -> NIC Configuration -> Wake On LAN1
        - DisplayName: 'NIC, NIC.Integrated.1-1-1, NIC Configuration, Wake On LAN'
          Value: Enabled
          IsIgnored: false
        # System -> LCD Configuration -> LCD 1 User Defined String for LCD
        - DisplayName: 'System, LCD Configuration, LCD 1 User Defined String for LCD'
          Value: LCD str by OMAM
          IsIgnored: false

- name: Deploy template on multiple devices
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "deploy"
    template_id: 12
    device_id:
      - 12765
      - 10173
    device_service_tag:
      - 'SVTG123'
      - 'SVTG456'

- name: Deploy template on groups
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "deploy"
    template_id: 12
    device_group_names:
      - server_group_1
      - server_group_2

- name: Deploy template on multiple devices along with the attributes values to be modified on the target devices
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "deploy"
    template_id: 12
    device_id:
      - 12765
      - 10173
    device_service_tag:
      - 'SVTG123'
    attributes:
      # Device specific attributes to be modified during deployment.
      # For information on any attribute id, use API /TemplateService/Templates(Id)/Views(Id)/AttributeViewDetails
      # This section is optional
      Attributes:
        # specific device where attribute to be modified at deployment run-time.
        # The DeviceId should be mentioned above in the 'device_id' section.
        # Service tags not allowed.
        - DeviceId: 12765
          Attributes:
            - Id: 15645
              Value: "0.0.0.0"
              IsIgnored: false
        - DeviceId: 10173
          Attributes:
            - Id: 18968,
              Value: "hostname-1"
              IsIgnored: false

- name: Deploy template and Operating System (OS) on multiple devices
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "deploy"
    template_id: 12
    device_id:
      - 12765
    device_service_tag:
      - 'SVTG123'
    attributes:
      # Include this to install OS on the devices.
      # This section is optional
      NetworkBootIsoModel:
        BootToNetwork: true
        ShareType: "NFS"
        IsoTimeout: 1 # allowable values(1,2,4,8,16) in hours
        IsoPath: "/home/iso_path/filename.iso"
        ShareDetail:
          IpAddress: "192.168.0.2"
          ShareName: "sharename"
          User: "share_user"
          Password: "share_password"
      Options:
        EndHostPowerState: 1
        ShutdownType: 0
        TimeToWaitBeforeShutdown: 300
      Schedule:
        RunLater: true
        RunNow: false

- name: "Deploy template on multiple devices and changes the device-level attributes. After the template is deployed,
install OS using its image"
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "deploy"
    template_id: 12
    device_id:
      - 12765
      - 10173
    device_service_tag:
      - 'SVTG123'
      - 'SVTG456'
    attributes:
      Attributes:
        - DeviceId: 12765
          Attributes:
            - Id: 15645
              Value: "0.0.0.0"
              IsIgnored: false
        - DeviceId: 10173
          Attributes:
            - Id: 18968,
              Value: "hostname-1"
              IsIgnored: false
      NetworkBootIsoModel:
        BootToNetwork: true
        ShareType: "NFS"
        IsoTimeout: 1 # allowable values(1,2,4,8,16) in hours
        IsoPath: "/home/iso_path/filename.iso"
        ShareDetail:
          IpAddress: "192.168.0.2"
          ShareName: "sharename"
          User: "share_user"
          Password: "share_password"
      Options:
        EndHostPowerState: 1
        ShutdownType: 0
        TimeToWaitBeforeShutdown: 300
      Schedule:
        RunLater: true
        RunNow: false

- name: Delete template
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "delete"
    template_id: 12

- name: Export a template
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "export"
    template_id: 12

# Start of example to export template to a local xml file
- name: Export template to a local xml file
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "export"
    template_name: "my_template"
  register: result
- name: Save template into a file
  ansible.builtin.copy:
    content: "{{ result.Content}}"
    dest: "/path/to/exported_template.xml"
# End of example to export template to a local xml file

- name: Clone a template
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "clone"
    template_id: 12
    attributes:
      Name: "New Cloned Template Name"

- name: Import template from XML content
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "import"
    attributes:
      Name: "Imported Template Name"
      # Template Type from TemplateService/TemplateTypes
      Type: 2
      # xml string content
      Content: "<SystemConfiguration Model=\"PowerEdge R940\" ServiceTag=\"SVCTAG1\"
      TimeStamp=\"Tue Sep 24 09:20:57.872551 2019\">\n<Component FQDD=\"AHCI.Slot.6-1\">\n<Attribute
      Name=\"RAIDresetConfig\">True</Attribute>\n<Attribute Name=\"RAIDforeignConfig\">Clear</Attribute>\n
      </Component>\n<Component FQDD=\"Disk.Direct.0-0:AHCI.Slot.6-1\">\n<Attribute Name=\"RAIDPDState\">Ready
      </Attribute>\n<Attribute Name=\"RAIDHotSpareStatus\">No</Attribute>\n</Component>\n
      <Component FQDD=\"Disk.Direct.1-1:AHCI.Slot.6-1\">\n<Attribute Name=\"RAIDPDState\">Ready</Attribute>\n
      <Attribute Name=\"RAIDHotSpareStatus\">No</Attribute>\n</Component>\n</SystemConfiguration>\n"

- name: Import template from local XML file
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "import"
    attributes:
      Name: "Imported Template Name"
      Type: 2
      Content: "{{ lookup('ansible.builtin.file', '/path/to/xmlfile') }}"

- name: "Deploy template and Operating System (OS) on multiple devices."
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "deploy"
    template_id: 12
    device_id:
      - 12765
    device_service_tag:
      - 'SVTG123'
    attributes:
      # Include this to install OS on the devices.
      # This section is optional
      NetworkBootIsoModel:
        BootToNetwork: true
        ShareType: "CIFS"
        IsoTimeout: 1 # allowable values(1,2,4,8,16) in hours
        IsoPath: "/home/iso_path/filename.iso"
        ShareDetail:
          IpAddress: "192.168.0.2"
          ShareName: "sharename"
          User: "share_user"
          Password: "share_password"
      Options:
        EndHostPowerState: 1
        ShutdownType: 0
        TimeToWaitBeforeShutdown: 300
      Schedule:
        RunLater: true
        RunNow: false

- name: Create a compliance template from reference device
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "create"
    device_service_tag:
      - "SVTG123"
    template_view_type: "Compliance"
    attributes:
      Name: "Configuration Compliance"
      Description: "Configuration Compliance Template"
      Fqdds: "BIOS"

- name: Import a compliance template from XML file
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    command: "import"
    template_view_type: "Compliance"
    attributes:
      Name: "Configuration Compliance"
      Content: "{{ lookup('ansible.builtin.file', './test.xml') }}"
      Type: 2

- name: Create a template from a reference device with Job wait as false
  dellemc.openmanage.ome_template:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    device_id: 25123
    attributes:
      Name: "New Template"
      Description: "New Template description"
      Fqdds: iDRAC,BIOS,
    job_wait: false
a  
---
msg:
  description: Overall status of the template operation.
  returned: always
  type: str
  sample: "Successfully created a template with ID 23"
return_id:
  description: ID of the template for C(create), C(modify), C(import) and C(clone) or task created in case of C(deploy).
  returned: success, when I(command) is C(create), C(modify), C(import), C(clone) and C(deploy)
  type: int
  sample: 12
TemplateId:
  description: ID of the template for C(export).
  returned: success, when I(command) is C(export)
  type: int
  sample: 13
Content:
  description: XML content of the exported template. This content can be written to a xml file.
  returned: success, when I(command) is C(export)
  type: str
  sample: "<SystemConfiguration Model=\"PowerEdge R940\" ServiceTag=\"DEFG123\" TimeStamp=\"Tue Sep 24 09:20:57.872551
     2019\">\n<Component FQDD=\"AHCI.Slot.6-1\">\n<Attribute Name=\"RAIDresetConfig\">True</Attribute>\n<Attribute
     Name=\"RAIDforeignConfig\">Clear</Attribute>\n</Component>\n<Component FQDD=\"Disk.Direct.0-0:AHCI.Slot.6-1\">
     \n<Attribute Name=\"RAIDPDState\">Ready</Attribute>\n<Attribute Name=\"RAIDHotSpareStatus\">No</Attribute>
     \n</Component>\n<Component FQDD=\"Disk.Direct.1-1:AHCI.Slot.6-1\">\n<Attribute Name=\"RAIDPDState\">Ready
     </Attribute>\n<Attribute Name=\"RAIDHotSpareStatus\">No</Attribute>\n</Component>\n</SystemConfiguration>"
devices_assigned:
  description: Mapping of devices with the templates already deployed on them.
  returned: I(command) is C(deploy)
  type: dict
  sample: {
        "10362": 28,
        "10312": 23
  }
error_info:
  description: Details of the HTTP Error.
  returned: on HTTP error
  type: dict
  sample: {
    "error": {
      "code": "Base.1.0.GeneralError",
      "message": "A general error has occurred. See ExtendedInfo for more information.",
      "@Message.ExtendedInfo": [
        {
          "MessageId": "GEN1234",
          "RelatedProperties": [],
          "Message": "Unable to process the request because an error occurred.",
          "MessageArgs": [],
          "Severity": "Critical",
          "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
        }
      ]
    }
  }
N)SSLError)RestOMEOmeAnsibleModule)URLError	HTTPError)ConnectionErrorSSLValidationError)apply_diff_keyjob_trackingzTemplateService/Templatesz(TemplateService/Templates({template_id})z,TemplateService/Actions/TemplateService.{op}z9TemplateService/Templates({template_id})/AttributeDetailszDeviceService/DeviceszGroupService/GroupszProfileService/ProfileszJobService/Jobs({job_id}),zNo changes found to be applied.zChanges found to be applied.z+Template with name '{name}' already exists.z~The device(s) '{dev}' have been assigned the template(s) '{temp}' respectively. Please unassign the profiles from the devices.z+Successfully created a template with ID {0}z:Successfully submitted a template creation with job ID {0}z.Successfully modified the template with ID {0}z<Successfully submitted a template deployment with job ID {0}z.Successfully deployed the template with ID {0}zFailed to {command} template.zDeleted successfullyzExported successfullyzImported successfullyzCloned successfullyzITemplate operation is in progress. Task excited after 'job_wait_timeout'.)create_when_job_wait_truecreate_when_job_wait_falsemodifydeploy_when_job_wait_falsedeploy_when_job_wait_truefaildeleteexportimportclone	timed_outc                     	 | j                  dt              }|j                  j                  d      }|S # t        $ r g }Y |S w xY w)NGETvalue)invoke_requestPROFILE_URI	json_dataget	Exception)rest_objrespprofile_lists      s/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/dellemc/openmanage/plugins/modules/ome_template.pyget_profilesr'   F  sQ    &&uk:~~))'2   s   15 AAc                     g }|}|rq| j                  d|      }|j                  }|j                  |j                  dg              t	        |j                  dd            j                  d      }|d   }|rq|S )Nr   r   z@odata.nextLink z/api)r   r    extendr!   strsplit)r#   uritotal_items	next_linkr$   datanext_link_lists          r&   get_group_devices_allr3   O  s{    KI
&&ui8~~488GR01TXX&7<=CCFK"2&	      c                     ddj                  |      i}| j                  dt        |      }|j                  j	                  d      D ]  }|d   |k(  s|c S  |j                  dj                  |             y )	N$filterName eq '{0}'r   query_paramr   Namez?Group name '{0}' is invalid. Please provide a valid group name.msg)formatr   	GROUP_URIr    r!   	fail_json)r#   module
group_namer9   	group_reqgrps         r&   	get_grouprD   [  s    o44Z@AK''yk'RI""&&w/ v;*$J Zaablmnr4   c                    |j                   j                  d      }g }|D ]X  }t        | ||      }t        dj	                  |d         z   }t        | |      }|j                  |D cg c]  }|d   	 c}       Z |S c c}w )Ndevice_group_namesz({0})/DevicesId)paramsr!   rD   r>   r=   r3   r+   )	r#   r@   group_name_list
device_idsrA   group	group_urigroup_device_listdevs	            r&   get_group_detailsrO   d  s    mm''(<=OJ% D
(FJ7 6 6uT{ CC	1(IF0AB3t9BC	D
  Cs   &A=
c                 *   g }| j                   j                  d      s| j                   j                  d      r|j                  t              d   }t	        |D cg c]$  }|j                  d      |j                  d      f& c}      }| j                   j                  d      }t        |      t        |j                               z
  }|rKt        | dj                  dj                  t        t        t        t        |                                     |j                  |       | j                   j                  d      }t        |      t        |j                               z
  }	|	r4t        | d	j                  dj                  t        |	                         |D ]"  }
|j                  |j                  |
             $ | j                   j                  d
      r|j                  t!        ||              t        t        |            S c c}w )zBGetting the list of device ids filtered from the device inventory.device_service_tag	device_idreport_listDeviceServiceTagrG   z[Unable to complete the operation because the entered target device id(s) '{0}' are invalid.r   r;   z]Unable to complete the operation because the entered target service tag(s) '{0}' are invalid.rF   )rH   r!   get_all_report_details
DEVICE_URIdictsetvaluesfail_moduler=   joinlistmapr,   r+   keysappendrO   )r@   r#   
target_idsdevice_listdevicedevice_tag_id_maprR   invalid_idsservice_tagsinvalid_tagstags              r&   get_device_idsrh   o  s   J}}-.&--2C2CK2P55jA-P cn!oY_6::.@#A6::dCS"T!opMM%%k2	)ns+<+C+C+E'FF %@@FsxxPTUXY\^abm^nUoPpGq@rt)$}}(()=><(3/@/E/E/G+HH %AAGQTUaQbHcAdf 	:C/33C89	:}}-.+Hf=>J  ! "ps   )Hc                 <   | j                  dd      }|j                  rf|j                  j                  d      rK|j                  j                  dg       }|D ]*  }|j                  dd      |k(  s|j                  d      c S  ddd	d
dd}|j                  |      S )Nr   z!TemplateService/TemplateViewTypesr   Descriptionr)   rG               r   
Deployment
Compliance	InventorySampleNoner   successr    r!   )r#   viewstrr$   tlistxtypeviewmaps         r&   get_view_idr{     s    ""5*MND||**73""7B/ 	'Eyy+w6yy&	' aa1VWXG;;wr4   c                     | j                  dd      }|j                  rT|j                  j                  d      r9|j                  j                  dg       }|D ]  }|j                  d      |k(  s y y)Nr   zTemplateService/TemplateTypesr   rG   TFru   )r#   typeidr$   rx   ry   s        r&   get_type_id_validr~     sj    ""5*IJD||**73""7B/ 	Eyy&(	 r4   c                     i }t         }ddj                  |       i}|j                  d||      }|j                  j	                  d      D ]  }|d   | k(  s|} |S  |S )Nr6   r7   r   r8   r   r:   )TEMPLATES_URIr=   r   r    r!   )template_namer@   r#   templatetemplate_pathr9   template_reqeachs           r&   get_template_by_namer     sx    H!Mo44]CDK**5-[*YL&&**73 <=(HO	 Or4   c                 r   t        | t              r| D ]  }dj                  |t        |j	                  d            }|j	                  d      rt        |j	                  d      ||||       Y|j	                  d      D ]5  }||d<   dj                  |t        |d         }||v r|d   ||<   |||d   <   7  y y )Nz	{0}{1}{2}DisplayNameSubAttributeGroups
AttributesprefixAttributeId)
isinstancer\   r=   SEPRTRr!   recurse_subattr_list)	subgroupr   attr_detailedattr_mapadv_listeach_subnprfxattrconstrs	            r&   r   r     s    (D!  	9H&&vvx||M7RSE||01$X\\2F%GP]_giqr$LL6 9D%*DN(//vtM?RSF)04]0Cf-48HT-019	9 "r4   c                 z    i }i }| D ]/  }t        |j                  d      |j                  d      |||       1 ||fS )Nr   r   )r   r!   )	attr_dtlsr   r   r   r   s        r&   get_subattr_allr     sN    MH yTXX&:;TXXm=TVcemowxy(""r4   c                    d}	 |j                  dt        j                  |            }|j                  }|j	                  di       }g }|D ]  }	|	j	                  d      st        |	j	                  d            j                  t              }
t        t
        j                  |
      }t        j                  |      }|j                  |        t        |j	                  d      |      \  }}|j	                  dg       }g }|D ]!  }	|	j	                  d      rt        |	j	                  d            j                  t              }
t        t
        j                  |
      }t        j                  |      }|j	                  |d      }||	d<   |	j                  dd        n|	j	                  d      }|s|j	                  |i       }|s|j                  |	       |	j	                  d	      |j	                  d	      k7  s%|	j	                  d
      |j	                  d
      k7  s|dz   }$ |D ]  }|j                  |        	 |S # t        $ r d}Y |S w xY w)Nr   r   template_idr   r   AttributeGroupsr)   rG   Value	IsIgnoredrl   )r   TEMPLATE_ATTRIBUTESr=   r    r!   r,   r-   r   r]   stripr[   r_   r   popremover"   )r@   r#   inp_attrr   diffr$   r   disp_adv_listr   r   split_ktrimmedn_kr   r   payload_attr	rem_attrsidex_valrems                       r&   attributes_checkr     s   D#&&u.A.H.HU`.H.abNN	 \26! 	%Dxx&dhh}56<<VDcii1kk'*$	% #2)--@Q2RT\"]x||L"5	  	$Dxx&dhh}56<<VDcii1kk'*"&&sB/T
-XXd^!b"-$$T*88G$

7(;;txx?TX^XbXbcnXo?o!8D!	$"  	%C$	%
 K  Ks&   AI !EI 3A,I ! I IIc                    d|d}| j                   j                  d      j                         }t        |t              r|j                  d      r|j                  d      n|j                  d      }|r||d<   |j                  dd        |j                  |       t        |j                  d      | |      }|r5| j                  t        j                  |j                  d                   t        |      |d	<   |S )
NAll)Fqdds
ViewTypeId
attributesTypeTypeIdr:   namer;   SourceDeviceId)rH   r!   copyr   rW   r   updater   	exit_jsonTEMPLATE_NAME_EXISTSr=   int)r@   r#   deviceidview_idcreate_payloadattrib_dictr}   r   s           r&   get_create_payloadr     s    $$+-N--##L1668K+t$,7OOF,C(YaIb'-N8$%k*'(?R!5!<!<+//RXBY!<!Z['*8}N#$r4   c           	         i }| j                   j                  d      }|j                  d      |d<   |d   |d<   d}|j                  d|d         |d   k7  rlt        |j                  d      | |      }|r5| j                  t        j                  |j                  d                   |j                  d      |d<   |dz   }|d   |d<   |t        ||dg      z   }|j                  d	      r |t        | |||j                  d            z   }|s| j                  t               t        |t              r|j                  |       |S )
Nr   rG   r:   r   r   r;   rl   rj   r   )rH   r!   r   r   r   r=   r   r   NO_CHANGES_MSGr   rW   r   )r@   r#   template_dictmodify_payloadr   r   r   s          r&   get_modify_payloadr     sE   N--##L1K%))$/K*62N6Dv}V45v9NN'(?R!5!<!<+//RXBY!<!Z[!,!8vax$1-$@N=!.n}oNND|$&vxmFWFWX\F]^^^,+t$k*r4   c                     i }t        | j                  d      t              r |j                  | j                  d             ||d<   ||d<   |S )Nr   rG   	TargetIds)r   r!   rW   r   )module_paramsdeviceidlistr   deploy_payloads       r&   get_deploy_payloadr     sO    N-##L148m//=>&N4".N;r4   c                 D   | j                   j                  d      j                         }i }|j                  d      |d<   t	        |d   | |      }|r)| j                  t        j                  |d                ||d<   d|d<   |j                  d      r|j                  d      n|j                  d      }|rt        ||      r||d<   nt        | d	       |j                  d
      |d
<   t        |t              r#|j                  dd        |j                  |       |S )Nr   r:   r   r;   r   rk   r   r   z/Type provided for 'import' operation is invalidContent)rH   r!   r   r   r   r   r   r=   r~   rZ   r   rW   r   )r@   r#   r   r   import_payloadr   r}   s          r&   get_import_payloadr     s   --##L1668KN(__V4N6#N6$:FHMH188nV>T8UV#*N< N6(3(?[__V$[__U]E^FXv.%+N6"$UV +	 :N9+t$$'k*r4   c                 P   | j                   j                  d      j                         }i }||d<   |j                  d      |d<   t	        |d   | |      }|r)| j                  t        j                  |d                ||d<   t        |t              r|j                  |       |S )Nr   SourceTemplateIdr:   NewTemplateNamer   r;   r   )rH   r!   r   r   r   r   r   r=   r   rW   r   )r@   r#   r   r   r   clone_payloadr   s          r&   get_clone_payloadr   4  s    --##L1668KM(3M$%'2v'>M#$#M2C$DfhWH188mL]>^8_`")M,+t$[)r4   c                     t         j                  |      }|j                  d|      }|j                  r|j                  S t        | d       y )Nr   r   zOUnable to complete the operation because the requested template is not present.r;   )TEMPLATE_PATHr=   r   rv   r    rZ   )r@   r#   r   pathr   s        r&   get_template_by_idr   B  sM    K8D**5$7L%%%F !F 	Gr4   c                    | j                   j                  d      }ddj                  |      i}d}|s0| j                   j                  d      }ddj                  |      i}d}i }|j                  dt        |	      }|j
                  rU|j                  j                  d
      r:|j                  j                  d
g       }|D ]  }|j                  |      |k(  s|} |S )Nr   r6   z	Id eq {0}rG   r   r7   r:   r   r8   r   )rH   r!   r=   r   r   rv   r    )	r@   r#   r   r9   srchr   r$   rx   ry   s	            r&   get_template_detailsr   L  s    			=	)Bk0045KD]]/ /"8"8"<=H""5-["QD||**73""7B/ 	!Eyy"$ 	! Or4   c                 >   | j                   j                  d      }d}i }t        | |      }|j                  d      }|dvr|st        | d       |dk(  rYt	        | |      }t        |      dk7  rt        | d	       t        || j                   d
         }t        | ||d   |      }t        }	nI|dk(  r>t        || j                   d
         }t        j                  d      }	t        | ||      }n|dk(  r2|s| j                  t               t        j                  |      }	d}n|dk(  r4t        j                  |      }	t        | ||      }
t!        | ||
      }d}n|dk(  rt        j                  d      }	d|i}nu|dk(  r-t	        | |      }|st        | d       t#        |      }i }|D ]:  }|d   }|d   dkD  s||v s||d   k(  r|j%                  |       0|d   ||d   <   < |r~| j                  |t&        j                  dj)                  t+        t,        |j/                                     dj)                  t+        t,        |j1                                                  |s| j                  t               t        j                  d      }	t3        | j                   ||      }nB|dk(  r=t        || j                   d
         }t        j                  d       }	t5        | |||      }| j6                  r| j                  t8        d!"       	||fS )#NcommandPOSTrG   )r   creater   z*Enter a valid template_name or template_idr;   r   rl   z2Create template requires only one reference devicetemplate_view_typer   r   Import)opr   r   DELETEr   PUTr   Export
TemplateIddeployz2There are no devices provided for deploy operationTargetIdProfileStater   )rN   temp)devices_assignedr<   Deployr   CloneTr<   changed)rH   r!   r   rZ   rh   lenr{   r   r   TEMPLATE_ACTIONr=   r   r   r   r   r   r   r'   r   DEPLOY_DEV_ASSIGNEDr[   r]   r,   r^   rY   r   r   
check_modeCHANGES_FOUND)r@   r#   r   rest_methodpayloadr   r   
devid_listr   r   r   r%   dev_temp_mapproftargets                  r&   _get_resource_parametersr   ^  s   mm	*GKG#FH5H,,t$K44XF LM(#FH5
z?a$XYh6J(KL$VXz!}gN	H	h6J(KL%%%2$VXw?	H	0###<	H	###<*68[I$VX}E	H	%%%2-	H	#FH5
$XY#H-  	HD*%FN#a'Fj,@$|"44%%f-59,5GLj!12	H l!4!;!;SR^RcRcReIf@gAD#cS_SfSfShJiAj "< "l  m 0%%%2$V]]JL	G	h6J(KL%%%1#FHk7K]D9+%%r4   c                    | j                   j                  d      }|dv r3| j                   d   }| j                   d   }d|v sd|v rt        | d       i }| j                   j                  d      r| j                   j                  d      }|d	v r-|j                  d
      st        | dj                  |             |dk(  r/|j                  d      st        | dj                  |             yyy)zvalidates input parametersr   )r   r   rR   rQ   Nz8Argument device_id or device_service_tag has null valuesr;   r   )r   r   r   r:   z8Argument 'Name' required in attributes for {0} operationr   r   z;Argument 'Content' required in attributes for {0} operation)rH   r!   rZ   r=   )r@   r   dev_iddev_str   s        r&   _validate_inputsr    s    mm	*G&&{+346>TV^$^_K}}&mm''5//v&$^$e$efm$no(y)$a$h$hip$qr * r4   c                     t        | t              rO| j                  d      }t        |t              r-|j                  d      }t        |t              rd|v rd|d<   y y y y y )NNetworkBootIsoModelShareDetailPassword#VALUE_SPECIFIED_IN_NO_LOG_PARAMETER)r   rW   r!   )r   netdictsharedets      r&   password_no_logr    sa    *d#..!67gt${{=1H(D)jH.D'L$ /E) % $r4   c                 p    t        | j                  j                  d              | j                  di | y )Nr    )r  rH   r!   r?   )r@   failmsgs     r&   rZ   rZ     s,    FMM%%l34Fwr4   c                 P   t        |j                  j                  d             d }d}|j                  j                  d      }i }|dv r|j                  |d<   |d   }|dk(  r+|rd}d}nq|d   s
d|d	<   d
}d}nb|j                  d   rd}nPd}nM|dk(  rH|rt	        | |      }d}d}n5|j                  d   rd}n#t        j                  d       t	        | |      }d}|dk(  rd}|j                  }t        j                  |      j                  |      } |j                  d||d| y )Nr   Tr   )r   r   r   r   r   	return_idr   r   Ffaileddeploy_failjob_waitr   r   r   r      r   r   r   r  )
r  rH   r!   r    
get_job_idtimesleepMSG_DICTr=   r   )	r#   r@   responsetime_outr$   changed_flagr   resultmessages	            r&   exit_moduler    s?   FMM%%l34DLmm	*GFCC&00{k"h%$K(#'x '$z*56 !(D1%$z*5

1!(D16(##ll7#**40GFA,A&Ar4   c                     | j                  dt        j                  |            }|j                  j	                  d      }|S )Nr   r   TaskId)r   r   r=   r    r!   )r#   r   r   job_ids       r&   r  r    s=    &&um.B.B{.B.[\H##H-FMr4   c                  z   dddgg dddddddddd	g d
dddg ddddg ddddg dddddddddddddd
} t        | dddggdddggdddggddddgdgddddgdgddddgdgddddgdgddddgdgddg ddgg	ddggd      }	 t        |       t        |j                  d       5 }t	        ||      \  }}}|j                  |||!      }|j                  d"   }d }|r&|j                  d   dk(  rF|j                  }	d#}
d$}|
d%kD  rO	 t        ||	      }|rn?t        j                  |       |
|z
  }
|
d%kD  r0n|j                  d   dk(  r|j                  }|rt        j                  |&      }t        |||j                  d'   (      \  }}}}|rv|j                  d)      j                  d*      d+k(  rt        |||d       nDt         j                  d,      j                  |j                  d   -      }|j#                  |.       |j$                  rt        |||       d d d        y # t        $ r t        j                  |       |
|z
  }
Y Lw xY w# 1 sw Y   y xY w# t        $ r4}t'        |t)        |      t+        j,                  |      /       Y d }~y d }~wt.        $ rJ}t1        |j                  j                  d             |j3                  t)        |      d0       Y d }~y d }~wt4        t6        t8        t:        t<        t>        t@        tB        f$ r }t'        |t)        |      .       Y d }~y d }~ww xY w)1NFr   state)r   r   r   r   r   r   r   )requireddefaultaliaseschoicesr   )r$  typer,   rp   ro   )r$  r%  r'  r\   )r$  r(  r%  elementsrW   boolT)r$  r(  r%  i  )
r   r   r   r   rR   rQ   rF   r   r  job_wait_timeoutr   r   r   r   r   r   r   r   r   r   )rR   rQ   rF   )argument_specrequired_ifmutually_exclusivesupports_check_mode)req_session)r1   r     r  r   )r!  r+  )max_job_wait_secLastRunStatusr:   Runningr   )r   r;   )r<   
error_info)r<   unreachable)"r   r  r   rH   r   r   r    r  r  r  r
   JOB_URIr=   r   r!   r  r  r?   rv   rZ   r,   jsonloadr	   r  r   IOErrorr   r   r   	TypeError
ValueErrorKeyErrorOSError)specsr@   r#   r   r   r   r$   r  r!  r   count
sleep_timejob_uri
job_failedr<   job_dict	wait_timer  errs                      r&   mainrG    s    %(ydf$)59&+U;+0\*eg"'BTYZ+0&R]bc+0&R]bc#(&9!&4H).$OE <.1<.1<.1=/"BDI=/"BDI=/"BDI-!A4H=/"BDI"[]ab

 +O<= "F ** V]]5 !	4)A&()S&D';**;7*KD}}Z0HF==+x7"&..KE!"J!)	%%/+%FF% % JJz2$)J$6E  !) ]]9-9!^^F%nnFn;G;GRYlrlyly  {M  mN  <O8JXy!#<<8<<VD	Q'&$E&.ll6&:&A&A&--XaJb&A&cG",,,9||Hfd3C!	4 !	4"  ) % JJz2$)J$6E$%#!	4 !	4D  EFCTYYs^DD 9)),78SX488X1?Iz[celm *FC))*s   "I! *A IH+IH+4I:C(I"I! +#IIIIII! I! !	L:**JL:%A K**0L:L55L:__main__)F)A
__future__r   r   r   r(  __metaclass__DOCUMENTATIONEXAMPLESRETURNr8  r  sslr   ?ansible_collections.dellemc.openmanage.plugins.module_utils.omer   r   +ansible.module_utils.six.moves.urllib.errorr	   r
   ansible.module_utils.urlsr   r   Aansible_collections.dellemc.openmanage.plugins.module_utils.utilsr   r   r   r   r   r   rV   r>   r   r7  r   r   r   r   r   r  r'   r3   rD   rO   rh   r{   r~   r   r   r   r   r   r   r   r   r   r   r   r   r  r  rZ   r  r  rG  __name__r  r4   r&   <module>rT     sQ   C B@DUn
7
r    e K I j ,:@Q $
!	'
%	2.D U )V*fF*h)Y3,--*d
f	o!2 	9 #&R"4,G$<&~s&M 
$BNJ*Z zF r4   