Debian Codegraph @

ansible_collections/cisco/intersight/plugins/module_utils/intersight.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # (c) 2016 Red Hat Inc.
8 # (c) 2020 Cisco Systems Inc.
9 #
10 # Redistribution and use in source and binary forms, with or without modification,
11 # are permitted provided that the following conditions are met:
12 #
13 # * Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # * Redistributions in binary form must reproduce the above copyright notice,
16 # this list of conditions and the following disclaimer in the documentation
17 # and/or other materials provided with the distribution.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #
29 # Intersight REST API Module
30 # Author: Matthew Garrett
31 # Contributors: David Soper, Chris Gascoigne, John McDonough
32
33 from __future__ import (absolute_import, division, print_function)
34
35 __metaclass__ = type
36
37 from base64 import b64encode
38 from email.utils import formatdate
39 import re
40 import json
41 import hashlib
42 from typing import Optional
43
44 from ansible.module_utils.six import iteritems
45 from ansible.module_utils.six.moves.urllib.parse import urlparse, urlencode
46 from ansible.module_utils.urls import fetch_url
47 from ansible.module_utils.basic import env_fallback
48
49 try:
50 from cryptography.hazmat.primitives import serialization, hashes
51 from cryptography.hazmat.primitives.asymmetric import padding, ec, rsa
52 from cryptography.hazmat.backends import default_backend
53
54 HAS_CRYPTOGRAPHY = True
55 except ImportError:
56 HAS_CRYPTOGRAPHY = False
57
58 intersight_argument_spec = dict(
59 api_private_key=dict(fallback=(env_fallback, ['INTERSIGHT_API_PRIVATE_KEY']), type='path', required=True,
60 no_log=True),
61 api_uri=dict(fallback=(env_fallback, ['INTERSIGHT_API_URI']), type='str', default='https://intersight.com/api/v1'),
62 api_key_id=dict(fallback=(env_fallback, ['INTERSIGHT_API_KEY_ID']), type='str', required=True),
63 validate_certs=dict(type='bool', default=True),
64 use_proxy=dict(type='bool', default=True),
65 )
66
67
68 def get_sha256_digest(data):
69 """
70 Generates a SHA256 digest from a String.
71
72 :param data: data string set by user
73 :return: instance of digest object
74 """
75
76 digest = hashlib.sha256()
77 digest.update(data.encode())
78
79 return digest
80
81
82 def prepare_str_to_sign(req_tgt, hdrs):
83 """
84 Concatenates Intersight headers in preparation to be signed
85
86 :param req_tgt : http method plus endpoint
87 :param hdrs: dict with header keys
88 :return: concatenated header authorization string
89 """
90 ss = ""
91 ss = ss + "(request-target): " + req_tgt + "\n"
92
93 length = len(hdrs.items())
94
95 i = 0
96 for key, value in hdrs.items():
97 ss = ss + key.lower() + ": " + value
98 if i < length - 1:
99 ss = ss + "\n"
100 i += 1
101
102 return ss
103
104
105 def get_gmt_date():
106 """
107 Generated a GMT formatted Date
108
109 :return: current date
110 """
111
112 return formatdate(timeval=None, localtime=False, usegmt=True)
113
114
115 def compare_lists(expected_list, actual_list):
116 if len(expected_list) != len(actual_list):
117 # mismatch if list lengths aren't equal
118 return False
119 for expected, actual in zip(expected_list, actual_list):
120 # if compare_values returns False, stop the loop and return
121 if not compare_values(expected, actual):
122 return False
123 # loop complete with all items matching
124 return True
125
126
127 def compare_values(expected, actual):
128 try:
129 if isinstance(expected, list) and isinstance(actual, list):
130 return compare_lists(expected, actual)
131 for (key, value) in iteritems(expected):
132 if re.search(r'P(ass)?w(or)?d', key) or re.search(r'OctetString', key) or re.search(r'IsOctetStringSet', key) or key not in actual:
133 # do not compare any password related attributes, OctetString (secrets), IsOctetStringSet, or attributes that are not in the actual resource
134 continue
135 # Special handling for SecKeys comparison
136 if key == 'SecKeys':
137 expected_empty = value is None or value == []
138 actual_value = actual.get(key)
139 actual_empty = actual_value is None or actual_value == [] or actual_value == ''
140 if expected_empty and actual_empty:
141 continue # Both are "empty", consider them equal
142 # If SecKeys has content, skip deep comparison (contains secrets we can't compare)
143 # Just verify both have content
144 if not expected_empty and not actual_empty:
145 continue # Both have keys, consider them equal (can't compare secrets)
146 if not compare_values(value, actual[key]):
147 return False
148 # loop complete with all items matching
149 return True
150 except (AttributeError, TypeError):
151 # Handle Intersight object references: when expected is a MOID string and actual is an object reference
152 if (isinstance(expected, str) and isinstance(actual, dict) and 'Moid' in actual and actual.get('ClassId') == 'mo.MoRef'):
153 # Compare the MOID string against the Moid field in the object reference
154 if actual['Moid'] == expected:
155 return True
156 # Handle case where expected is a string and actual is an object reference
157 elif (isinstance(expected, str) and isinstance(actual, dict) and
158 'Name' in actual and actual.get('ObjectType') == 'organization.Organization'):
159 if actual['Name'] == expected:
160 return True
161 # if expected and actual != expected:
162 if actual != expected:
163 return False
164 return True
165
166
167 # This will fix the format of a v3 secret key, if needed.
168 # Some v3 keys PEM files are incorrectly formatted with
169 # "BEGIN EC PRIVATE KEY" instead of "BEGIN PRIVATE KEY"
170 def _fix_v3_key_format(secret_key: bytes):
171 return secret_key.replace(
172 b"-----BEGIN EC PRIVATE KEY-----", b"-----BEGIN PRIVATE KEY-----"
173 ).replace(b"-----END EC PRIVATE KEY-----", b"-----END PRIVATE KEY-----")
174
175
176 class IntersightModule():
177
178 def __init__(self, module):
179 self.module = module
180 self.result = dict(changed=False)
181 if not HAS_CRYPTOGRAPHY:
182 self.module.fail_json(msg='cryptography is required for this module')
183 self.host = self.module.params['api_uri']
184 self.public_key = self.module.params['api_key_id']
185 try:
186 with open(self.module.params['api_private_key'], 'r') as f:
187 self.private_key = f.read()
188 except (FileNotFoundError, OSError):
189 self.private_key = self.module.params['api_private_key']
190 self.digest_algorithm = ''
191 self.response_list = []
192 self.update_method = ''
193
194 def get_sig_b64encode(self, data):
195 """
196 Generates a signed digest from a String
197
198 :param digest: string to be signed & hashed
199 :return: instance of digest object
200 """
201 try:
202 key = serialization.load_pem_private_key(self.private_key.encode(), None, default_backend())
203 except (ValueError):
204 key = serialization.load_pem_private_key(_fix_v3_key_format(self.private_key.encode()), None, default_backend())
205
206 if isinstance(key, rsa.RSAPrivateKey):
207 sign = key.sign(data.encode(), padding.PKCS1v15(), hashes.SHA256())
208 self.digest_algorithm = 'rsa-sha256'
209 elif isinstance(key, ec.EllipticCurvePrivateKey):
210 sign = key.sign(data.encode(), ec.ECDSA(hashes.SHA256()))
211 self.digest_algorithm = 'hs2019'
212 else:
213 raise Exception("Unsupported key: {0}".format(type(key).__name__))
214
215 return b64encode(sign)
216
217 def get_auth_header(self, hdrs, signed_msg):
218 """
219 Assmebled an Intersight formatted authorization header
220
221 :param hdrs : object with header keys
222 :param signed_msg: base64 encoded sha256 hashed body
223 :return: concatenated authorization header
224 """
225
226 auth_str = "Signature"
227
228 auth_str = auth_str + " " + "keyId=\"" + self.public_key + "\"," + "algorithm=\"" + self.digest_algorithm + "\","
229
230 auth_str = auth_str + "headers=\"(request-target)"
231
232 for key, dummy in hdrs.items():
233 auth_str = auth_str + " " + key.lower()
234 auth_str = auth_str + "\""
235
236 auth_str = auth_str + "," + "signature=\"" + signed_msg.decode('ascii') + "\""
237
238 return auth_str
239
240 def call_api(self, **options):
241 """
242 Call the Intersight API and check for success status
243 :param options: options dict with method and other params for API call
244 :return: json http response object
245 """
246
247 try:
248 response, info = self.intersight_call(**options)
249 if not re.match(r'2..', str(info['status'])):
250 raise RuntimeError(info.get('status'), info.get('msg'), info.get('body', info))
251 except Exception as e:
252 self.module.fail_json(msg="Code exception: %s " % str(e))
253
254 response_data = response.read()
255 if len(response_data) > 0:
256 resp_json = json.loads(response_data)
257 resp_json['trace_id'] = info.get('x-starship-traceid')
258 return resp_json
259 return {}
260
261 def intersight_call(self, http_method="", resource_path="", query_params=None, body=None, moid=None, name=None):
262 """
263 Invoke the Intersight API
264
265 :param resource_path: intersight resource path e.g. '/ntp/Policies'
266 :param query_params: dictionary object with query string parameters as key/value pairs
267 :param body: dictionary object with intersight data
268 :param moid: intersight object moid
269 :param name: intersight object name
270 :return: json http response object
271 """
272
273 target_host = urlparse(self.host).netloc
274 target_path = urlparse(self.host).path
275 query_path = ""
276 method = http_method.upper()
277 bodyString = ""
278
279 # Verify an accepted HTTP verb was chosen
280 if (method not in ['GET', 'POST', 'PATCH', 'DELETE']):
281 raise ValueError('Please select a valid HTTP verb (GET/POST/PATCH/DELETE)')
282
283 # Verify the resource path isn't empy & is a valid <str> object
284 if (resource_path != "" and not (resource_path, str)):
285 raise TypeError('The *resource_path* value is required and must be of type "<str>"')
286
287 # Verify the query parameters isn't empy & is a valid <dict> object
288 if (query_params is not None and not isinstance(query_params, dict)):
289 raise TypeError('The *query_params* value must be of type "<dict>"')
290
291 # Verify the MOID is not null & of proper length
292 if (moid is not None and len(moid.encode('utf-8')) != 24):
293 raise ValueError('Invalid *moid* value!')
294
295 if (method != 'PATCH' and self.update_method == 'json-patch'):
296 raise ValueError('json-patch is only supported with PATCH on existing resource')
297
298 # Check for query_params, encode, and concatenate onto URL
299 if query_params:
300 query_path = "?" + urlencode(query_params)
301
302 # Handle PATCH/DELETE by Object "name" instead of "moid"
303 if method in ('PATCH', 'DELETE'):
304 if moid is None:
305 if name is not None:
306 if isinstance(name, str):
307 moid = self.get_moid_by_name(resource_path, name)
308 else:
309 raise TypeError('The *name* value must be of type "<str>"')
310 else:
311 raise ValueError('Must set either *moid* or *name* with "PATCH/DELETE!"')
312
313 # Check for moid and concatenate onto URL
314 if moid is not None:
315 resource_path += "/" + moid
316
317 # Check for GET request to properly form body
318 if method != "GET":
319 bodyString = json.dumps(body)
320
321 # Concatenate URLs for headers
322 target_url = self.host + resource_path + query_path
323 request_target = method.lower() + " " + target_path + resource_path + query_path
324
325 # Get the current GMT Date/Time
326 cdate = get_gmt_date()
327
328 # Generate the body digest
329 body_digest = get_sha256_digest(bodyString)
330 b64_body_digest = b64encode(body_digest.digest())
331
332 # Generate the authorization header
333 auth_header = {
334 'Host': target_host,
335 'Date': cdate,
336 'Digest': "SHA-256=" + b64_body_digest.decode('ascii'),
337 }
338
339 string_to_sign = prepare_str_to_sign(request_target, auth_header)
340 b64_signed_msg = self.get_sig_b64encode(string_to_sign)
341 auth_header = self.get_auth_header(auth_header, b64_signed_msg)
342
343 # Generate the HTTP requests header
344 if self.update_method == 'json-patch':
345 content_type = 'application/json-patch+json'
346 else:
347 content_type = 'application/json'
348 request_header = {
349 'Accept': 'application/json',
350 'Content-Type': content_type,
351 'Host': '{0}'.format(target_host),
352 'Date': '{0}'.format(cdate),
353 'Digest': 'SHA-256={0}'.format(b64_body_digest.decode('ascii')),
354 'Authorization': '{0}'.format(auth_header),
355 }
356
357 response, info = fetch_url(self.module, target_url, data=bodyString, headers=request_header, method=method,
358 use_proxy=self.module.params['use_proxy'])
359
360 return response, info
361
362 def get_resource(self, resource_path, query_params, return_list=False):
363 '''
364 GET a resource and return the 1st element found or the full Results list
365 If return_list is False and more than 1 element is returned, a warning is raised
366 '''
367
368 if query_params is None:
369 query_params = {}
370 # Handle pagination, default return list consists of 100 elements.
371 if return_list and '$top' not in query_params:
372 query_params['$top'] = 1000
373 options = {
374 'http_method': 'get',
375 'resource_path': resource_path,
376 'query_params': query_params,
377 }
378 response = self.call_api(**options)
379 if response.get('Results'):
380 if return_list:
381 self.result['api_response'] = response['Results']
382 else:
383 if len(response['Results']) > 1:
384 self.module.warn('More than 1 resource found, returning the 1st one')
385 # return the 1st list element
386 self.result['api_response'] = response['Results'][0]
387 else:
388 # Return a dict if no Results array (handles case where resource_path contains a Moid)
389 if isinstance(response, dict):
390 self.result['api_response'] = response
391 else:
392 # Clear api_response when no results found to prevent returning stale data
393 if return_list:
394 self.result['api_response'] = []
395 else:
396 self.result['api_response'] = {}
397 self.result['count'] = response.get('Count', 0)
398 self.result['trace_id'] = response.get('trace_id')
399
400 def configure_resource(self, moid, resource_path, body, query_params, update_method=''):
401 self.update_method = update_method
402 if not self.module.check_mode:
403 if moid and update_method != 'post':
404 # update the resource - user has to specify all the props they want updated
405 options = {
406 'http_method': 'patch',
407 'resource_path': resource_path,
408 'body': body,
409 'moid': moid,
410 }
411 response_dict = self.call_api(**options)
412 if response_dict.get('Results'):
413 # return the 1st element in the results list
414 self.result['api_response'] = response_dict['Results'][0]
415 self.result['trace_id'] = response_dict.get('trace_id')
416 elif response_dict and 'Moid' in response_dict:
417 # PATCH returned the updated object directly (not in Results array)
418 self.result['api_response'] = response_dict
419 self.result['trace_id'] = response_dict.get('trace_id')
420 else:
421 # create the resource
422 options = {
423 'http_method': 'post',
424 'resource_path': resource_path,
425 'body': body,
426 }
427 response_dict = self.call_api(**options)
428 if response_dict:
429 self.result['api_response'] = response_dict
430 self.result['trace_id'] = response_dict.get('trace_id')
431 elif query_params:
432 # POSTs may not return any data.
433 # Get the current state of the resource if query_params.
434 self.get_resource(
435 resource_path=resource_path,
436 query_params=query_params,
437 )
438 else:
439 # In check mode, clear api_response to indicate no actual action was taken
440 self.result['api_response'] = {}
441 self.result['changed'] = True
442
443 def delete_resource(self, moid, resource_path):
444 # delete resource and create empty api_response
445 if not self.module.check_mode:
446 options = {
447 'http_method': 'delete',
448 'resource_path': resource_path,
449 'moid': moid,
450 }
451 resp = self.call_api(**options)
452 self.result['api_response'] = {}
453 self.result['trace_id'] = resp.get('trace_id')
454 self.result['changed'] = True
455
456 def configure_policy_or_profile(self, resource_path, filter_key=None, filter_value=None):
457 # Configure (create, update, or delete) the policy or profile
458 organization_name = self.module.params['organization']
459 organization_moid = self.get_moid_by_name(resource_path='/organization/Organizations', resource_name=organization_name)
460
461 if organization_moid is None:
462 self.module.fail_json(
463 msg=f"Organization '{organization_name}' not found. Please verify the organization name exists in Intersight and that you have access to it."
464 )
465
466 self.result['api_response'] = {}
467 # Get the current state of the resource
468 filter_str = "Name eq '" + self.module.params['name'] + "'"
469 if filter_value and filter_key:
470 filter_str += " and " + filter_key + " eq '" + filter_value + "'"
471 filter_str += " and Organization.Moid eq '" + organization_moid + "'"
472 self.get_resource(
473 resource_path=resource_path,
474 query_params={
475 '$filter': filter_str,
476 '$expand': 'Organization',
477 }
478 )
479
480 moid = None
481 resource_values_match = False
482 if self.result['api_response'].get('Moid'):
483 # resource exists and moid was returned
484 moid = self.result['api_response']['Moid']
485 if self.module.params['state'] == 'present':
486 resource_values_match = compare_values(self.api_body, self.result['api_response'])
487 else: # state == 'absent'
488 self.delete_resource(
489 moid=moid,
490 resource_path=resource_path,
491 )
492 moid = None
493
494 if self.module.params['state'] == 'present' and not resource_values_match:
495 # remove read-only Organization key
496 self.api_body.pop('Organization')
497 if not moid:
498 # Organization must be set, but can't be changed after initial POST
499 self.api_body['Organization'] = {
500 'Moid': organization_moid,
501 }
502 self.configure_resource(
503 moid=moid,
504 resource_path=resource_path,
505 body=self.api_body,
506 query_params={
507 '$filter': filter_str
508 }
509 )
510 if self.result['api_response'].get('Moid'):
511 # resource exists and moid was returned
512 moid = self.result['api_response']['Moid']
513
514 return moid
515
516 def configure_secondary_resource(self, resource_path, resource_name=None, state='present', custom_filter=None):
517 # Configure (create, update, or delete) resources
518 # This method is used to configure secondery resources that are part of a policy or profile (e.g. VLANs)
519
520 self.result['api_response'] = {}
521 # Get the current state of the resource
522 if custom_filter:
523 filter_str = custom_filter
524 elif resource_name:
525 filter_str = "Name eq '" + resource_name + "'"
526 else:
527 raise ValueError("Either resource_name or custom_filter must be provided")
528 self.get_resource(
529 resource_path=resource_path,
530 query_params={
531 '$filter': filter_str
532 }
533 )
534
535 moid = None
536 resource_values_match = False
537 if self.result['api_response'].get('Moid'):
538 # resource exists and moid was returned
539 moid = self.result['api_response']['Moid']
540 if state == 'present':
541 resource_values_match = compare_values(self.api_body, self.result['api_response'])
542 else: # state == 'absent'
543 self.delete_resource(
544 moid=moid,
545 resource_path=resource_path,
546 )
547 moid = None
548
549 if state == 'present' and not resource_values_match:
550 self.configure_resource(
551 moid=moid,
552 resource_path=resource_path,
553 body=self.api_body,
554 query_params={
555 '$filter': filter_str
556 }
557 )
558 if self.result['api_response'].get('Moid'):
559 # resource exists and moid was returned
560 moid = self.result['api_response']['Moid']
561
562 return moid
563
564 def get_moid_by_name(self, resource_path, resource_name) -> Optional[str]:
565 '''
566 Get the moid of the resource by the value of the resource
567 '''
568 organization_moid = None
569 # GET Moid of the resource
570 self.get_resource(
571 resource_path=resource_path,
572 query_params={
573 '$filter': "Name eq '" + resource_name + "'",
574 '$select': 'Moid',
575 },
576 )
577 if self.result['api_response'].get('Moid'):
578 # resource exists and moid was returned
579 return self.result['api_response']['Moid']
580 return None
581
582 def get_moid_by_name_and_org(self, resource_path, resource_name, organization_name) -> Optional[str]:
583 '''
584 Get the moid of an organization-scoped resource by name and organization.
585
586 This function is used for resources that belong to a specific organization
587 to avoid conflicts when multiple organizations have resources with the same name.
588 '''
589 # Get the organization MOID
590 org_moid = self.get_moid_by_name(
591 resource_path='/organization/Organizations',
592 resource_name=organization_name
593 )
594
595 if not org_moid:
596 self.module.fail_json(msg=f"Organization '{organization_name}' not found")
597
598 # Build filter with both name and organization
599 filter_str = f"Name eq '{resource_name}' and Organization.Moid eq '{org_moid}'"
600
601 # GET Moid of the resource
602 self.get_resource(
603 resource_path=resource_path,
604 query_params={
605 '$filter': filter_str,
606 '$select': 'Moid',
607 },
608 )
609
610 if self.result['api_response'].get('Moid'):
611 # resource exists and moid was returned
612 return self.result['api_response']['Moid']
613 return None
614
615 def set_query_params(self, filter_key=None, filter_value=None) -> dict:
616 filter_conditions = []
617 name_to_filter = self.module.params.get('name')
618 org_to_filter = self.module.params.get('organization')
619 if name_to_filter:
620 filter_conditions.append(f"Name eq '{name_to_filter}'")
621
622 if org_to_filter:
623 org_moid = self.get_moid_by_name(resource_path='/organization/Organizations', resource_name=org_to_filter)
624 filter_conditions.append(f"Organization.Moid eq '{org_moid}'")
625
626 if filter_value and filter_key:
627 filter_conditions.append(f"{filter_key} eq '{filter_value}'")
628
629 query_params = {}
630 if filter_conditions:
631 query_params["$filter"] = " and ".join(filter_conditions)
632 return query_params
633
634 def set_tags_and_description(self):
635 """
636 Generalize the pattern of setting tags and description in api_body if they are provided in module params.
637 """
638 if self.module.params.get('tags'):
639 self.api_body['Tags'] = self.module.params['tags']
640 if self.module.params.get('description'):
641 self.api_body['Description'] = self.module.params['description']
642
643 def execute_bulk_operations(self, resource_path, operations_dict, changed_states):
644 """
645 Execute bulk operations (POST, PATCH, DELETE) and track results.
646
647 This is a generic method to execute categorized bulk operations and collect results.
648 It handles all three operation types and properly tracks changed states.
649 Order of operations does not affect the final changed state - any operation that
650 makes changes will result in changed=True at the end.
651
652 Args:
653 resource_path: API resource path (e.g., '/fabric/Vlans')
654 operations_dict: Dictionary with keys 'create', 'update', 'delete', each containing
655 a list of operation data dicts
656 changed_states: List to append changed state to after each operation
657
658 Returns:
659 List of all operation results from create and update operations
660 """
661 all_results = []
662
663 # Execute bulk CREATE operations
664 if operations_dict.get('create'):
665 # Reset changed flag before operation to ensure clean state tracking
666 self.result['changed'] = False
667 create_results = self.configure_bulk_resources(
668 resource_path=resource_path,
669 resources_data=operations_dict['create'],
670 http_method='post'
671 )
672 all_results.extend(create_results)
673 # Track if this operation made changes
674 changed_states.append(self.result['changed'])
675
676 # Execute bulk UPDATE operations
677 if operations_dict.get('update'):
678 # Reset changed flag before operation to ensure clean state tracking
679 self.result['changed'] = False
680 update_results = self.configure_bulk_resources(
681 resource_path=resource_path,
682 resources_data=operations_dict['update'],
683 http_method='patch'
684 )
685 all_results.extend(update_results)
686 # Track if this operation made changes
687 changed_states.append(self.result['changed'])
688
689 # Execute bulk DELETE operations
690 if operations_dict.get('delete'):
691 # Reset changed flag before operation to ensure clean state tracking
692 self.result['changed'] = False
693 self.configure_bulk_resources(
694 resource_path=resource_path,
695 resources_data=operations_dict['delete'],
696 http_method='delete'
697 )
698 # Track if this operation made changes (no results to return for deletes)
699 changed_states.append(self.result['changed'])
700
701 return all_results
702
703 def configure_bulk_resources(self, resource_path, resources_data, http_method='post'):
704 """
705 Configure multiple resources in bulk operations with automatic chunking.
706
707 This method uses the Intersight bulk API endpoint to create, update, or delete multiple
708 resources. It automatically splits large operations into chunks of 100 requests (Intersight API limit)
709 and processes them sequentially.
710
711 Args:
712 resource_path: API resource path (e.g., '/fabric/Vlans')
713 resources_data: List of dicts, each containing:
714 - 'body': Resource API body (required for POST/PATCH)
715 - 'moid': Resource MOID (required for PATCH/DELETE)
716 - 'filter': Filter string to check existence (optional)
717 - 'name': Resource name for identification (optional)
718 http_method: 'post' for create, 'patch' for update, or 'delete' for delete operations
719
720 Returns:
721 List of API response objects for each resource in the bulk operation
722
723 Raises:
724 ValueError: If http_method is not 'post', 'patch', or 'delete'
725 """
726 if http_method.lower() not in ['post', 'patch', 'delete']:
727 raise ValueError("Bulk operations only support 'post' (create), 'patch' (update), and 'delete' methods")
728
729 if not resources_data:
730 return []
731
732 # Intersight API limit: maximum 100 requests per bulk operation
733 BULK_CHUNK_SIZE = 100
734 bulk_results = []
735
736 # Split resources_data into chunks of 100
737 for chunk_start in range(0, len(resources_data), BULK_CHUNK_SIZE):
738 # Prevent index out of range error
739 chunk_end = min(chunk_start + BULK_CHUNK_SIZE, len(resources_data))
740 # Get the chunk of resources data
741 chunk_data = resources_data[chunk_start:chunk_end]
742
743 # Process this chunk based on HTTP method
744 if http_method.lower() == 'post':
745 chunk_results = self._process_bulk_post_chunk(resource_path, chunk_data)
746 elif http_method.lower() == 'patch':
747 chunk_results = self._process_bulk_patch_chunk(resource_path, chunk_data)
748 elif http_method.lower() == 'delete':
749 chunk_results = self._process_bulk_delete_chunk(resource_path, chunk_data)
750
751 bulk_results.extend(chunk_results)
752
753 return bulk_results
754
755 def _process_bulk_response(self, response, chunk_data, operation_type, success_statuses=None):
756 """
757 Process bulk API response and collect failures.
758
759 Args:
760 response: API response dictionary
761 chunk_data: Original chunk data for resource identification
762 operation_type: Type of operation (POST, PATCH, DELETE)
763 success_statuses: List of HTTP status codes considered successful (defaults to [200])
764
765 Returns:
766 List of bulk operation results
767 """
768 if success_statuses is None:
769 success_statuses = [200]
770
771 bulk_results = []
772 failed_count = 0
773 failure_messages = []
774
775 if response.get('Results'):
776 for idx, result in enumerate(response['Results']):
777 if result.get('Status') in success_statuses:
778 bulk_results.append(result.get('Body', {}))
779 else:
780 failed_count += 1
781 error_body = result.get('Body', {})
782 error_msg = error_body.get('Message', error_body.get('message', 'Unknown error'))
783 resource_name = chunk_data[idx].get('name', f'resource {idx}')
784 failure_msg = f" - {resource_name}: {error_msg}"
785 if failure_msg not in failure_messages:
786 failure_messages.append(failure_msg)
787 bulk_results.append({})
788
789 # Handle any failures
790 self._handle_bulk_failures(failed_count, len(response['Results']), failure_messages, operation_type)
791 else:
792 # If no Results, return empty results for each item
793 bulk_results = [{}] * len(chunk_data)
794
795 return bulk_results
796
797 def _handle_bulk_failures(self, failed_count, total_count, failure_messages, operation_type):
798 """
799 Handle bulk operation failures with consistent error reporting.
800
801 Args:
802 failed_count: Number of failed operations
803 total_count: Total number of operations attempted
804 failure_messages: List of error messages
805 operation_type: Type of operation (POST, PATCH, DELETE)
806 """
807 if failed_count > 0:
808 error_summary = "\n".join(failure_messages[:10]) # Show up to 10 errors
809 self.module.fail_json(
810 msg=f"Bulk {operation_type} operation failed: {failed_count}/{total_count} resources failed. "
811 f"Errors:\n{error_summary}"
812 )
813
814 def _process_bulk_post_chunk(self, resource_path, chunk_data):
815 """
816 Process a chunk of POST (create) operations.
817
818 Args:
819 resource_path: API resource path
820 chunk_data: List of resources to create (max 100 items)
821
822 Returns:
823 List of API response objects for created resources
824 """
825 bulk_results = []
826
827 # Build bulk request body
828 bulk_requests = []
829 for resource_data in chunk_data:
830 bulk_requests.append({
831 'ObjectType': 'bulk.RestSubRequest',
832 'Body': resource_data['body']
833 })
834
835 bulk_body = {
836 'Verb': 'POST',
837 'Uri': f'/v1{resource_path}',
838 'Requests': bulk_requests
839 }
840
841 if not self.module.check_mode:
842 # Make bulk API call
843 options = {
844 'http_method': 'post',
845 'resource_path': '/bulk/Requests',
846 'body': bulk_body
847 }
848 response = self.call_api(**options)
849 bulk_results = self._process_bulk_response(response, chunk_data, 'POST')
850 else:
851 # In check mode, return empty results
852 bulk_results = [{}] * len(chunk_data)
853
854 self.result['changed'] = True
855 return bulk_results
856
857 def _process_bulk_patch_chunk(self, resource_path, chunk_data):
858 """
859 Process a chunk of PATCH (update) operations.
860
861 Args:
862 resource_path: API resource path
863 chunk_data: List of resources to update (max 100 items)
864
865 Returns:
866 List of API response objects for updated resources
867 """
868 bulk_results = []
869
870 # Build bulk request body
871 bulk_requests = []
872 for resource_data in chunk_data:
873 if 'moid' in resource_data and resource_data['moid']:
874 bulk_requests.append({
875 'ObjectType': 'bulk.RestSubRequest',
876 'TargetMoid': resource_data['moid'],
877 'Body': resource_data['body']
878 })
879
880 if bulk_requests:
881 bulk_body = {
882 'Verb': 'PATCH',
883 'Uri': f'/v1{resource_path}',
884 'Requests': bulk_requests
885 }
886
887 if not self.module.check_mode:
888 # Make bulk API call
889 options = {
890 'http_method': 'post',
891 'resource_path': '/bulk/Requests',
892 'body': bulk_body
893 }
894 response = self.call_api(**options)
895 bulk_results = self._process_bulk_response(response, chunk_data, 'PATCH')
896 else:
897 # In check mode, return empty results
898 bulk_results = [{}] * len(bulk_requests)
899
900 self.result['changed'] = True
901
902 return bulk_results
903
904 def _process_bulk_delete_chunk(self, resource_path, chunk_data):
905 """
906 Process a chunk of DELETE operations.
907
908 Args:
909 resource_path: API resource path
910 chunk_data: List of resources to delete (max 100 items)
911
912 Returns:
913 List of empty dicts (delete operations don't return data)
914 """
915 bulk_results = []
916
917 # Build bulk request body
918 bulk_requests = []
919 for resource_data in chunk_data:
920 if 'moid' in resource_data and resource_data['moid']:
921 sub_request = {
922 'ObjectType': 'bulk.RestSubRequest',
923 'TargetMoid': resource_data['moid']
924 }
925 # Include any additional fields from resource_data (e.g., VlanId for VLANs)
926 if 'body' in resource_data and resource_data['body']:
927 sub_request.update(resource_data['body'])
928 bulk_requests.append(sub_request)
929
930 if bulk_requests:
931 bulk_body = {
932 'Verb': 'DELETE',
933 'Uri': f'/v1{resource_path}',
934 'Requests': bulk_requests
935 }
936
937 if not self.module.check_mode:
938 # Make bulk API call
939 options = {
940 'http_method': 'post',
941 'resource_path': '/bulk/Requests',
942 'body': bulk_body
943 }
944 response = self.call_api(**options)
945 bulk_results = self._process_bulk_response(response, chunk_data, 'DELETE', success_statuses=[200, 204])
946 else:
947 # In check mode, return empty results
948 bulk_results = [{}] * len(bulk_requests)
949
950 self.result['changed'] = True
951
952 return bulk_results
953
954
955 def resolve_policy_bucket(intersight, organization_name, policy_mapping):
956 """Resolve policy names to MOIDs and build the PolicyBucket list.
957
958 Args:
959 intersight: IntersightModule instance.
960 organization_name: Organization to scope the policy lookup.
961 policy_mapping: Dict mapping module param names to resource_path/object_type.
962 """
963 policy_bucket = []
964 for param_name, mapping in policy_mapping.items():
965 policy_name = intersight.module.params.get(param_name)
966 if policy_name:
967 moid = intersight.get_moid_by_name_and_org(
968 resource_path=mapping['resource_path'],
969 resource_name=policy_name,
970 organization_name=organization_name,
971 )
972 if not moid:
973 intersight.module.fail_json(
974 msg=f"Policy '{policy_name}' ({param_name}) not found in organization '{organization_name}'"
975 )
976 policy_bucket.append({
977 'Moid': moid,
978 'ObjectType': mapping['object_type'],
979 })
980 return policy_bucket
981
982
983 def sync_policy_bucket(intersight, bucket_path, desired_bucket, current_bucket):
984 """Sync the PolicyBucket via the sub-resource endpoint using differential add/delete.
985
986 Args:
987 intersight: IntersightModule instance.
988 bucket_path: Full API sub-resource path (e.g. /chassis/Profiles/{moid}/PolicyBucket).
989 desired_bucket: List of policy dicts representing the desired state.
990 current_bucket: List of policy dicts representing the current state.
991 """
992 current_set = {(p['Moid'], p['ObjectType']) for p in current_bucket}
993 desired_set = {(p['Moid'], p['ObjectType']) for p in desired_bucket}
994
995 if current_set == desired_set:
996 return
997
998 to_remove = current_set - desired_set
999 for policy_moid, obj_type in to_remove:
1000 intersight.delete_resource(
1001 moid=policy_moid,
1002 resource_path=bucket_path,
1003 )
1004
1005 to_add = desired_set - current_set
1006 if to_add:
1007 add_body = [{'Moid': m, 'ObjectType': t} for m, t in to_add]
1008 intersight.configure_resource(
1009 moid=None,
1010 resource_path=bucket_path,
1011 body=add_body,
1012 query_params={},
1013 )