Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_template.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 10.0.1
7 # Copyright (C) 2019-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12
13 from __future__ import (absolute_import, division, print_function)
14 __metaclass__ = type
15
16 DOCUMENTATION = r'''
17 ---
18 module: ome_template
19 short_description: Create, modify, deploy, delete, export, import and clone a template on OpenManage Enterprise
20 version_added: "2.0.0"
21 description: "This module creates, modifies, deploys, deletes, exports, imports and clones a template on
22 OpenManage Enterprise."
23 extends_documentation_fragment:
24 - dellemc.openmanage.ome_auth_options
25 options:
26 command:
27 description:
28 - C(create) creates a new template.
29 - C(modify) modifies an existing template.
30 - C(deploy) creates a template-deployment job.
31 - C(delete) deletes an existing template.
32 - C(export) exports an existing template.
33 - C(import) creates a template from a specified configuration text in SCP XML format.
34 - C(clone) creates a clone of a existing template.
35 choices: [create, modify, deploy, delete, export, import, clone]
36 default: create
37 aliases: ['state']
38 type: str
39 template_id:
40 description:
41 - ID of the existing template.
42 - This option is applicable when I(command) is C(modify), C(deploy), C(delete), C(clone) and C(export).
43 - This option is mutually exclusive with I(template_name).
44 type: int
45 template_name:
46 description:
47 - Name of the existing template.
48 - This option is applicable when I(command) is C(modify), C(deploy), C(delete), C(clone) and C(export).
49 - This option is mutually exclusive with I(template_id).
50 type: str
51 device_id:
52 description:
53 - >-
54 Specify the list of targeted device ID(s) when I(command) is C(deploy). When I (command) is C(create),
55 specify the ID of a single device.
56 - Either I(device_id) or I(device_service_tag) is mandatory or both can be applicable.
57 type: list
58 elements: int
59 default: []
60 device_service_tag:
61 description:
62 - >-
63 Specify the list of targeted device service tags when I (command) is C(deploy). When I(command) is C(create),
64 specify the service tag of a single device.
65 - Either I(device_id) or I(device_service_tag) is mandatory or both can be applicable.
66 type: list
67 elements: str
68 default: []
69 device_group_names:
70 description:
71 - Specify the list of groups when I (command) is C(deploy).
72 - Provide at least one of the mandatory options I(device_id), I(device_service_tag), or I(device_group_names).
73 type: list
74 elements: str
75 default: []
76 template_view_type:
77 description:
78 - Select the type of view of the OME template.
79 - This is applicable when I(command) is C(create),C(clone) and C(import).
80 choices: [Deployment, Compliance, Inventory, Sample, None]
81 type: str
82 default: Deployment
83 attributes:
84 type: dict
85 description:
86 - >-
87 Payload data for the template operations. All the variables in this option are added as payload for C(create),
88 C(modify), C(deploy), C(import), and C(clone) operations. It takes the following attributes.
89 - >-
90 Attributes: List of dictionaries of attributes (if any) to be modified in the deployment template. This is
91 applicable when I(command) is C(deploy) and C(modify). Use the I(Id) If the attribute Id is available.
92 If not, use the comma separated I (DisplayName). For more details about using the I(DisplayName),
93 see the example provided.
94 - >-
95 Name: Name of the template. This is mandatory when I(command) is C(create), C(import), C(clone), and
96 optional when I(command) is C(modify).
97 - >-
98 Description: Description for the template. This is applicable when I(command) is C(create) or C(modify).
99 - >-
100 Fqdds: This allows to create a template using components from a specified reference server. One or more, of the
101 following values must be specified in a comma-separated string: iDRAC, System, BIOS, NIC, LifeCycleController,
102 RAID, and EventFilters. If none of the values are specified, the default value 'All' is selected.
103 This is applicable when I (command) is C(create).
104 - >-
105 Options: Options to control device shutdown or end power state post template deployment. This is applicable
106 for C(deploy) operation.
107 - >-
108 Schedule: Provides options to schedule the deployment task immediately, or at a specified time. This is
109 applicable when I(command) is C(deploy).
110 - >-
111 NetworkBootIsoModel: Payload to specify the ISO deployment details. This is applicable when I(command) is
112 C(deploy).
113 - >-
114 Content: The XML content of template. This is applicable when I(command) is C(import).
115 - >-
116 Type: Template type ID, indicating the type of device for which configuration is supported, such as chassis
117 and servers. This is applicable when I(command) is C(import).
118 - >-
119 TypeId: Template type ID, indicating the type of device for which configuration is supported, such as chassis
120 and servers. This is applicable when I(command) is C(create).
121 - >-
122 Refer OpenManage Enterprise API Reference Guide for more details.
123 job_wait:
124 type: bool
125 description:
126 - Provides the option to wait for job completion.
127 - This option is applicable when I(command) is C(create), or C(deploy).
128 default: true
129 job_wait_timeout:
130 type: int
131 description:
132 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
133 - This option is applicable when I(job_wait) is C(true).
134 default: 1200
135 requirements:
136 - "python >= 3.9.6"
137 author:
138 - "Jagadeesh N V (@jagadeeshnv)"
139 - "Husniya Hameed (@husniya_hameed)"
140 - "Kritika Bhateja (@Kritika-Bhateja)"
141 - "Meenakshi Dembi (@meenakshidembi691)"
142 notes:
143 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
144 - This module supports C(check_mode).
145 '''
146
147 EXAMPLES = r'''
148 ---
149 - name: Create a template from a reference device
150 dellemc.openmanage.ome_template:
151 hostname: "192.168.0.1"
152 username: "username"
153 password: "password"
154 ca_path: "/path/to/ca_cert.pem"
155 device_id: 25123
156 attributes:
157 Name: "New Template"
158 Description: "New Template description"
159
160 - name: Modify template name, description, and attribute value
161 dellemc.openmanage.ome_template:
162 hostname: "192.168.0.1"
163 username: "username"
164 password: "password"
165 ca_path: "/path/to/ca_cert.pem"
166 command: "modify"
167 template_id: 12
168 attributes:
169 Name: "New Custom Template"
170 Description: "Custom Template Description"
171 # Attributes to be modified in the template.
172 # For information on any attribute id, use API /TemplateService/Templates(Id)/Views(Id)/AttributeViewDetails
173 # This section is optional
174 Attributes:
175 - Id: 1234
176 Value: "Test Attribute"
177 IsIgnored: false
178
179 - name: Modify template name, description, and attribute using detailed view
180 dellemc.openmanage.ome_template:
181 hostname: "192.168.0.1"
182 username: "username"
183 password: "password"
184 ca_path: "/path/to/ca_cert.pem"
185 command: "modify"
186 template_id: 12
187 attributes:
188 Name: "New Custom Template"
189 Description: "Custom Template Description"
190 Attributes:
191 # Enter the comma separated string as appearing in the Detailed view on GUI
192 # NIC -> NIC.Integrated.1-1-1 -> NIC Configuration -> Wake On LAN1
193 - DisplayName: 'NIC, NIC.Integrated.1-1-1, NIC Configuration, Wake On LAN'
194 Value: Enabled
195 IsIgnored: false
196 # System -> LCD Configuration -> LCD 1 User Defined String for LCD
197 - DisplayName: 'System, LCD Configuration, LCD 1 User Defined String for LCD'
198 Value: LCD str by OMAM
199 IsIgnored: false
200
201 - name: Deploy template on multiple devices
202 dellemc.openmanage.ome_template:
203 hostname: "192.168.0.1"
204 username: "username"
205 password: "password"
206 ca_path: "/path/to/ca_cert.pem"
207 command: "deploy"
208 template_id: 12
209 device_id:
210 - 12765
211 - 10173
212 device_service_tag:
213 - 'SVTG123'
214 - 'SVTG456'
215
216 - name: Deploy template on groups
217 dellemc.openmanage.ome_template:
218 hostname: "192.168.0.1"
219 username: "username"
220 password: "password"
221 ca_path: "/path/to/ca_cert.pem"
222 command: "deploy"
223 template_id: 12
224 device_group_names:
225 - server_group_1
226 - server_group_2
227
228 - name: Deploy template on multiple devices along with the attributes values to be modified on the target devices
229 dellemc.openmanage.ome_template:
230 hostname: "192.168.0.1"
231 username: "username"
232 password: "password"
233 ca_path: "/path/to/ca_cert.pem"
234 command: "deploy"
235 template_id: 12
236 device_id:
237 - 12765
238 - 10173
239 device_service_tag:
240 - 'SVTG123'
241 attributes:
242 # Device specific attributes to be modified during deployment.
243 # For information on any attribute id, use API /TemplateService/Templates(Id)/Views(Id)/AttributeViewDetails
244 # This section is optional
245 Attributes:
246 # specific device where attribute to be modified at deployment run-time.
247 # The DeviceId should be mentioned above in the 'device_id' section.
248 # Service tags not allowed.
249 - DeviceId: 12765
250 Attributes:
251 - Id: 15645
252 Value: "0.0.0.0"
253 IsIgnored: false
254 - DeviceId: 10173
255 Attributes:
256 - Id: 18968,
257 Value: "hostname-1"
258 IsIgnored: false
259
260 - name: Deploy template and Operating System (OS) on multiple devices
261 dellemc.openmanage.ome_template:
262 hostname: "192.168.0.1"
263 username: "username"
264 password: "password"
265 ca_path: "/path/to/ca_cert.pem"
266 command: "deploy"
267 template_id: 12
268 device_id:
269 - 12765
270 device_service_tag:
271 - 'SVTG123'
272 attributes:
273 # Include this to install OS on the devices.
274 # This section is optional
275 NetworkBootIsoModel:
276 BootToNetwork: true
277 ShareType: "NFS"
278 IsoTimeout: 1 # allowable values(1,2,4,8,16) in hours
279 IsoPath: "/home/iso_path/filename.iso"
280 ShareDetail:
281 IpAddress: "192.168.0.2"
282 ShareName: "sharename"
283 User: "share_user"
284 Password: "share_password"
285 Options:
286 EndHostPowerState: 1
287 ShutdownType: 0
288 TimeToWaitBeforeShutdown: 300
289 Schedule:
290 RunLater: true
291 RunNow: false
292
293 - name: "Deploy template on multiple devices and changes the device-level attributes. After the template is deployed,
294 install OS using its image"
295 dellemc.openmanage.ome_template:
296 hostname: "192.168.0.1"
297 username: "username"
298 password: "password"
299 ca_path: "/path/to/ca_cert.pem"
300 command: "deploy"
301 template_id: 12
302 device_id:
303 - 12765
304 - 10173
305 device_service_tag:
306 - 'SVTG123'
307 - 'SVTG456'
308 attributes:
309 Attributes:
310 - DeviceId: 12765
311 Attributes:
312 - Id: 15645
313 Value: "0.0.0.0"
314 IsIgnored: false
315 - DeviceId: 10173
316 Attributes:
317 - Id: 18968,
318 Value: "hostname-1"
319 IsIgnored: false
320 NetworkBootIsoModel:
321 BootToNetwork: true
322 ShareType: "NFS"
323 IsoTimeout: 1 # allowable values(1,2,4,8,16) in hours
324 IsoPath: "/home/iso_path/filename.iso"
325 ShareDetail:
326 IpAddress: "192.168.0.2"
327 ShareName: "sharename"
328 User: "share_user"
329 Password: "share_password"
330 Options:
331 EndHostPowerState: 1
332 ShutdownType: 0
333 TimeToWaitBeforeShutdown: 300
334 Schedule:
335 RunLater: true
336 RunNow: false
337
338 - name: Delete template
339 dellemc.openmanage.ome_template:
340 hostname: "192.168.0.1"
341 username: "username"
342 password: "password"
343 ca_path: "/path/to/ca_cert.pem"
344 command: "delete"
345 template_id: 12
346
347 - name: Export a template
348 dellemc.openmanage.ome_template:
349 hostname: "192.168.0.1"
350 username: "username"
351 password: "password"
352 ca_path: "/path/to/ca_cert.pem"
353 command: "export"
354 template_id: 12
355
356 # Start of example to export template to a local xml file
357 - name: Export template to a local xml file
358 dellemc.openmanage.ome_template:
359 hostname: "192.168.0.1"
360 username: "username"
361 password: "password"
362 ca_path: "/path/to/ca_cert.pem"
363 command: "export"
364 template_name: "my_template"
365 register: result
366 - name: Save template into a file
367 ansible.builtin.copy:
368 content: "{{ result.Content}}"
369 dest: "/path/to/exported_template.xml"
370 # End of example to export template to a local xml file
371
372 - name: Clone a template
373 dellemc.openmanage.ome_template:
374 hostname: "192.168.0.1"
375 username: "username"
376 password: "password"
377 ca_path: "/path/to/ca_cert.pem"
378 command: "clone"
379 template_id: 12
380 attributes:
381 Name: "New Cloned Template Name"
382
383 - name: Import template from XML content
384 dellemc.openmanage.ome_template:
385 hostname: "192.168.0.1"
386 username: "username"
387 password: "password"
388 ca_path: "/path/to/ca_cert.pem"
389 command: "import"
390 attributes:
391 Name: "Imported Template Name"
392 # Template Type from TemplateService/TemplateTypes
393 Type: 2
394 # xml string content
395 Content: "<SystemConfiguration Model=\"PowerEdge R940\" ServiceTag=\"SVCTAG1\"
396 TimeStamp=\"Tue Sep 24 09:20:57.872551 2019\">\n<Component FQDD=\"AHCI.Slot.6-1\">\n<Attribute
397 Name=\"RAIDresetConfig\">True</Attribute>\n<Attribute Name=\"RAIDforeignConfig\">Clear</Attribute>\n
398 </Component>\n<Component FQDD=\"Disk.Direct.0-0:AHCI.Slot.6-1\">\n<Attribute Name=\"RAIDPDState\">Ready
399 </Attribute>\n<Attribute Name=\"RAIDHotSpareStatus\">No</Attribute>\n</Component>\n
400 <Component FQDD=\"Disk.Direct.1-1:AHCI.Slot.6-1\">\n<Attribute Name=\"RAIDPDState\">Ready</Attribute>\n
401 <Attribute Name=\"RAIDHotSpareStatus\">No</Attribute>\n</Component>\n</SystemConfiguration>\n"
402
403 - name: Import template from local XML file
404 dellemc.openmanage.ome_template:
405 hostname: "192.168.0.1"
406 username: "username"
407 password: "password"
408 ca_path: "/path/to/ca_cert.pem"
409 command: "import"
410 attributes:
411 Name: "Imported Template Name"
412 Type: 2
413 Content: "{{ lookup('ansible.builtin.file', '/path/to/xmlfile') }}"
414
415 - name: "Deploy template and Operating System (OS) on multiple devices."
416 dellemc.openmanage.ome_template:
417 hostname: "192.168.0.1"
418 username: "username"
419 password: "password"
420 ca_path: "/path/to/ca_cert.pem"
421 command: "deploy"
422 template_id: 12
423 device_id:
424 - 12765
425 device_service_tag:
426 - 'SVTG123'
427 attributes:
428 # Include this to install OS on the devices.
429 # This section is optional
430 NetworkBootIsoModel:
431 BootToNetwork: true
432 ShareType: "CIFS"
433 IsoTimeout: 1 # allowable values(1,2,4,8,16) in hours
434 IsoPath: "/home/iso_path/filename.iso"
435 ShareDetail:
436 IpAddress: "192.168.0.2"
437 ShareName: "sharename"
438 User: "share_user"
439 Password: "share_password"
440 Options:
441 EndHostPowerState: 1
442 ShutdownType: 0
443 TimeToWaitBeforeShutdown: 300
444 Schedule:
445 RunLater: true
446 RunNow: false
447
448 - name: Create a compliance template from reference device
449 dellemc.openmanage.ome_template:
450 hostname: "192.168.0.1"
451 username: "username"
452 password: "password"
453 ca_path: "/path/to/ca_cert.pem"
454 command: "create"
455 device_service_tag:
456 - "SVTG123"
457 template_view_type: "Compliance"
458 attributes:
459 Name: "Configuration Compliance"
460 Description: "Configuration Compliance Template"
461 Fqdds: "BIOS"
462
463 - name: Import a compliance template from XML file
464 dellemc.openmanage.ome_template:
465 hostname: "192.168.0.1"
466 username: "username"
467 password: "password"
468 ca_path: "/path/to/ca_cert.pem"
469 command: "import"
470 template_view_type: "Compliance"
471 attributes:
472 Name: "Configuration Compliance"
473 Content: "{{ lookup('ansible.builtin.file', './test.xml') }}"
474 Type: 2
475
476 - name: Create a template from a reference device with Job wait as false
477 dellemc.openmanage.ome_template:
478 hostname: "192.168.0.1"
479 username: "username"
480 password: "password"
481 ca_path: "/path/to/ca_cert.pem"
482 device_id: 25123
483 attributes:
484 Name: "New Template"
485 Description: "New Template description"
486 Fqdds: iDRAC,BIOS,
487 job_wait: false
488 '''
489
490 RETURN = r'''
491 ---
492 msg:
493 description: Overall status of the template operation.
494 returned: always
495 type: str
496 sample: "Successfully created a template with ID 23"
497 return_id:
498 description: ID of the template for C(create), C(modify), C(import) and C(clone) or task created in case of C(deploy).
499 returned: success, when I(command) is C(create), C(modify), C(import), C(clone) and C(deploy)
500 type: int
501 sample: 12
502 TemplateId:
503 description: ID of the template for C(export).
504 returned: success, when I(command) is C(export)
505 type: int
506 sample: 13
507 Content:
508 description: XML content of the exported template. This content can be written to a xml file.
509 returned: success, when I(command) is C(export)
510 type: str
511 sample: "<SystemConfiguration Model=\"PowerEdge R940\" ServiceTag=\"DEFG123\" TimeStamp=\"Tue Sep 24 09:20:57.872551
512 2019\">\n<Component FQDD=\"AHCI.Slot.6-1\">\n<Attribute Name=\"RAIDresetConfig\">True</Attribute>\n<Attribute
513 Name=\"RAIDforeignConfig\">Clear</Attribute>\n</Component>\n<Component FQDD=\"Disk.Direct.0-0:AHCI.Slot.6-1\">
514 \n<Attribute Name=\"RAIDPDState\">Ready</Attribute>\n<Attribute Name=\"RAIDHotSpareStatus\">No</Attribute>
515 \n</Component>\n<Component FQDD=\"Disk.Direct.1-1:AHCI.Slot.6-1\">\n<Attribute Name=\"RAIDPDState\">Ready
516 </Attribute>\n<Attribute Name=\"RAIDHotSpareStatus\">No</Attribute>\n</Component>\n</SystemConfiguration>"
517 devices_assigned:
518 description: Mapping of devices with the templates already deployed on them.
519 returned: I(command) is C(deploy)
520 type: dict
521 sample: {
522 "10362": 28,
523 "10312": 23
524 }
525 error_info:
526 description: Details of the HTTP Error.
527 returned: on HTTP error
528 type: dict
529 sample: {
530 "error": {
531 "code": "Base.1.0.GeneralError",
532 "message": "A general error has occurred. See ExtendedInfo for more information.",
533 "@Message.ExtendedInfo": [
534 {
535 "MessageId": "GEN1234",
536 "RelatedProperties": [],
537 "Message": "Unable to process the request because an error occurred.",
538 "MessageArgs": [],
539 "Severity": "Critical",
540 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
541 }
542 ]
543 }
544 }
545 '''
546
547 import time
548 from ssl import SSLError
549 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
550 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
551 from ansible.module_utils.urls import ConnectionError, SSLValidationError
552 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import apply_diff_key, job_tracking
553
554
555 TEMPLATES_URI = "TemplateService/Templates"
556 TEMPLATE_PATH = "TemplateService/Templates({template_id})"
557 TEMPLATE_ACTION = "TemplateService/Actions/TemplateService.{op}"
558 TEMPLATE_ATTRIBUTES = "TemplateService/Templates({template_id})/AttributeDetails"
559 DEVICE_URI = "DeviceService/Devices"
560 GROUP_URI = "GroupService/Groups"
561 PROFILE_URI = "ProfileService/Profiles"
562 JOB_URI = "JobService/Jobs({job_id})"
563 SEPRTR = ','
564 NO_CHANGES_MSG = "No changes found to be applied."
565 CHANGES_FOUND = "Changes found to be applied."
566 TEMPLATE_NAME_EXISTS = "Template with name '{name}' already exists."
567 DEPLOY_DEV_ASSIGNED = "The device(s) '{dev}' have been assigned the template(s) '{temp}' " \
568 "respectively. Please unassign the profiles from the devices."
569 MSG_DICT = {'create_when_job_wait_true': "Successfully created a template with ID {0}",
570 'create_when_job_wait_false': "Successfully submitted a template creation with job ID {0}",
571 'modify': "Successfully modified the template with ID {0}",
572 'deploy_when_job_wait_false': "Successfully submitted a template deployment with job ID {0}",
573 'deploy_when_job_wait_true': "Successfully deployed the template with ID {0}",
574 'fail': 'Failed to {command} template.',
575 'delete': "Deleted successfully",
576 'export': "Exported successfully",
577 'import': "Imported successfully",
578 'clone': "Cloned successfully",
579 'timed_out': "Template operation is in progress. Task excited after 'job_wait_timeout'."}
580
581
582 def get_profiles(rest_obj):
583 try:
584 resp = rest_obj.invoke_request('GET', PROFILE_URI)
585 profile_list = resp.json_data.get("value")
586 except Exception:
587 profile_list = []
588 return profile_list
589
590
591 def get_group_devices_all(rest_obj, uri):
592 total_items = []
593 next_link = uri
594 while next_link:
595 resp = rest_obj.invoke_request('GET', next_link)
596 data = resp.json_data
597 total_items.extend(data.get("value", []))
598 next_link_list = str(data.get('@odata.nextLink', '')).split('/api')
599 next_link = next_link_list[-1]
600 return total_items
601
602
603 def get_group(rest_obj, module, group_name):
604 query_param = {"$filter": "Name eq '{0}'".format(group_name)}
605 group_req = rest_obj.invoke_request("GET", GROUP_URI, query_param=query_param)
606 for grp in group_req.json_data.get('value'):
607 if grp['Name'] == group_name:
608 return grp
609 module.exit_json(msg="Group name '{0}' is invalid. Please provide a valid group name.".format(group_name), failed=True)
610
611
612 def get_group_details(rest_obj, module):
613 group_name_list = module.params.get('device_group_names')
614 device_ids = []
615 for group_name in group_name_list:
616 group = get_group(rest_obj, module, group_name)
617 group_uri = GROUP_URI + "({0})/Devices".format(group['Id'])
618 group_device_list = get_group_devices_all(rest_obj, group_uri)
619 device_ids.extend([dev['Id'] for dev in group_device_list])
620 return device_ids
621
622
623 def get_device_ids(module, rest_obj):
624 """Getting the list of device ids filtered from the device inventory."""
625 target_ids = []
626 if module.params.get('device_service_tag') or module.params.get('device_id'):
627 # device_list = get_group_devices_all(rest_obj, DEVICE_URI)
628 device_list = rest_obj.get_all_report_details(DEVICE_URI)['report_list']
629 device_tag_id_map = dict([(device.get('DeviceServiceTag'), device.get('Id')) for device in device_list])
630 device_id = module.params.get('device_id')
631 invalid_ids = set(device_id) - set(device_tag_id_map.values())
632 if invalid_ids:
633 fail_module(module, msg="Unable to complete the operation because the entered target device"
634 " id(s) '{0}' are invalid.".format(",".join(list(map(str, set(invalid_ids))))))
635 target_ids.extend(device_id)
636 service_tags = module.params.get('device_service_tag')
637 invalid_tags = set(service_tags) - set(device_tag_id_map.keys())
638 if invalid_tags:
639 fail_module(module, msg="Unable to complete the operation because the entered target service"
640 " tag(s) '{0}' are invalid.".format(",".join(set(invalid_tags))))
641 for tag in service_tags: # append ids for service tags
642 target_ids.append(device_tag_id_map.get(tag))
643 if module.params.get('device_group_names'):
644 target_ids.extend(get_group_details(rest_obj, module))
645 return list(set(target_ids)) # set to eliminate duplicates
646
647
648 def get_view_id(rest_obj, viewstr):
649 resp = rest_obj.invoke_request('GET', "TemplateService/TemplateViewTypes")
650 if resp.success and resp.json_data.get('value'):
651 tlist = resp.json_data.get('value', [])
652 for xtype in tlist:
653 if xtype.get('Description', "") == viewstr:
654 return xtype.get('Id')
655 viewmap = {"Deployment": 2, "Compliance": 1, "Inventory": 3, "Sample": 4, "None": 0}
656 return viewmap.get(viewstr)
657
658
659 def get_type_id_valid(rest_obj, typeid):
660 resp = rest_obj.invoke_request('GET', "TemplateService/TemplateTypes")
661 if resp.success and resp.json_data.get('value'):
662 tlist = resp.json_data.get('value', [])
663 for xtype in tlist:
664 if xtype.get('Id') == typeid:
665 return True
666 return False
667
668
669 def get_template_by_name(template_name, module, rest_obj):
670 template = {}
671 template_path = TEMPLATES_URI
672 query_param = {"$filter": "Name eq '{0}'".format(template_name)}
673 template_req = rest_obj.invoke_request("GET", template_path, query_param=query_param)
674 for each in template_req.json_data.get('value'):
675 if each['Name'] == template_name:
676 template = each
677 break
678 return template
679
680
681 def recurse_subattr_list(subgroup, prefix, attr_detailed, attr_map, adv_list):
682 if isinstance(subgroup, list):
683 for each_sub in subgroup:
684 nprfx = "{0}{1}{2}".format(prefix, SEPRTR, each_sub.get("DisplayName"))
685 if each_sub.get("SubAttributeGroups"):
686 recurse_subattr_list(each_sub.get("SubAttributeGroups"), nprfx, attr_detailed, attr_map, adv_list)
687 else:
688 for attr in each_sub.get('Attributes'):
689 attr['prefix'] = nprfx
690 # case sensitive, remove whitespaces for optim
691 constr = "{0}{1}{2}".format(nprfx, SEPRTR, attr['DisplayName'])
692 if constr in adv_list:
693 attr_detailed[constr] = attr['AttributeId']
694 attr_map[attr['AttributeId']] = attr
695
696
697 def get_subattr_all(attr_dtls, adv_list):
698 attr_detailed = {}
699 attr_map = {}
700 for each in attr_dtls:
701 recurse_subattr_list(each.get('SubAttributeGroups'), each.get('DisplayName'), attr_detailed, attr_map, adv_list)
702 return attr_detailed, attr_map
703
704
705 def attributes_check(module, rest_obj, inp_attr, template_id):
706 diff = 0
707 try:
708 resp = rest_obj.invoke_request("GET", TEMPLATE_ATTRIBUTES.format(template_id=template_id))
709 attr_dtls = resp.json_data
710 disp_adv_list = inp_attr.get("Attributes", {})
711 adv_list = []
712 for attr in disp_adv_list:
713 if attr.get("DisplayName"):
714 split_k = str(attr.get("DisplayName")).split(SEPRTR)
715 trimmed = map(str.strip, split_k)
716 n_k = SEPRTR.join(trimmed)
717 adv_list.append(n_k)
718 attr_detailed, attr_map = get_subattr_all(attr_dtls.get('AttributeGroups'), adv_list)
719 payload_attr = inp_attr.get("Attributes", [])
720 rem_attrs = []
721 for attr in payload_attr:
722 if attr.get("DisplayName"):
723 split_k = str(attr.get("DisplayName")).split(SEPRTR)
724 trimmed = map(str.strip, split_k)
725 n_k = SEPRTR.join(trimmed)
726 id = attr_detailed.get(n_k, "")
727 attr['Id'] = id
728 attr.pop("DisplayName", None)
729 else:
730 id = attr.get('Id')
731 if id:
732 ex_val = attr_map.get(id, {})
733 if not ex_val:
734 rem_attrs.append(attr)
735 continue
736 if attr.get('Value') != ex_val.get("Value") or attr.get('IsIgnored') != ex_val.get("IsIgnored"):
737 diff = diff + 1
738 for rem in rem_attrs:
739 payload_attr.remove(rem)
740 # module.exit_json(attr_detailed=attr_detailed, inp_attr=disp_adv_list, payload_attr=payload_attr, adv_list=adv_list)
741 except Exception:
742 diff = 1
743 return diff
744
745
746 def get_create_payload(module, rest_obj, deviceid, view_id):
747 create_payload = {"Fqdds": "All",
748 "ViewTypeId": view_id}
749 attrib_dict = module.params.get("attributes").copy()
750 if isinstance(attrib_dict, dict):
751 typeid = attrib_dict.get("Type") if attrib_dict.get("Type") else attrib_dict.get("TypeId")
752 if typeid:
753 create_payload["TypeId"] = typeid
754 attrib_dict.pop("Type", None) # remove if exists as it is not required for create payload
755 create_payload.update(attrib_dict)
756 template = get_template_by_name(attrib_dict.get("Name"), module, rest_obj)
757 if template:
758 module.exit_json(msg=TEMPLATE_NAME_EXISTS.format(name=attrib_dict.get("Name")))
759 create_payload["SourceDeviceId"] = int(deviceid)
760 return create_payload
761
762
763 def get_modify_payload(module, rest_obj, template_dict):
764 modify_payload = {}
765 attrib_dict = module.params.get("attributes")
766 attrib_dict['Id'] = template_dict.get('Id')
767 modify_payload["Name"] = template_dict["Name"]
768 diff = 0
769 if attrib_dict.get("Name", template_dict["Name"]) != template_dict["Name"]:
770 template = get_template_by_name(attrib_dict.get("Name"), module, rest_obj)
771 if template:
772 module.exit_json(msg=TEMPLATE_NAME_EXISTS.format(name=attrib_dict.get("Name")))
773 modify_payload["Name"] = attrib_dict.get("Name")
774 diff = diff + 1
775 modify_payload["Description"] = template_dict["Description"]
776 diff = diff + apply_diff_key(attrib_dict, modify_payload, ["Description"])
777 # check attributes
778 if attrib_dict.get("Attributes"):
779 diff = diff + attributes_check(module, rest_obj, attrib_dict, template_dict.get('Id'))
780
781 if not diff:
782 module.exit_json(msg=NO_CHANGES_MSG)
783 if isinstance(attrib_dict, dict):
784 modify_payload.update(attrib_dict)
785 # module.exit_json(attrib_dict=attrib_dict, modify_payload=modify_payload)
786 return modify_payload
787
788
789 def get_deploy_payload(module_params, deviceidlist, template_id):
790 deploy_payload = {}
791 if isinstance(module_params.get("attributes"), dict):
792 deploy_payload.update(module_params.get("attributes"))
793 deploy_payload["Id"] = template_id
794 deploy_payload["TargetIds"] = deviceidlist
795 return deploy_payload
796
797
798 def get_import_payload(module, rest_obj, view_id):
799 attrib_dict = module.params.get("attributes").copy()
800 import_payload = {}
801 import_payload["Name"] = attrib_dict.pop("Name")
802 template = get_template_by_name(import_payload["Name"], module, rest_obj)
803 if template:
804 module.exit_json(msg=TEMPLATE_NAME_EXISTS.format(name=import_payload["Name"]))
805 import_payload["ViewTypeId"] = view_id
806 import_payload["Type"] = 2
807 typeid = attrib_dict.get("Type") if attrib_dict.get("Type") else attrib_dict.get("TypeId")
808 if typeid:
809 if get_type_id_valid(rest_obj, typeid):
810 import_payload["Type"] = typeid # Type is mandatory for import
811 else:
812 fail_module(module, msg="Type provided for 'import' operation is invalid")
813 import_payload["Content"] = attrib_dict.pop("Content")
814 if isinstance(attrib_dict, dict):
815 attrib_dict.pop("TypeId", None) # remove if exists as it is not required for import payload
816 import_payload.update(attrib_dict)
817 return import_payload
818
819
820 def get_clone_payload(module, rest_obj, template_id, view_id):
821 attrib_dict = module.params.get("attributes").copy()
822 clone_payload = {}
823 clone_payload["SourceTemplateId"] = template_id
824 clone_payload["NewTemplateName"] = attrib_dict.pop("Name")
825 template = get_template_by_name(clone_payload["NewTemplateName"], module, rest_obj)
826 if template:
827 module.exit_json(msg=TEMPLATE_NAME_EXISTS.format(name=clone_payload["NewTemplateName"]))
828 clone_payload["ViewTypeId"] = view_id
829 if isinstance(attrib_dict, dict):
830 clone_payload.update(attrib_dict)
831 return clone_payload
832
833
834 def get_template_by_id(module, rest_obj, template_id):
835 path = TEMPLATE_PATH.format(template_id=template_id)
836 template_req = rest_obj.invoke_request("GET", path)
837 if template_req.success:
838 return template_req.json_data
839 else:
840 fail_module(module, msg="Unable to complete the operation because the"
841 " requested template is not present.")
842
843
844 def get_template_details(module, rest_obj):
845 id = module.params.get('template_id')
846 query_param = {"$filter": "Id eq {0}".format(id)}
847 srch = 'Id'
848 if not id:
849 id = module.params.get('template_name')
850 query_param = {"$filter": "Name eq '{0}'".format(id)}
851 srch = 'Name'
852 template = {}
853 resp = rest_obj.invoke_request('GET', TEMPLATES_URI, query_param=query_param)
854 if resp.success and resp.json_data.get('value'):
855 tlist = resp.json_data.get('value', [])
856 for xtype in tlist:
857 if xtype.get(srch) == id:
858 template = xtype
859 return template
860
861
862 def _get_resource_parameters(module, rest_obj):
863 command = module.params.get("command")
864 rest_method = 'POST'
865 payload = {}
866 template = get_template_details(module, rest_obj)
867 template_id = template.get('Id')
868 # template_name = template.get('Name')
869 if command not in ["import", "create", "delete"] and not template:
870 fail_module(module, msg="Enter a valid template_name or template_id")
871 if command == "create":
872 devid_list = get_device_ids(module, rest_obj)
873 if len(devid_list) != 1:
874 fail_module(module, msg="Create template requires only one reference device")
875 view_id = get_view_id(rest_obj, module.params['template_view_type'])
876 payload = get_create_payload(module, rest_obj, devid_list[0], view_id)
877 path = TEMPLATES_URI
878 elif command == 'import':
879 view_id = get_view_id(rest_obj, module.params['template_view_type'])
880 path = TEMPLATE_ACTION.format(op="Import")
881 payload = get_import_payload(module, rest_obj, view_id)
882 elif command == "delete":
883 if not template:
884 module.exit_json(msg=NO_CHANGES_MSG)
885 path = TEMPLATE_PATH.format(template_id=template_id)
886 rest_method = 'DELETE'
887 elif command == "modify":
888 path = TEMPLATE_PATH.format(template_id=template_id)
889 template_dict = get_template_by_id(module, rest_obj, template_id)
890 payload = get_modify_payload(module, rest_obj, template_dict)
891 rest_method = 'PUT'
892 elif command == "export":
893 path = TEMPLATE_ACTION.format(op="Export")
894 payload = {'TemplateId': template_id}
895 elif command == "deploy":
896 devid_list = get_device_ids(module, rest_obj)
897 if not devid_list:
898 fail_module(module, msg="There are no devices provided for deploy operation")
899 profile_list = get_profiles(rest_obj)
900 dev_temp_map = {}
901 for prof in profile_list:
902 target = prof["TargetId"]
903 if prof["ProfileState"] > 0 and target in devid_list:
904 if template_id == prof['TemplateId']: # already same template deployed
905 devid_list.remove(target)
906 else:
907 dev_temp_map[prof["TargetId"]] = prof['TemplateId']
908 if dev_temp_map:
909 module.exit_json(devices_assigned=dev_temp_map,
910 msg=DEPLOY_DEV_ASSIGNED.format(dev=','.join(map(str, dev_temp_map.keys())),
911 temp=','.join(map(str, dev_temp_map.values()))))
912 if not devid_list:
913 module.exit_json(msg=NO_CHANGES_MSG)
914 path = TEMPLATE_ACTION.format(op="Deploy")
915 payload = get_deploy_payload(module.params, devid_list, template_id)
916 elif command == "clone":
917 view_id = get_view_id(rest_obj, module.params['template_view_type'])
918 path = TEMPLATE_ACTION.format(op="Clone")
919 payload = get_clone_payload(module, rest_obj, template_id, view_id)
920 if module.check_mode:
921 module.exit_json(msg=CHANGES_FOUND, changed=True)
922 return path, payload, rest_method
923
924
925 def _validate_inputs(module):
926 """validates input parameters"""
927 command = module.params.get("command")
928 if command in ["create", "deploy"]:
929 dev_id = module.params["device_id"]
930 dev_st = module.params["device_service_tag"]
931 if None in dev_id or None in dev_st:
932 fail_module(module, msg="Argument device_id or device_service_tag has null values")
933 attrib_dict = {}
934 if module.params.get("attributes"):
935 attrib_dict = module.params.get("attributes")
936 if command in ["import", "clone", "create"]:
937 if not attrib_dict.get("Name"):
938 fail_module(module, msg="Argument 'Name' required in attributes for {0} operation".format(command))
939 if command == "import":
940 if not attrib_dict.get("Content"):
941 fail_module(module, msg="Argument 'Content' required in attributes for {0} operation".format(command))
942
943
944 def password_no_log(attributes):
945 if isinstance(attributes, dict):
946 netdict = attributes.get("NetworkBootIsoModel")
947 if isinstance(netdict, dict):
948 sharedet = netdict.get("ShareDetail")
949 if isinstance(sharedet, dict) and 'Password' in sharedet:
950 sharedet['Password'] = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
951
952
953 def fail_module(module, **failmsg):
954 password_no_log(module.params.get("attributes"))
955 module.exit_json(**failmsg, failed=True)
956
957
958 def exit_module(rest_obj, module, response, time_out=False):
959 password_no_log(module.params.get("attributes"))
960 resp = None
961 changed_flag = True
962 command = module.params.get('command')
963 result = {}
964 if command in ["create", "modify", "deploy", "import", "clone"]:
965 result["return_id"] = response.json_data
966 resp = result["return_id"]
967 if command == 'deploy':
968 if time_out:
969 command = 'timed_out'
970 changed_flag = False
971 elif not result["return_id"]:
972 result["failed"] = True
973 command = 'deploy_fail'
974 changed_flag = False
975 elif module.params["job_wait"]:
976 command = 'deploy_when_job_wait_true'
977 else:
978 command = 'deploy_when_job_wait_false'
979 elif command == 'create':
980 if time_out:
981 resp = get_job_id(rest_obj, resp)
982 command = 'timed_out'
983 changed_flag = False
984 elif module.params["job_wait"]:
985 command = 'create_when_job_wait_true'
986 else:
987 time.sleep(5)
988 resp = get_job_id(rest_obj, resp)
989 command = 'create_when_job_wait_false'
990 if command == 'export':
991 changed_flag = False
992 result = response.json_data
993 message = MSG_DICT.get(command).format(resp)
994 module.exit_json(msg=message, changed=changed_flag, **result)
995
996
997 def get_job_id(rest_obj, template_id):
998 template = rest_obj.invoke_request("GET", TEMPLATE_PATH.format(template_id=template_id))
999 job_id = template.json_data.get("TaskId")
1000 return job_id
1001
1002
1003 def _resolve_job_id(rest_obj, resp, command, job_wait):
1004 if not job_wait:
1005 return None
1006 if command == "create":
1007 template_id = resp.json_data
1008 sleep_time = 5
1009 for _index in range(0, 30, sleep_time):
1010 try:
1011 job_id = get_job_id(rest_obj, template_id)
1012 except HTTPError:
1013 job_id = None
1014 if job_id:
1015 return job_id
1016 time.sleep(sleep_time)
1017 return None
1018 if command == "deploy":
1019 return resp.json_data
1020 return None
1021
1022
1023 def _track_job(rest_obj, module, resp, job_uri):
1024 try:
1025 job_failed, _unused1, job_dict, _unused2 = job_tracking(
1026 rest_obj, job_uri, max_job_wait_sec=module.params["job_wait_timeout"])
1027 except (URLError, SSLError, SSLValidationError, ConnectionError):
1028 # Handle job tracking timeouts gracefully
1029 exit_module(rest_obj, module, resp, True)
1030 return job_failed, job_dict
1031
1032
1033 def main():
1034 specs = {
1035 "command": {"required": False, "default": "create", "aliases": ['state'],
1036 "choices": ['create', 'modify', 'deploy', 'delete', 'export', 'import', 'clone']},
1037 "template_id": {"required": False, "type": 'int'},
1038 "template_name": {"required": False, "type": 'str'},
1039 "template_view_type": {"required": False, "default": 'Deployment',
1040 "choices": ['Deployment', 'Compliance', 'Inventory', 'Sample', 'None']},
1041 "device_id": {"required": False, "type": 'list', "default": [], "elements": 'int'},
1042 "device_service_tag": {"required": False, "type": 'list', "default": [], "elements": 'str'},
1043 "device_group_names": {"required": False, "type": 'list', "default": [], "elements": 'str'},
1044 "attributes": {"required": False, "type": 'dict'},
1045 "job_wait": {"required": False, "type": "bool", "default": True},
1046 "job_wait_timeout": {"required": False, "type": "int", "default": 1200}
1047 }
1048
1049 module = OmeAnsibleModule(
1050 argument_spec=specs,
1051 required_if=[
1052 ['command', 'create', ['attributes']],
1053 ['command', 'modify', ['attributes']],
1054 ['command', 'import', ['attributes']],
1055 ['command', 'modify', ['template_id', 'template_name'], True],
1056 ['command', 'delete', ['template_id', 'template_name'], True],
1057 ['command', 'export', ['template_id', 'template_name'], True],
1058 ['command', 'clone', ['template_id', 'template_name'], True],
1059 ['command', 'deploy', ['template_id', 'template_name'], True],
1060 ['command', 'deploy', ['device_id', 'device_service_tag', 'device_group_names'], True],
1061 ],
1062 mutually_exclusive=[["template_id", "template_name"]],
1063 supports_check_mode=True)
1064
1065 try:
1066 _validate_inputs(module)
1067 with RestOME(module.params, req_session=True) as rest_obj:
1068 path, payload, rest_method = _get_resource_parameters(module, rest_obj)
1069 resp = rest_obj.invoke_request(rest_method, path, data=payload)
1070 command = module.params["command"]
1071 job_wait = module.params["job_wait"]
1072 job_id = _resolve_job_id(rest_obj, resp, command, job_wait)
1073 if job_id:
1074 job_uri = JOB_URI.format(job_id=job_id)
1075 job_failed, job_dict = _track_job(rest_obj, module, resp, job_uri)
1076 if job_failed and job_dict.get('LastRunStatus', {}).get('Name') == "Running":
1077 exit_module(rest_obj, module, resp, True)
1078 elif job_failed:
1079 module.exit_json(msg=MSG_DICT.get('fail').format(command=command), failed=True)
1080 if resp.success:
1081 exit_module(rest_obj, module, resp)
1082 except HTTPError as err:
1083 module.exit_json(msg=str(err), failed=True)
1084 except URLError as err:
1085 password_no_log(module.params.get("attributes"))
1086 module.exit_json(msg=str(err), unreachable=True)
1087 except (IOError, SSLError, SSLValidationError, ConnectionError, TypeError, ValueError, KeyError, OSError) as err:
1088 module.exit_json(msg=str(err), failed=True)
1089
1090
1091 if __name__ == '__main__':
1092 main()