Debian Codegraph @

ansible_collections/infoblox/nios_modules/plugins/module_utils/api.py

raw symbols SCIP
1 from __future__ import (absolute_import, division, print_function)
2 __metaclass__ = type
3 # This code is part of Ansible, but is an independent component.
4 # This particular file snippet, and this file snippet only, is BSD licensed.
5 # Modules you write using this snippet, which is embedded dynamically by Ansible
6 # still belong to the author of the module, and may assign their own license
7 # to the complete work.
8 #
9 # Copyright © 2020 Infoblox Inc
10 #
11 # Redistribution and use in source and binary forms, with or without modification,
12 # are permitted provided that the following conditions are met:
13 #
14 # * Redistributions of source code must retain the above copyright
15 # notice, this list of conditions and the following disclaimer.
16 # * Redistributions in binary form must reproduce the above copyright notice,
17 # this list of conditions and the following disclaimer in the documentation
18 # and/or other materials provided with the distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
28 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #
30
31
32 import json
33 import os
34 import copy
35 from functools import partial
36 from ansible.module_utils._text import to_native
37 from ansible.module_utils._text import to_text
38 from ansible.module_utils.basic import env_fallback
39 from ansible.module_utils.common.validation import check_type_dict
40 from ast import literal_eval as safe_eval
41
42 try:
43 from infoblox_client.connector import Connector
44 from infoblox_client.exceptions import InfobloxException
45 HAS_INFOBLOX_CLIENT = True
46 except ImportError:
47 HAS_INFOBLOX_CLIENT = False
48
49 # defining nios constants
50 NIOS_DNS_VIEW = 'view'
51 NIOS_NETWORK_VIEW = 'networkview'
52 NIOS_HOST_RECORD = 'record:host'
53 NIOS_IPV4_NETWORK = 'network'
54 NIOS_RANGE = 'range'
55 NIOS_IPV6_NETWORK = 'ipv6network'
56 NIOS_ZONE = 'zone_auth'
57 NIOS_PTR_RECORD = 'record:ptr'
58 NIOS_A_RECORD = 'record:a'
59 NIOS_AAAA_RECORD = 'record:aaaa'
60 NIOS_CNAME_RECORD = 'record:cname'
61 NIOS_MX_RECORD = 'record:mx'
62 NIOS_SRV_RECORD = 'record:srv'
63 NIOS_NAPTR_RECORD = 'record:naptr'
64 NIOS_TXT_RECORD = 'record:txt'
65 NIOS_NSGROUP = 'nsgroup'
66 NIOS_IPV4_FIXED_ADDRESS = 'fixedaddress'
67 NIOS_IPV6_FIXED_ADDRESS = 'ipv6fixedaddress'
68 NIOS_NEXT_AVAILABLE_IP = 'func:nextavailableip'
69 NIOS_IPV4_NETWORK_CONTAINER = 'networkcontainer'
70 NIOS_IPV6_NETWORK_CONTAINER = 'ipv6networkcontainer'
71 NIOS_MEMBER = 'member'
72 NIOS_DTC_SERVER = 'dtc:server'
73 NIOS_DTC_POOL = 'dtc:pool'
74 NIOS_DTC_LBDN = 'dtc:lbdn'
75 NIOS_NSGROUP_FORWARDSTUBSERVER = 'nsgroup:forwardstubserver'
76 NIOS_NSGROUP_FORWARDINGMEMBER = 'nsgroup:forwardingmember'
77 NIOS_NSGROUP_DELEGATION = 'nsgroup:delegation'
78 NIOS_NSGROUP_STUBMEMBER = 'nsgroup:stubmember'
79 NIOS_DTC_MONITOR_HTTP = 'dtc:monitor:http'
80 NIOS_DTC_MONITOR_ICMP = 'dtc:monitor:icmp'
81 NIOS_DTC_MONITOR_PDP = 'dtc:monitor:pdp'
82 NIOS_DTC_MONITOR_SIP = 'dtc:monitor:sip'
83 NIOS_DTC_MONITOR_SNMP = 'dtc:monitor:snmp'
84 NIOS_DTC_MONITOR_TCP = 'dtc:monitor:tcp'
85 NIOS_DTC_TOPOLOGY = 'dtc:topology'
86 NIOS_EXTENSIBLE_ATTRIBUTE = 'extensibleattributedef'
87 NIOS_VLAN = 'vlan'
88 NIOS_ADMINUSER = 'adminuser'
89
90 NIOS_PROVIDER_SPEC = {
91 'host': dict(fallback=(env_fallback, ['INFOBLOX_HOST'])),
92 'username': dict(fallback=(env_fallback, ['INFOBLOX_USERNAME'])),
93 'password': dict(fallback=(env_fallback, ['INFOBLOX_PASSWORD']), no_log=True),
94 'cert': dict(fallback=(env_fallback, ['INFOBLOX_CERT'])),
95 'key': dict(fallback=(env_fallback, ['INFOBLOX_KEY']), no_log=True),
96 'validate_certs': dict(type='bool', default=False, fallback=(env_fallback, ['INFOBLOX_SSL_VERIFY']), aliases=['ssl_verify']),
97 'silent_ssl_warnings': dict(type='bool', default=True),
98 'http_request_timeout': dict(type='int', default=10, fallback=(env_fallback, ['INFOBLOX_HTTP_REQUEST_TIMEOUT'])),
99 'http_pool_connections': dict(type='int', default=10),
100 'http_pool_maxsize': dict(type='int', default=10),
101 'max_retries': dict(type='int', default=3, fallback=(env_fallback, ['INFOBLOX_MAX_RETRIES'])),
102 'wapi_version': dict(default='2.12.3', fallback=(env_fallback, ['INFOBLOX_WAPI_VERSION'])),
103 'max_results': dict(type='int', default=1000, fallback=(env_fallback, ['INFOBLOX_MAX_RESULTS']))
104 }
105
106
107 def get_connector(*args, **kwargs):
108 ''' Returns an instance of infoblox_client.connector.Connector
109 :params args: positional arguments are silently ignored
110 :params kwargs: dict that is passed to Connector init
111 :returns: Connector
112 '''
113 if not HAS_INFOBLOX_CLIENT:
114 raise Exception('infoblox-client is required but does not appear '
115 'to be installed. It can be installed using the '
116 'command `pip install infoblox-client`')
117
118 if not set(kwargs.keys()).issubset(list(NIOS_PROVIDER_SPEC.keys()) + ['ssl_verify']):
119 raise Exception('invalid or unsupported keyword argument for connector')
120 for key, value in NIOS_PROVIDER_SPEC.items():
121 if key not in kwargs:
122 # apply default values from NIOS_PROVIDER_SPEC since we cannot just
123 # assume the provider values are coming from AnsibleModule
124 if 'default' in value:
125 kwargs[key] = value['default']
126
127 # override any values with env variables unless they were
128 # explicitly set
129 env = ('INFOBLOX_%s' % key).upper()
130 if env in os.environ:
131 if NIOS_PROVIDER_SPEC[key].get('type') == 'bool':
132 kwargs[key] = eval(os.environ.get(env).title())
133 elif NIOS_PROVIDER_SPEC[key].get('type') == 'int':
134 kwargs[key] = eval(os.environ.get(env))
135 else:
136 kwargs[key] = os.environ.get(env)
137
138 if 'validate_certs' in kwargs.keys():
139 kwargs['ssl_verify'] = kwargs['validate_certs']
140 kwargs.pop('validate_certs', None)
141
142 return Connector(kwargs)
143
144
145 def normalize_extattrs(value):
146 ''' Normalize extattrs field to expected format
147 The module accepts extattrs as key/value pairs. This method will
148 transform the key/value pairs into a structure suitable for
149 sending across WAPI in the format of:
150 extattrs: {
151 key: {
152 value: <value>
153 }
154 }
155 '''
156 return dict([(k, {'value': v}) for k, v in value.items()])
157
158
159 def flatten_extattrs(value):
160 ''' Flatten the key/value struct for extattrs
161 WAPI returns extattrs field as a dict in form of:
162 extattrs: {
163 key: {
164 value: <value>
165 }
166 }
167 This method will flatten the structure to:
168 extattrs: {
169 key: value
170 }
171 '''
172 return dict([(k, v['value']) for k, v in value.items()])
173
174
175 def member_normalize(member_spec):
176 ''' Transforms the member module arguments into a valid WAPI struct
177 This function will transform the arguments into a structure that
178 is a valid WAPI structure in the format of:
179 {
180 key: <value>,
181 }
182 It will remove any arguments that are set to None since WAPI will error on
183 that condition.
184 The remainder of the value validation is performed by WAPI
185 Some parameters in ib_spec are passed as a list in order to pass the validation for elements.
186 In this function, they are converted to dictionary.
187 '''
188 member_elements = ['vip_setting', 'ipv6_setting', 'lan2_port_setting', 'mgmt_port_setting',
189 'pre_provisioning', 'network_setting', 'v6_network_setting',
190 'ha_port_setting', 'lan_port_setting', 'lan2_physical_setting',
191 'lan_ha_port_setting', 'mgmt_network_setting', 'v6_mgmt_network_setting']
192 for key in list(member_spec.keys()):
193 if key in member_elements and member_spec[key] is not None:
194 member_spec[key] = member_spec[key][0]
195 if isinstance(member_spec[key], dict):
196 member_spec[key] = member_normalize(member_spec[key])
197 elif isinstance(member_spec[key], list):
198 for x in member_spec[key]:
199 if isinstance(x, dict):
200 x = member_normalize(x)
201 elif member_spec[key] is None:
202 del member_spec[key]
203 return member_spec
204
205
206 def convert_members_to_struct(member_spec):
207 ''' Transforms the members list of the Network module arguments into a
208 valid WAPI struct. This function will change arguments into the valid
209 wapi structure of the format:
210 {
211 network: 10.1.1.0/24
212 members:
213 [
214 {'_struct': 'dhcpmember', 'name': 'member_name1'},
215 {'_struct': 'dhcpmember', 'name': 'member_name2'}
216 {'_struct': 'dhcpmember', 'name': '...'}
217 ]
218 }
219 '''
220 if 'members' in member_spec.keys():
221 member_spec['members'] = [{'_struct': 'dhcpmember', 'name': k['name']} for k in member_spec['members']]
222 return member_spec
223
224
225 def convert_ea_list_to_struct(member_spec):
226 ''' Transforms the list of the values into a valid WAPI struct.
227 '''
228 if 'list_values' in member_spec.keys():
229 if all(isinstance(item, dict) for item in member_spec['list_values']):
230 member_spec['list_values'] = [item['value'] for item in member_spec['list_values']]
231 member_spec['list_values'] = [{'_struct': 'extensibleattributedef:listvalues', 'value': v} for v in member_spec['list_values']]
232 return member_spec
233
234
235 def normalize_ib_spec(ib_spec):
236 result = {}
237 for arg in ib_spec:
238 result[arg] = dict([(k, v)
239 for k, v in ib_spec[arg].items()
240 if k not in ('ib_req', 'transform', 'update')])
241 return result
242
243
244 class WapiBase(object):
245 ''' Base class for implementing Infoblox WAPI API '''
246 provider_spec = {'provider': dict(type='dict', options=NIOS_PROVIDER_SPEC)}
247
248 def __init__(self, provider):
249 self.connector = get_connector(**provider)
250
251 def __getattr__(self, name):
252 try:
253 return self.__dict__[name]
254 except KeyError:
255 if name.startswith('_'):
256 raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
257 return partial(self._invoke_method, name)
258
259 def _invoke_method(self, name, *args, **kwargs):
260 try:
261 method = getattr(self.connector, name)
262 return method(*args, **kwargs)
263 except InfobloxException as exc:
264 if hasattr(self, 'handle_exception'):
265 self.handle_exception(name, exc)
266 else:
267 raise
268
269
270 class WapiLookup(WapiBase):
271 ''' Implements WapiBase for lookup plugins '''
272 def handle_exception(self, method_name, exc):
273 if ('text' in exc.response):
274 raise Exception(exc.response['text'])
275 else:
276 raise Exception(exc)
277
278
279 class WapiInventory(WapiBase):
280 ''' Implements WapiBase for dynamic inventory script '''
281 pass
282
283
284 class AnsibleError(Exception):
285 '''Implements raising exceptions'''
286 pass
287
288
289 class WapiModule(WapiBase):
290 ''' Implements WapiBase for executing a NIOS module '''
291 def __init__(self, module):
292 self.module = module
293 provider = module.params['provider']
294 try:
295 super(WapiModule, self).__init__(provider)
296 except Exception as exc:
297 self.module.fail_json(msg=to_text(exc))
298
299 def handle_exception(self, method_name, exc):
300 ''' Handles any exceptions raised
301 This method will be called if an InfobloxException is raised for
302 any call to the instance of Connector and also, in case of generic
303 exception. This method will then gracefully fail the module.
304 :args exc: instance of InfobloxException
305 '''
306 if ('text' in exc.response):
307 self.module.fail_json(
308 msg=exc.response['text'],
309 type=exc.response['Error'].split(':')[0],
310 code=exc.response.get('code'),
311 operation=method_name
312 )
313 else:
314 self.module.fail_json(msg=to_native(exc))
315
316 def clean_empty_keys(self, current_object, proposed_object):
317 """
318 Removes keys from the proposed_object that are empty and do not exist in current_object.
319 :param current_object: The current object to compare with.
320 :param proposed_object: The proposed object to clean up.
321 :return: Cleaned a proposed_object.
322 """
323 keys_to_remove = []
324
325 for key, proposed_item in proposed_object.items():
326 # Check if the key is empty (None, empty string, empty list, etc.)
327 if proposed_item in [None, '', [], {}, set()]: # Add more empty checks if needed
328 # If the key doesn't exist in current_object, mark it for removal
329 if key not in current_object:
330 keys_to_remove.append(key)
331
332 # Remove the identified keys from proposed_object
333 for key in keys_to_remove:
334 del proposed_object[key]
335
336 return proposed_object
337
338 def run(self, ib_obj_type, ib_spec):
339 ''' Runs the module and perform configuration tasks
340 :args ib_obj_type: the WAPI object type to operate against
341 :args ib_spec: the specification for the WAPI object as a dict
342 :returns: result dict
343 '''
344
345 update = new_name = None
346 state = self.module.params['state']
347 if state not in ('present', 'absent'):
348 self.module.fail_json(msg='state must be one of `present`, `absent`, got `%s`' % state)
349
350 result = {'changed': False}
351
352 obj_filter = dict([(k, self.module.params[k]) for k, v in ib_spec.items() if v.get('ib_req')])
353 # get object reference
354 ib_obj_ref, update, new_name = self.get_object_ref(self.module, ib_obj_type, obj_filter, ib_spec)
355
356 # When a range update is defined, check for a range that matches the target range definition as well
357 # to allows for idempotence
358 if ib_obj_type == NIOS_RANGE and len(ib_obj_ref) == 0 and \
359 (True for v in ('new_start_addr', 'new_end_addr') if v in ib_spec.keys()):
360 if self.module.params.get('new_start_addr'):
361 obj_filter['start_addr'] = self.module.params.get('new_start_addr')
362 if self.module.params.get('new_end_addr'):
363 obj_filter['end_addr'] = self.module.params.get('new_end_addr')
364 ib_obj_ref, update, new_name = self.get_object_ref(self.module, ib_obj_type, obj_filter, ib_spec)
365
366 proposed_object = {}
367 for key, value in ib_spec.items():
368 if self.module.params[key] is not None:
369 if 'transform' in value:
370 proposed_object[key] = value['transform'](self.module)
371 else:
372 proposed_object[key] = self.module.params[key]
373 elif 'transform' in value:
374 # Call transform even if param is None, in case it returns a default value
375 transformed_value = value['transform'](self.module)
376 if transformed_value is not None:
377 proposed_object[key] = transformed_value
378
379 # If configure_by_dns is set to False and view is 'default', then delete the default dns
380 if not proposed_object.get('configure_for_dns') and proposed_object.get('view') == 'default' \
381 and ib_obj_type == NIOS_HOST_RECORD:
382 del proposed_object['view']
383 if ib_obj_ref:
384 if len(ib_obj_ref) > 1:
385 for each in ib_obj_ref:
386 # To check for existing A_record with same name with input A_record by IP
387 if each.get('ipv4addr') and each.get('ipv4addr') == proposed_object.get('ipv4addr'):
388 current_object = each
389 break
390 # To check for existing Host_record with same name with input Host_record by IP
391 elif each.get('ipv4addrs') and each.get('ipv4addrs')[0].get('ipv4addr') \
392 == proposed_object.get('ipv4addrs')[0].get('ipv4addr'):
393 current_object = each
394 # Else set the current_object with input value
395 else:
396 current_object = obj_filter
397 ref = None
398 else:
399 current_object = ib_obj_ref[0]
400 if 'extattrs' in current_object:
401 current_object['extattrs'] = flatten_extattrs(current_object['extattrs'])
402 if current_object.get('_ref'):
403 ref = current_object.pop('_ref')
404 else:
405 current_object = obj_filter
406 ref = None
407 # checks if the object type is member to normalize the attributes being passed
408 if (ib_obj_type == NIOS_MEMBER):
409 proposed_object = member_normalize(proposed_object)
410 # The WAPI API will never return the "create_token" field that causes a difference
411 # with the defaults of the module. To prevent this we remove the "create_token" option
412 # if it has not been set to true.
413 if (proposed_object.get("create_token") is not True):
414 proposed_object.pop("create_token")
415
416 if (ib_obj_type == NIOS_IPV4_NETWORK or ib_obj_type == NIOS_IPV6_NETWORK):
417 proposed_object = convert_members_to_struct(proposed_object)
418
419 if ib_obj_type in {NIOS_IPV4_NETWORK_CONTAINER, NIOS_IPV6_NETWORK_CONTAINER, NIOS_IPV4_NETWORK, NIOS_IPV6_NETWORK, NIOS_RANGE}:
420
421 # Iterate over each option and remove the 'num' key
422 if current_object.get('options') or proposed_object.get('options'):
423 if proposed_object.get('options'):
424 # remove use_options false from proposed_object
425 proposed_object['options'] = [option for option in proposed_object['options'] if option.get('use_option', True)]
426
427 if current_object.get('options'):
428 # remove use_options false from current_object
429 current_object['options'] = [option for option in current_object['options'] if option.get('use_option', True)]
430
431 if (ib_obj_type == NIOS_RANGE):
432 if proposed_object.get('new_start_addr'):
433 proposed_object['start_addr'] = proposed_object.get('new_start_addr')
434 del proposed_object['new_start_addr']
435 if proposed_object.get('new_end_addr'):
436 proposed_object['end_addr'] = proposed_object.get('new_end_addr')
437 del proposed_object['new_end_addr']
438
439 if (ib_obj_type == NIOS_EXTENSIBLE_ATTRIBUTE):
440 proposed_object = convert_ea_list_to_struct(proposed_object)
441 current_object = convert_ea_list_to_struct(current_object)
442 # Convert 'default_value' to string in both proposed_object and current_object if it exists
443 for obj in (proposed_object, current_object):
444 if 'default_value' in obj:
445 obj['default_value'] = str(obj['default_value'])
446
447 if ib_obj_type == NIOS_VLAN and ib_obj_ref:
448 if 'parent' in current_object:
449 current_object['parent'] = current_object['parent']['_ref']
450
451 # checks if the 'text' field has to be updated for the TXT Record
452 if (ib_obj_type == NIOS_TXT_RECORD):
453 text_obj = proposed_object["text"]
454 if text_obj.startswith("{"):
455 try:
456 text_obj = json.loads(text_obj)
457 txt = text_obj['new_text']
458 except Exception:
459 try:
460 result = safe_eval(text_obj)
461 txt = result['new_text']
462 except Exception:
463 raise TypeError('unable to evaluate string as dictionary')
464 txt = result['new_text']
465 proposed_object['text'] = txt
466
467 # checks if the name's field has been updated
468 if update and new_name:
469 if (ib_obj_type == NIOS_MEMBER):
470 proposed_object['host_name'] = new_name
471 else:
472 proposed_object['name'] = new_name
473
474 check_remove = []
475 if (ib_obj_type == NIOS_HOST_RECORD):
476 if 'ipv4addrs' in proposed_object and sum(addr.get('use_for_ea_inheritance', False) for addr in proposed_object['ipv4addrs']) > 1:
477 raise AnsibleError('Only one address allowed to be used for extensible attributes inheritance')
478 # this check is for idempotency, as if the same ip address shall be passed
479 # add param will be removed, and the same exists true for the remove case as well.
480 if 'ipv4addrs' in [current_object and proposed_object]:
481 for each in current_object['ipv4addrs']:
482 if each['ipv4addr'] == proposed_object['ipv4addrs'][0]['ipv4addr']:
483 if 'add' in proposed_object['ipv4addrs'][0]:
484 del proposed_object['ipv4addrs'][0]['add']
485 break
486 check_remove += each.values()
487 if proposed_object['ipv4addrs'][0]['ipv4addr'] not in check_remove:
488 if 'remove' in proposed_object['ipv4addrs'][0]:
489 del proposed_object['ipv4addrs'][0]['remove']
490
491 # Checks if 'new_ipv4addr' param exists in ipv4addr args
492 proposed_object = self.check_for_new_ipv4addr(proposed_object)
493
494 res = None
495 if ib_obj_type == NIOS_VLAN:
496 # Removes keys from the proposed_object that are empty and do not exist in current_object.
497 # Fix the issue to update the optional fields of the object with default empty values
498 proposed_object = self.clean_empty_keys(current_object, proposed_object)
499 modified = not self.compare_objects(current_object, proposed_object, ib_obj_type)
500 if 'extattrs' in proposed_object:
501 proposed_object['extattrs'] = normalize_extattrs(proposed_object['extattrs'])
502
503 # Checks if nios_next_ip param is passed in ipv4addrs/ipv4addr args
504 proposed_object = self.check_if_nios_next_ip_exists(proposed_object)
505
506 if state == 'present':
507 if ref is None:
508 if not self.module.check_mode:
509 self.create_object(ib_obj_type, proposed_object)
510 result['changed'] = True
511 # Check if NIOS_MEMBER and the flag to call function create_token is set
512 elif (ib_obj_type == NIOS_MEMBER) and (proposed_object.get("create_token") is True):
513 proposed_object = None
514 # the function creates a token that can be used by a pre-provisioned member to join the grid
515 result['api_results'] = self.call_func('create_token', ref, proposed_object)
516 result['changed'] = True
517 elif modified:
518 if 'ipv4addrs' in proposed_object:
519 if ('add' not in proposed_object['ipv4addrs'][0]) and ('remove' not in proposed_object['ipv4addrs'][0]):
520 self.check_if_recordname_exists(obj_filter, ib_obj_ref, ib_obj_type, current_object, proposed_object)
521
522 if (ib_obj_type in (NIOS_HOST_RECORD, NIOS_NETWORK_VIEW, NIOS_DNS_VIEW)):
523 run_update = True
524 proposed_object = self.on_update(proposed_object, ib_spec)
525 if 'ipv4addrs' in proposed_object:
526 if ('add' or 'remove') in proposed_object['ipv4addrs'][0]:
527 run_update, proposed_object = self.check_if_add_remove_ip_arg_exists(proposed_object)
528 if run_update:
529 res = self.update_object(ref, proposed_object)
530 result['changed'] = True
531 else:
532 res = ref
533
534 if (ib_obj_type in (NIOS_A_RECORD, NIOS_AAAA_RECORD, NIOS_PTR_RECORD, NIOS_SRV_RECORD, NIOS_NAPTR_RECORD)):
535 # popping 'view' key as update of 'view' is not supported with respect to a:record/aaaa:record/srv:record/ptr:record/naptr:record
536 proposed_object = self.on_update(proposed_object, ib_spec)
537 del proposed_object['view']
538 if not self.module.check_mode:
539 res = self.update_object(ref, proposed_object)
540 result['changed'] = True
541 if (ib_obj_type in (NIOS_ZONE)):
542 # popping 'zone_format' key as update of 'zone_format' is not supported with respect to zone_auth
543 proposed_object = self.on_update(proposed_object, ib_spec)
544 del proposed_object['zone_format']
545 self.update_object(ref, proposed_object)
546 result['changed'] = True
547 elif 'network_view' in proposed_object and (ib_obj_type not in (NIOS_IPV4_FIXED_ADDRESS, NIOS_IPV6_FIXED_ADDRESS, NIOS_RANGE)):
548 proposed_object.pop('network_view')
549 if ib_obj_type in (NIOS_IPV4_NETWORK_CONTAINER, NIOS_IPV6_NETWORK_CONTAINER):
550 proposed_object.pop('network')
551 result['changed'] = True
552 if not self.module.check_mode and res is None:
553 proposed_object = self.on_update(proposed_object, ib_spec)
554 if ib_obj_type == NIOS_HOST_RECORD and 'ipv4addrs' in proposed_object:
555 # Remove 'use_for_ea_inheritance' from each dictionary in 'ipv4addrs'
556 update_proposed = copy.deepcopy(proposed_object)
557 update_proposed['ipv4addrs'] = [
558 {k: v for k, v in addr.items() if k != 'use_for_ea_inheritance'}
559 for addr in proposed_object['ipv4addrs']
560 ]
561 res = self.update_object(ref, update_proposed)
562 else:
563 res = self.update_object(ref, proposed_object)
564 result['changed'] = True
565
566 if ib_obj_type == NIOS_HOST_RECORD and res:
567 # WAPI always reset the use_for_ea_inheritance for each update operation
568 # Handle use_for_ea_inheritance flag changes for IPv4addr in a host record
569 # Fetch the updated reference of host to avoid drift.
570 host_ref = self.connector.get_object(obj_type=str(res), return_fields=['ipv4addrs'])
571 if host_ref and 'ipv4addrs' in host_ref:
572 # Create a dictionary for quick lookups
573 ref_dict = {obj['ipv4addr']: obj['_ref'] for obj in host_ref['ipv4addrs']}
574 sorted_ipv4addrs = sorted(proposed_object['ipv4addrs'], key=lambda x: x.get('use_for_ea_inheritance', False))
575 for proposed in sorted_ipv4addrs:
576 ipv4addr = proposed['ipv4addr']
577 if ipv4addr in ref_dict and 'use_for_ea_inheritance' in proposed:
578 self.update_object(ref_dict[ipv4addr], {'use_for_ea_inheritance': proposed['use_for_ea_inheritance']})
579 elif state == 'absent':
580 if ref is not None:
581 if 'ipv4addrs' in proposed_object:
582 if 'remove' in proposed_object['ipv4addrs'][0]:
583 self.check_if_add_remove_ip_arg_exists(proposed_object)
584 self.update_object(ref, proposed_object)
585 result['changed'] = True
586 elif not self.module.check_mode:
587 self.delete_object(ref)
588 result['changed'] = True
589
590 return result
591
592 def check_if_recordname_exists(self, obj_filter, ib_obj_ref, ib_obj_type, current_object, proposed_object):
593 ''' Send POST request if host record input name and retrieved ref name is same,
594 but input IP and retrieved IP is different'''
595
596 if 'name' in (obj_filter and ib_obj_ref[0]) and ib_obj_type == NIOS_HOST_RECORD:
597 obj_host_name = obj_filter['name']
598 ref_host_name = ib_obj_ref[0]['name']
599 if 'ipv4addrs' in (current_object and proposed_object):
600 current_ip_addr = current_object['ipv4addrs'][0]['ipv4addr']
601 proposed_ip_addr = proposed_object['ipv4addrs'][0]['ipv4addr']
602 elif 'ipv6addrs' in (current_object and proposed_object):
603 current_ip_addr = current_object['ipv6addrs'][0]['ipv6addr']
604 proposed_ip_addr = proposed_object['ipv6addrs'][0]['ipv6addr']
605
606 if obj_host_name == ref_host_name and current_ip_addr != proposed_ip_addr:
607 self.create_object(ib_obj_type, proposed_object)
608
609 def get_network_view(self, proposed_object):
610 ''' Check for the associated network view with
611 the given dns_view'''
612 try:
613 network_view_ref = self.get_object('view', {"name": proposed_object['view']}, return_fields=['network_view'])
614 if network_view_ref:
615 network_view = network_view_ref[0].get('network_view')
616 return network_view
617 except Exception:
618 raise Exception("object with dns_view: %s not found" % (proposed_object['view']))
619
620 def check_if_nios_next_ip_exists(self, proposed_object):
621 ''' Check if nios_next_ip argument is passed in ipaddr while creating
622 host record, if yes then format proposed object ipv4addrs and pass
623 func:nextavailableip and ipaddr range to create hostrecord with next
624 available ip in one call to avoid any race condition '''
625
626 if 'ipv4addrs' in proposed_object:
627 if 'nios_next_ip' in proposed_object['ipv4addrs'][0]['ipv4addr']:
628 ip_range = check_type_dict(proposed_object['ipv4addrs'][0]['ipv4addr'])['nios_next_ip']
629 proposed_object['ipv4addrs'][0]['ipv4addr'] = NIOS_NEXT_AVAILABLE_IP + ':' + ip_range
630 elif 'ipv4addr' in proposed_object:
631 if 'nios_next_ip' in proposed_object['ipv4addr']:
632 ip_range = check_type_dict(proposed_object['ipv4addr'])['nios_next_ip']
633 net_view = self.get_network_view(proposed_object)
634 proposed_object['ipv4addr'] = NIOS_NEXT_AVAILABLE_IP + ':' + ip_range + ',' + net_view
635
636 return proposed_object
637
638 def check_for_new_ipv4addr(self, proposed_object):
639 ''' Checks if new_ipv4addr parameter is passed in the argument
640 while updating the record with new ipv4addr with static allocation'''
641 if 'ipv4addr' in proposed_object:
642 if 'new_ipv4addr' in proposed_object['ipv4addr']:
643 new_ipv4 = check_type_dict(proposed_object['ipv4addr'])['new_ipv4addr']
644 proposed_object['ipv4addr'] = new_ipv4
645
646 return proposed_object
647
648 def check_if_add_remove_ip_arg_exists(self, proposed_object):
649 '''
650 This function shall check if add/remove param is set to true and
651 is passed in the args, then we will update the proposed dictionary
652 to add/remove IP to existing host_record, if the user passes false
653 param with the argument nothing shall be done.
654 :returns: True if param is changed based on add/remove, and also the
655 changed proposed_object.
656 '''
657 update = False
658 if 'add' in proposed_object['ipv4addrs'][0]:
659 if proposed_object['ipv4addrs'][0]['add']:
660 proposed_object['ipv4addrs+'] = proposed_object['ipv4addrs']
661 del proposed_object['ipv4addrs']
662 del proposed_object['ipv4addrs+'][0]['add']
663 update = True
664 else:
665 del proposed_object['ipv4addrs'][0]['add']
666 elif 'remove' in proposed_object['ipv4addrs'][0]:
667 if proposed_object['ipv4addrs'][0]['remove']:
668 proposed_object['ipv4addrs-'] = proposed_object['ipv4addrs']
669 del proposed_object['ipv4addrs']
670 del proposed_object['ipv4addrs-'][0]['remove']
671 update = True
672 else:
673 del proposed_object['ipv4addrs'][0]['remove']
674 return update, proposed_object
675
676 def check_next_ip_status(self, obj_filter):
677 ''' Checks if nios next ip argument exists if True returns true
678 else returns false'''
679 if 'ipv4addr' in obj_filter:
680 if 'nios_next_ip' in obj_filter['ipv4addr']:
681 return True
682 return False
683
684 def issubset(self, item, objects):
685 ''' Checks if item is a subset of objects
686 :args item: the subset item to validate
687 :args objects: superset list of objects to validate against
688 :returns: True if item is a subset of one entry in objects otherwise
689 this method will return None
690 '''
691 for obj in objects:
692 if isinstance(item, dict):
693 # Normalize MAC address for comparison
694 if 'mac' in item:
695 item['mac'] = item['mac'].replace('-', ':').lower()
696 elif 'duid' in item:
697 item['duid'] = item['duid'].replace('-', ':').lower()
698 if all(entry in obj.items() for entry in item.items()):
699 return True
700 else:
701 if item in obj:
702 return True
703
704 def compare_extattrs(self, current_extattrs, proposed_extattrs):
705 '''Compare current extensible attributes to given extensible
706 attribute, if length is not equal returns false , else
707 checks the value of keys in proposed extattrs'''
708 if len(current_extattrs) != len(proposed_extattrs):
709 return False
710 else:
711 for key, proposed_item in proposed_extattrs.items():
712 current_item = current_extattrs.get(key)
713 if current_item != proposed_item:
714 return False
715 return True
716
717 def verify_list_order(self, proposed_data, current_data):
718 return len(proposed_data) == len(current_data) and all(a == b for a, b in zip(proposed_data, current_data))
719
720 def compare_objects(self, current_object, proposed_object, ib_obj_type=None):
721 for key, proposed_item in proposed_object.items():
722 current_item = current_object.get(key)
723
724 # if proposed has a key that current doesn't, then the objects are
725 # not equal and False will be immediately returned
726 if current_item is None:
727 # Allow None/empty values to be considered equal
728 if proposed_item in (None, '', [], {}, set()):
729 continue
730 return False
731
732 elif isinstance(proposed_item, list):
733 if key == 'aliases':
734 if set(current_item) != set(proposed_item):
735 return False
736 # If the lists are of a different length, the objects cannot be
737 # equal, and False will be returned before comparing the list items
738 # this code part will work for members' assignment
739
740 if key in ('monitors', 'members', 'options', 'delegate_to', 'forwarding_servers', 'stub_members', 'ssh_keys', 'vlans') \
741 and len(proposed_item) != len(current_item):
742 return False
743
744 # Special handling for auth_zones - we need to compare the actual values
745 if key == 'auth_zones' and ib_obj_type == NIOS_DTC_LBDN:
746 if len(proposed_item) != len(current_item):
747 return False
748 # Sort and compare as strings for deterministic comparison
749 current_zones_str = sorted([str(zone) for zone in current_item])
750 proposed_zones_str = sorted([str(zone) for zone in proposed_item])
751 if current_zones_str != proposed_zones_str:
752 return False
753
754 # Validate the Sequence of the List data
755 if key in ('servers', 'external_servers', 'list_values') and not self.verify_list_order(proposed_item, current_item):
756 return False
757
758 for subitem in proposed_item:
759 if not isinstance(subitem, dict):
760 continue # Skip non-dict items
761
762 if ib_obj_type == NIOS_HOST_RECORD and key == 'ipv4addrs':
763 current_config = current_item[0]
764 dhcp_flag = current_config.get('configure_for_dhcp', False)
765 # Host IPv4addrs wont contain use_nextserver and nextserver
766 # If DHCP is false.
767 use_nextserver = subitem.get('use_nextserver', False)
768
769 if not dhcp_flag:
770 try:
771 subitem.pop('use_nextserver')
772 subitem.pop('nextserver')
773 except KeyError:
774 pass
775 elif dhcp_flag and not use_nextserver:
776 try:
777 subitem.pop('nextserver')
778 except KeyError:
779 pass
780
781 if not self.issubset(subitem, current_item):
782 return False
783
784 if key == 'logic_filter_rules' and proposed_item != current_item:
785 return False
786
787 elif isinstance(proposed_item, dict):
788 # Compare the items of the dict to see if they are equal. A
789 # difference stops the comparison and returns false. If they
790 # are equal, move on to the next item
791
792 # Checks if extattrs existing in proposed object
793 if key == 'extattrs':
794 current_extattrs = current_object.get(key)
795 proposed_extattrs = proposed_object.get(key)
796 if not self.compare_extattrs(current_extattrs, proposed_extattrs):
797 return False
798
799 if self.compare_objects(current_item, proposed_item, ib_obj_type) is False:
800 return False
801 else:
802 continue
803
804 else:
805 if current_item != proposed_item:
806 return False
807
808 return True
809
810 def get_object_ref(self, module, ib_obj_type, obj_filter, ib_spec):
811 ''' this function gets the reference object of pre-existing nios objects '''
812 update = False
813 old_name = new_name = None
814 old_ipv4addr_exists = old_text_exists = False
815 next_ip_exists = False
816
817 if ib_obj_type == NIOS_VLAN:
818 obj_filter.update({'parent': ib_spec['parent']['transform'](self.module)})
819
820 if ('name' in obj_filter):
821 # gets and returns the current object based on name/old_name passed
822 try:
823 name_obj = check_type_dict(obj_filter['name'])
824 # check if network_view allows searching and updating with camelCase
825 if (ib_obj_type == NIOS_NETWORK_VIEW):
826 old_name = name_obj['old_name']
827 new_name = name_obj['new_name']
828 else:
829 old_name = name_obj['old_name'].lower()
830 new_name = name_obj['new_name'].lower()
831 except TypeError:
832 name = obj_filter['name']
833
834 return_fields = list(ib_spec.keys())
835
836 if (ib_obj_type == NIOS_ADMINUSER):
837 if 'password' in return_fields:
838 return_fields.remove('password')
839
840 if old_name and new_name:
841 if (ib_obj_type == NIOS_HOST_RECORD):
842 # to check only by old_name if dns bypassing is set
843 if not obj_filter['configure_for_dns']:
844 test_obj_filter = dict([('name', old_name)])
845 else:
846 test_obj_filter = dict([('name', old_name), ('view', obj_filter['view'])])
847 # if there are multiple records with the same name and different ip
848 elif (ib_obj_type == NIOS_A_RECORD):
849 test_obj_filter = dict([('name', old_name), ('ipv4addr', obj_filter['ipv4addr'])])
850 try:
851 ipaddr_obj = check_type_dict(obj_filter['ipv4addr'])
852 ipaddr = ipaddr_obj.get('old_ipv4addr')
853 old_ipv4addr_exists = True if ipaddr else False
854 except TypeError:
855 ipaddr = test_obj_filter['ipv4addr']
856 if old_ipv4addr_exists:
857 test_obj_filter['ipv4addr'] = ipaddr
858 else:
859 del test_obj_filter['ipv4addr']
860 elif ib_obj_type == NIOS_VLAN:
861 test_obj_filter = dict([
862 ('name', old_name), ('id', obj_filter['id']), ('parent', obj_filter['parent'])])
863 else:
864 test_obj_filter = dict([('name', old_name)])
865 # get the object reference
866 ib_obj = self.get_object(ib_obj_type, test_obj_filter, return_fields=return_fields)
867 if ib_obj:
868 obj_filter['name'] = new_name
869 elif old_ipv4addr_exists and (len(ib_obj) == 0):
870 raise Exception(
871 "object with name: '%s', ipv4addr: '%s' is not found" % (old_name, test_obj_filter['ipv4addr']))
872 else:
873 raise Exception("object with name: '%s' is not found" % (old_name))
874 update = True
875 return ib_obj, update, new_name
876 if (ib_obj_type == NIOS_HOST_RECORD):
877 # to fix the sanity issue
878 name = obj_filter['name']
879 # to check only by name if dns bypassing is set
880 if not obj_filter['configure_for_dns']:
881 test_obj_filter = dict([('name', name)])
882 else:
883 test_obj_filter = dict([('name', name), ('view', obj_filter['view'])])
884 elif (ib_obj_type == NIOS_IPV4_FIXED_ADDRESS and 'mac' in obj_filter):
885 test_obj_filter = dict([['mac', obj_filter['mac']]])
886 elif (ib_obj_type == NIOS_IPV6_FIXED_ADDRESS and 'duid' in obj_filter):
887 test_obj_filter = dict([['duid', obj_filter['duid']]])
888 elif (ib_obj_type == NIOS_CNAME_RECORD):
889 test_obj_filter = dict([('name', obj_filter['name']), ('view', obj_filter['view'])])
890 elif (ib_obj_type == NIOS_A_RECORD):
891 # resolves issue where a_record with uppercase name was returning null and was failing
892 test_obj_filter = obj_filter
893 test_obj_filter['name'] = test_obj_filter['name'].lower()
894 # resolves issue where multiple a_records with same name and different IP address
895 try:
896 ipaddr_obj = check_type_dict(obj_filter['ipv4addr'])
897 ipaddr = ipaddr_obj.get('old_ipv4addr')
898 old_ipv4addr_exists = True if ipaddr else False
899 if not old_ipv4addr_exists:
900 next_ip_exists = self.check_next_ip_status(test_obj_filter)
901 except TypeError:
902 ipaddr = obj_filter['ipv4addr']
903 if old_ipv4addr_exists:
904 test_obj_filter['ipv4addr'] = ipaddr
905 # resolve issue if nios_next_ip exists which is not searchable attribute
906 if next_ip_exists:
907 del test_obj_filter['ipv4addr']
908 elif (ib_obj_type == NIOS_TXT_RECORD):
909 # resolves issue where multiple txt_records with same name and different text
910 test_obj_filter = obj_filter
911 try:
912 text_obj = obj_filter['text']
913 if text_obj.startswith("{"):
914 try:
915 text_obj = json.loads(text_obj)
916 txt = text_obj['old_text']
917 old_text_exists = True
918 except Exception:
919 try:
920 result = safe_eval(text_obj)
921 txt = result['old_text']
922 old_text_exists = True
923 except Exception:
924 raise TypeError('unable to evaluate string as dictionary')
925 txt = result['old_text']
926 old_text_exists = True
927 else:
928 txt = text_obj
929 except TypeError:
930 txt = obj_filter['text']
931 test_obj_filter['text'] = txt
932
933 # removing Port param from get params for NIOS_DTC_MONITOR_TCP
934 elif (ib_obj_type == NIOS_DTC_MONITOR_TCP):
935 test_obj_filter = dict([('name', obj_filter['name'])])
936
937 # check if test_obj_filter is empty copy passed obj_filter
938 else:
939 test_obj_filter = obj_filter
940
941 if ib_obj_type == NIOS_HOST_RECORD:
942 ipv4addrs_return = [
943 'ipv4addrs.ipv4addr', 'ipv4addrs.mac', 'ipv4addrs.configure_for_dhcp', 'ipv4addrs.host',
944 'ipv4addrs.nextserver', 'ipv4addrs.use_nextserver', 'ipv4addrs.use_for_ea_inheritance'
945 ]
946 ipv6addrs_return = [
947 'ipv6addrs.ipv6addr', 'ipv6addrs.duid', 'ipv6addrs.configure_for_dhcp', 'ipv6addrs.host'
948 ]
949 return_fields.extend(ipv4addrs_return)
950 return_fields.extend(ipv6addrs_return)
951
952 ib_obj = self.get_object(ib_obj_type, test_obj_filter.copy(), return_fields=return_fields)
953
954 # prevents creation of a new A record with 'new_ipv4addr' when A record with a particular 'old_ipv4addr' is not found
955 if old_ipv4addr_exists and (ib_obj is None or len(ib_obj) == 0):
956 raise Exception("A Record with ipv4addr: '%s' is not found" % (ipaddr))
957 # prevents creation of a new TXT record with 'new_text' when TXT record with a particular 'old_text' is not found
958 if old_text_exists and ib_obj is None:
959 raise Exception("TXT Record with text: '%s' is not found" % (txt))
960 elif (ib_obj_type == NIOS_A_RECORD):
961 # resolves issue where multiple a_records with same name and different IP address
962 test_obj_filter = obj_filter
963 try:
964 ipaddr_obj = check_type_dict(obj_filter['ipv4addr'])
965 ipaddr = ipaddr_obj.get('old_ipv4addr')
966 old_ipv4addr_exists = True if ipaddr else False
967 except TypeError:
968 ipaddr = obj_filter['ipv4addr']
969 test_obj_filter['ipv4addr'] = ipaddr
970 ib_obj = self.get_object(ib_obj_type, test_obj_filter.copy(), return_fields=list(ib_spec.keys()))
971 # prevents creation of a new A record with 'new_ipv4addr' when A record with a particular 'old_ipv4addr' is not found
972 if old_ipv4addr_exists and ib_obj is None:
973 raise Exception("A Record with ipv4addr: '%s' is not found" % (ipaddr))
974 elif (ib_obj_type == NIOS_TXT_RECORD):
975 # resolves issue where multiple txt_records with same name and different text
976 test_obj_filter = obj_filter
977 try:
978 text_obj = obj_filter(['text'])
979 if text_obj.startswith("{"):
980 try:
981 text_obj = json.loads(text_obj)
982 txt = text_obj['old_text']
983 old_text_exists = True
984 except Exception:
985 try:
986 result = safe_eval(text_obj)
987 txt = result['old_text']
988 old_text_exists = True
989 except Exception:
990 raise TypeError('unable to evaluate string as dictionary')
991 txt = result['old_text']
992 old_text_exists = True
993 else:
994 txt = text_obj
995 except TypeError:
996 txt = obj_filter['text']
997 test_obj_filter['text'] = txt
998 ib_obj = self.get_object(ib_obj_type, test_obj_filter.copy(), return_fields=list(ib_spec.keys()))
999 # prevents creation of a new TXT record with 'new_text' when TXT record with a particular 'old_text' is not found
1000 if old_text_exists and ib_obj is None:
1001 raise Exception("TXT Record with text: '%s' is not found" % (txt))
1002 elif (ib_obj_type == NIOS_ZONE):
1003 # del key 'restart_if_needed' as nios_zone get_object fails with the key present
1004 temp = ib_spec['restart_if_needed']
1005 del ib_spec['restart_if_needed']
1006 ib_obj = self.get_object(ib_obj_type, obj_filter.copy(), return_fields=list(ib_spec.keys()))
1007 # reinstate restart_if_needed if ib_obj is none, meaning there's no existing nios_zone ref
1008 if not ib_obj:
1009 ib_spec['restart_if_needed'] = temp
1010 elif (ib_obj_type == NIOS_MEMBER):
1011 # gets and returns current_object as per old_name/host_name passed
1012 test_obj_filter = obj_filter
1013 try:
1014 name_obj = check_type_dict(test_obj_filter['host_name'])
1015 old_name = name_obj['old_name']
1016 new_name = name_obj['new_name']
1017 except TypeError:
1018 host_name = obj_filter['host_name']
1019
1020 if old_name and new_name:
1021 test_obj_filter['host_name'] = old_name
1022 temp = ib_spec['create_token']
1023 del ib_spec['create_token']
1024 ib_obj = self.get_object(ib_obj_type, test_obj_filter.copy(), return_fields=list(ib_spec.keys()))
1025 if temp:
1026 # reinstate 'create_token' key
1027 ib_spec['create_token'] = temp
1028 if ib_obj:
1029 obj_filter['host_name'] = new_name
1030 else:
1031 raise Exception("object with name: '%s' is not found" % (old_name))
1032 update = True
1033 else:
1034 # del key 'create_token' as nios_member get_object fails with the key present
1035 temp = ib_spec['create_token']
1036 del ib_spec['create_token']
1037 ib_obj = self.get_object(ib_obj_type, obj_filter.copy(), return_fields=list(ib_spec.keys()))
1038 if temp:
1039 # reinstate 'create_token' key
1040 ib_spec['create_token'] = temp
1041 elif (ib_obj_type in (NIOS_IPV4_NETWORK, NIOS_IPV6_NETWORK, NIOS_IPV4_NETWORK_CONTAINER, NIOS_IPV6_NETWORK_CONTAINER)):
1042 # del key 'template' as nios_network get_object fails with the key present
1043 temp = ib_spec['template']
1044 del ib_spec['template']
1045
1046 if (ib_obj_type in (NIOS_IPV4_NETWORK_CONTAINER, NIOS_IPV6_NETWORK_CONTAINER)):
1047 # del key 'members' as nios_network get_object fails with the key present
1048 # Don't reinstate the field after as it is not valid for network containers
1049 del ib_spec['members']
1050 del ib_spec['vlans']
1051
1052 ib_obj = self.get_object(ib_obj_type, obj_filter.copy(), return_fields=list(ib_spec.keys()))
1053 # reinstate the 'template' and 'members' key
1054 if temp:
1055 ib_spec['template'] = temp
1056
1057 elif (ib_obj_type in (NIOS_RANGE)):
1058 # Delete the update keys to find the original range object
1059 new_start = ib_spec.get('new_start_addr')
1060 new_end = ib_spec.get('new_end_addr')
1061 del ib_spec['new_start_addr']
1062 del ib_spec['new_end_addr']
1063 new_start_arg = self.module.params.get('new_start_addr')
1064 new_end_arg = self.module.params.get('new_end_addr')
1065 ib_obj = self.get_object(ib_obj_type, obj_filter.copy(), return_fields=list(ib_spec.keys()))
1066 # Restore the keys to the object.
1067 if new_start:
1068 ib_spec['new_start_addr'] = new_start
1069 if new_end:
1070 ib_spec['new_end_addr'] = new_end
1071
1072 # throws exception if start_addr and end_addr doesn't exists for updating range
1073 if (new_start_arg and new_end_arg):
1074 if not ib_obj:
1075 raise Exception(
1076 'Specified range %s-%s not found' % (obj_filter['start_addr'], obj_filter['end_addr']))
1077 else:
1078 ib_obj = self.get_object(ib_obj_type, obj_filter.copy(), return_fields=list(ib_spec.keys()))
1079 return ib_obj, update, new_name
1080
1081 def on_update(self, proposed_object, ib_spec):
1082 ''' Event called before the update is sent to the API endpoing
1083 This method will allow the final proposed object to be changed
1084 and/or keys filtered before it is sent to the API endpoint to
1085 be processed.
1086 :args proposed_object: A dict item that will be encoded and sent
1087 the API endpoint with the updated data structure
1088 :returns: updated object to be sent to API endpoint
1089 '''
1090 keys = set()
1091 for key, value in proposed_object.items():
1092 update = ib_spec[key].get('update', True)
1093 if not update:
1094 keys.add(key)
1095 return dict([(k, v) for k, v in proposed_object.items() if k not in keys])