def monitor_bindings_identical(client, module): log('Entering monitor_bindings_identical') configured_bindings = get_configured_monitor_bindings(client, module) actual_bindings = get_actual_monitor_bindings(client, module) configured_key_set = set(configured_bindings.keys()) actual_key_set = set(actual_bindings.keys()) symmetrical_diff = configured_key_set ^ actual_key_set for default_monitor in ('tcp-default', 'ping-default'): if default_monitor in symmetrical_diff: log('Excluding %s monitor from key comparison' % default_monitor) symmetrical_diff.remove(default_monitor) if len(symmetrical_diff) > 0: return False # Compare key to key for key in configured_key_set: configured_proxy = configured_bindings[key] # Follow nscli convention for missing weight value if not hasattr(configured_proxy, 'weight'): configured_proxy.weight = 1 log('configured_proxy %s' % [configured_proxy.monitorname, configured_proxy.servicegroupname, configured_proxy.weight]) log('actual_bindings %s' % [actual_bindings[key].monitor_name, actual_bindings[key].servicegroupname, actual_bindings[key].weight]) if not monitor_binding_equal(configured_proxy, actual_bindings[key]): return False # Fallthrought to success return True
def get_actual_monitor_bindings(client, module): log('get_actual_monitor_bindings') # Get actual monitor bindings and index them by monitor_name actual_monitor_bindings = {} if gslbservice_lbmonitor_binding.count( client, servicename=module.params['servicename']) != 0: # Get all monitor bindings associated with the named gslb vserver fetched_bindings = gslbservice_lbmonitor_binding.get( client, servicename=module.params['servicename']) # index by monitor name for binding in fetched_bindings: # complete_missing_attributes(binding, gslbservice_lbmonitor_binding_rw_attrs, fill_value=None) actual_monitor_bindings[binding.monitor_name] = binding return actual_monitor_bindings
def sync_cs_policybindings(client, module): log('Syncing cs policybindings') actual_bindings = get_actual_policybindings(client, module) configured_bindings = get_configured_policybindings(client, module) # Delete actual bindings not in configured delete_keys = list( set(actual_bindings.keys()) - set(configured_bindings.keys())) for key in delete_keys: log('Deleting binding for policy %s' % key) csvserver_cspolicy_binding.delete(client, actual_bindings[key]) # Add configured bindings not in actual add_keys = list( set(configured_bindings.keys()) - set(actual_bindings.keys())) for key in add_keys: log('Adding binding for policy %s' % key) configured_bindings[key].add() # Update existing if changed modify_keys = list( set(configured_bindings.keys()) & set(actual_bindings.keys())) for key in modify_keys: if not configured_bindings[key].has_equal_attributes( actual_bindings[key]): log('Updating binding for policy %s' % key) csvserver_cspolicy_binding.delete(client, actual_bindings[key]) configured_bindings[key].add()
def get_actual_domain_bindings(client, module): log('get_actual_domain_bindings') # Get actual domain bindings and index them by domainname actual_domain_bindings = {} if gslbvserver_domain_binding.count(client, name=module.params['name']) != 0: # Get all domain bindings associated with the named gslb vserver fetched_domain_bindings = gslbvserver_domain_binding.get( client, name=module.params['name']) # index by domainname for binding in fetched_domain_bindings: complete_missing_attributes(binding, gslbvserver_domain_binding_rw_attrs, fill_value=None) actual_domain_bindings[binding.domainname] = binding return actual_domain_bindings
def server_identical(client, module, server_proxy): log('Checking if configured server is identical') if server.count_filtered(client, 'name:%s' % module.params['name']) == 0: return False diff = diff_list(client, module, server_proxy) # Remove options that are not present in nitro server object # These are special options relevant to the disabled action for option in ['graceful', 'delay']: if option in diff: del diff[option] if diff == {}: return True else: return False
def get_configured_service_bindings(client, module): log('get_configured_service_bindings_proxys') configured_proxys = {} # Get configured domain bindings and index them by domainname if module.params['service_bindings'] is not None: for configured_binding in module.params['service_bindings']: binding_values = copy.deepcopy(configured_binding) binding_values['name'] = module.params['name'] gslbvserver_service_binding_proxy = ConfigProxy( actual=gslbvserver_gslbservice_binding(), client=client, attribute_values_dict=binding_values, readwrite_attrs=gslbvserver_gslbservice_binding_rw_attrs, readonly_attrs=[], ) configured_proxys[configured_binding[ 'servicename']] = gslbvserver_service_binding_proxy return configured_proxys
def ssl_certkey_bindings_identical(client, module): log('Checking if ssl cert key bindings are identical') vservername = module.params['name'] if sslvserver_sslcertkey_binding.count(client, vservername) == 0: bindings = [] else: bindings = sslvserver_sslcertkey_binding.get(client, vservername) if module.params['ssl_certkey'] is None: if len(bindings) == 0: return True else: return False else: certificate_list = [item.certkeyname for item in bindings] if certificate_list == [module.params['ssl_certkey']]: return True else: return False
def cs_policybindings_identical(client, module): log('Checking policy bindings identical') actual_bindings = get_actual_policybindings(client, module) configured_bindings = get_configured_policybindings(client, module) actual_keyset = set(actual_bindings.keys()) configured_keyset = set(configured_bindings.keys()) if len(actual_keyset ^ configured_keyset) > 0: return False # Compare item to item for key in actual_bindings.keys(): configured_binding_proxy = configured_bindings[key] actual_binding_object = actual_bindings[key] if not configured_binding_proxy.has_equal_attributes( actual_binding_object): return False # Fallthrough to success return True
def get_actual_policybindings(client, module): log('Getting actual policy bindigs') bindings = {} try: count = csvserver_cspolicy_binding.count(client, name=module.params['name']) if count == 0: return bindings except nitro_exception as e: if e.errorcode == 258: return bindings else: raise for binding in csvserver_cspolicy_binding.get(client, name=module.params['name']): key = binding.policyname bindings[key] = binding return bindings
def sync_default_lb_vserver(client, module): d = get_default_lb_vserver(client, module) if module.params['lbvserver'] is not None: configured = ConfigProxy(actual=csvserver_lbvserver_binding(), client=client, readwrite_attrs=[ 'name', 'lbvserver', ], attribute_values_dict={ 'name': module.params['name'], 'lbvserver': module.params['lbvserver'], }) if not configured.has_equal_attributes(d): if d.name is not None: log('Deleting default lb vserver %s' % d.lbvserver) csvserver_lbvserver_binding.delete(client, d) log('Adding default lb vserver %s' % configured.lbvserver) configured.add() else: if d.name is not None: log('Deleting default lb vserver %s' % d.lbvserver) csvserver_lbvserver_binding.delete(client, d)
def sync_service_bindings(client, module): actual = get_actual_service_bindings(client, module) configured = get_configured_service_bindings(client, module) # Delete extraneous extraneous_service_bindings = list( set(actual.keys()) - set(configured.keys())) for servicename in extraneous_service_bindings: log('Deleting missing binding from service %s' % servicename) binding = actual[servicename] binding.name = module.params['name'] gslbvserver_gslbservice_binding.delete(client, binding) # Recreate different common_service_bindings = list(set(actual.keys()) & set(configured.keys())) for servicename in common_service_bindings: proxy = configured[servicename] binding = actual[servicename] if not proxy.has_equal_attributes(actual): log('Recreating differing service binding %s' % servicename) gslbvserver_gslbservice_binding.delete(client, binding) proxy.add() # Add missing missing_service_bindings = list( set(configured.keys()) - set(actual.keys())) for servicename in missing_service_bindings: proxy = configured[servicename] log('Adding missing service binding %s' % servicename) proxy.add()
def sync_monitor_bindings(client, module, monitor_bindings_rw_attrs): configured_proxys = get_configured_monitor_bindings( client, module, monitor_bindings_rw_attrs) actual_bindings = get_actual_monitor_bindings(client, module) configured_keyset = set(configured_proxys.keys()) actual_keyset = set(actual_bindings.keys()) # Delete extra delete_keys = list(actual_keyset - configured_keyset) for monitor_name in delete_keys: log('Deleting binding for monitor %s' % monitor_name) lbmonitor_service_binding.delete(client, actual_bindings[monitor_name]) # Delete and re-add modified common_keyset = list(configured_keyset & actual_keyset) for monitor_name in common_keyset: proxy = configured_proxys[monitor_name] actual = actual_bindings[monitor_name] if not proxy.has_equal_attributes(actual): log('Deleting and re adding binding for monitor %s' % monitor_name) lbmonitor_service_binding.delete(client, actual) proxy.add() # Add new new_keys = list(configured_keyset - actual_keyset) for monitor_name in new_keys: log('Adding binding for monitor %s' % monitor_name) configured_proxys[monitor_name].add()
def get_actual_monitor_bindings(client, module): log('Entering get_actual_monitor_bindings') bindings = {} try: # count() raises nitro exception instead of returning 0 count = servicegroup_lbmonitor_binding.count(client, module.params['servicegroupname']) except nitro_exception as e: if e.errorcode == 258: return bindings else: raise if count == 0: return bindings # Fallthrough to rest of execution for binding in servicegroup_lbmonitor_binding.get(client, module.params['servicegroupname']): log('Gettign actual monitor with name %s' % binding.monitor_name) key = binding.monitor_name bindings[key] = binding return bindings
def get_configured_service_members(client, module): log('get_configured_service_members') readwrite_attrs = [ 'servicegroupname', 'ip', 'port', 'state', 'hashid', 'serverid', 'servername', 'customserverid', 'weight' ] readonly_attrs = [ 'delay', 'statechangetimesec', 'svrstate', 'tickssincelaststatechange', 'graceful', ] members = [] if module.params['servicemembers'] is None: return members for config in module.params['servicemembers']: # Make a copy to update config = copy.deepcopy(config) config['servicegroupname'] = module.params['servicegroupname'] member_proxy = ConfigProxy( actual=servicegroup_servicegroupmember_binding(), client=client, attribute_values_dict=config, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs ) members.append(member_proxy) return members
def get_configured_monitor_bindings(client, module): log('Entering get_configured_monitor_bindings') bindings = {} if 'monitorbindings' in module.params and module.params['monitorbindings'] is not None: for binding in module.params['monitorbindings']: readwrite_attrs = [ 'monitorname', 'servicegroupname', 'weight', ] readonly_attrs = [] attribute_values_dict = copy.deepcopy(binding) attribute_values_dict['servicegroupname'] = module.params['servicegroupname'] binding_proxy = ConfigProxy( actual=lbmonitor_servicegroup_binding(), client=client, attribute_values_dict=attribute_values_dict, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) key = attribute_values_dict['monitorname'] bindings[key] = binding_proxy return bindings
def get_configured_monitor_bindings(client, module): log('get_configured_monitor_bindings') configured_monitor_proxys = {} gslbservice_lbmonitor_binding_rw_attrs = [ 'weight', 'servicename', 'monitor_name', ] # Get configured monitor bindings and index them by monitor_name if module.params['monitor_bindings'] is not None: for configured_monitor_bindings in module.params['monitor_bindings']: binding_values = copy.deepcopy(configured_monitor_bindings) binding_values['servicename'] = module.params['servicename'] proxy = ConfigProxy( actual=gslbservice_lbmonitor_binding(), client=client, attribute_values_dict=binding_values, readwrite_attrs=gslbservice_lbmonitor_binding_rw_attrs, readonly_attrs=[], ) configured_monitor_proxys[ configured_monitor_bindings['monitor_name']] = proxy return configured_monitor_proxys
def domain_bindings_identical(client, module): log('domain_bindings_identical') actual_domain_bindings = get_actual_domain_bindings(client, module) configured_domain_proxys = get_configured_domain_bindings_proxys( client, module) actual_keyset = set(actual_domain_bindings.keys()) configured_keyset = set(configured_domain_proxys.keys()) symmetric_difference = actual_keyset ^ configured_keyset log('symmetric difference %s' % symmetric_difference) if len(symmetric_difference) != 0: return False # Item for item equality test for key, proxy in configured_domain_proxys.items(): diff = proxy.diff_object(actual_domain_bindings[key]) if 'backupipflag' in diff: del diff['backupipflag'] if not len(diff) == 0: return False # Fallthrough to True result return True
def sync_service_members(client, module): log('sync_service_members') configured_service_members = get_configured_service_members(client, module) actual_service_members = get_actual_service_members(client, module) skip_add = [] skip_delete = [] # Find positions of identical service members for (configured_index, configured_service) in enumerate(configured_service_members): for (actual_index, actual_service) in enumerate(actual_service_members): if configured_service.has_equal_attributes(actual_service): skip_add.append(configured_index) skip_delete.append(actual_index) # Delete actual that are not identical to any configured for (actual_index, actual_service) in enumerate(actual_service_members): # Skip identical if actual_index in skip_delete: log('Skipping actual delete at index %s' % actual_index) continue # Fallthrouth to deletion if all([ hasattr(actual_service, 'ip'), actual_service.ip is not None, hasattr(actual_service, 'servername'), actual_service.servername is not None, ]): actual_service.ip = None actual_service.servicegroupname = module.params['servicegroupname'] servicegroup_servicegroupmember_binding.delete(client, actual_service) # Add configured that are not already present in actual for (configured_index, configured_service) in enumerate(configured_service_members): # Skip identical if configured_index in skip_add: log('Skipping configured add at index %s' % configured_index) continue # Fallthrough to addition configured_service.add()
def ssl_certkey_bindings_sync(client, module): log('Syncing certkey bindings') vservername = module.params['name'] if sslvserver_sslcertkey_binding.count(client, vservername) == 0: bindings = [] else: bindings = sslvserver_sslcertkey_binding.get(client, vservername) # Delete existing bindings for binding in bindings: log('Deleting existing binding for certkey %s' % binding.certkeyname) sslvserver_sslcertkey_binding.delete(client, binding) # Add binding if appropriate if module.params['ssl_certkey'] is not None: log('Adding binding for certkey %s' % module.params['ssl_certkey']) binding = sslvserver_sslcertkey_binding() binding.vservername = module.params['name'] binding.certkeyname = module.params['ssl_certkey'] sslvserver_sslcertkey_binding.add(client, binding)
def servicemembers_identical(client, module): log('servicemembers_identical') servicegroup_members = get_actual_service_members(client, module) log('servicemembers %s' % servicegroup_members) module_servicegroups = get_configured_service_members(client, module) log('Number of service group members %s' % len(servicegroup_members)) if len(servicegroup_members) != len(module_servicegroups): return False # Fallthrough to member evaluation identical_count = 0 for actual_member in servicegroup_members: for member in module_servicegroups: if member.has_equal_attributes(actual_member): identical_count += 1 break if identical_count != len(servicegroup_members): return False # Fallthrough to success return True
def monitor_bindings_identical(client, module): log('monitor_bindings_identical') actual_bindings = get_actual_monitor_bindings(client, module) configured_proxys = get_configured_monitor_bindings(client, module) actual_keyset = set(actual_bindings.keys()) configured_keyset = set(configured_proxys.keys()) symmetric_difference = actual_keyset ^ configured_keyset if len(symmetric_difference) != 0: log('Symmetric difference %s' % symmetric_difference) return False # Item for item equality test for key, proxy in configured_proxys.items(): if not proxy.has_equal_attributes(actual_bindings[key]): log('monitor binding difference %s' % proxy.diff_object(actual_bindings[key])) return False # Fallthrough to True result return True
def main(): module_specific_arguments = dict( name=dict(type='str'), td=dict(type='float'), servicetype=dict(type='str', choices=[ 'HTTP', 'SSL', 'TCP', 'FTP', 'RTSP', 'SSL_TCP', 'UDP', 'DNS', 'SIP_UDP', 'SIP_TCP', 'SIP_SSL', 'ANY', 'RADIUS', 'RDP', 'MYSQL', 'MSSQL', 'DIAMETER', 'SSL_DIAMETER', 'DNS_TCP', 'ORACLE', 'SMPP' ]), ipv46=dict(type='str'), dnsrecordtype=dict(type='str', choices=[ 'A', 'AAAA', 'CNAME', 'NAPTR', ]), ippattern=dict(type='str'), ipmask=dict(type='str'), range=dict(type='float'), port=dict(type='int'), stateupdate=dict(type='str', choices=[ 'enabled', 'disabled', ]), cacheable=dict(type='bool'), redirecturl=dict(type='str'), clttimeout=dict(type='float'), precedence=dict(type='str', choices=[ 'RULE', 'URL', ]), casesensitive=dict(type='bool'), somethod=dict(type='str', choices=[ 'CONNECTION', 'DYNAMICCONNECTION', 'BANDWIDTH', 'HEALTH', 'NONE', ]), sopersistence=dict(type='str', choices=[ 'enabled', 'disabled', ]), sopersistencetimeout=dict(type='float'), sothreshold=dict(type='float'), sobackupaction=dict(type='str', choices=[ 'DROP', 'ACCEPT', 'REDIRECT', ]), redirectportrewrite=dict(type='str', choices=[ 'enabled', 'disabled', ]), downstateflush=dict(type='str', choices=[ 'enabled', 'disabled', ]), disableprimaryondown=dict(type='str', choices=[ 'enabled', 'disabled', ]), insertvserveripport=dict(type='str', choices=[ 'OFF', 'VIPADDR', 'V6TOV4MAPPING', ]), vipheader=dict(type='str'), rtspnat=dict(type='bool'), authenticationhost=dict(type='str'), authentication=dict(type='bool'), listenpolicy=dict(type='str'), authn401=dict(type='bool'), authnvsname=dict(type='str'), push=dict(type='str', choices=[ 'enabled', 'disabled', ]), pushvserver=dict(type='str'), pushlabel=dict(type='str'), pushmulticlients=dict(type='bool'), tcpprofilename=dict(type='str'), httpprofilename=dict(type='str'), dbprofilename=dict(type='str'), oracleserverversion=dict(type='str', choices=[ '10G', '11G', ]), comment=dict(type='str'), mssqlserverversion=dict(type='str', choices=[ '70', '2000', '2000SP1', '2005', '2008', '2008R2', '2012', '2014', ]), l2conn=dict(type='bool'), mysqlprotocolversion=dict(type='float'), mysqlserverversion=dict(type='str'), mysqlcharacterset=dict(type='float'), mysqlservercapabilities=dict(type='float'), appflowlog=dict(type='str', choices=[ 'enabled', 'disabled', ]), netprofile=dict(type='str'), icmpvsrresponse=dict(type='str', choices=[ 'PASSIVE', 'ACTIVE', ]), rhistate=dict(type='str', choices=[ 'PASSIVE', 'ACTIVE', ]), authnprofile=dict(type='str'), dnsprofilename=dict(type='str'), ) hand_inserted_arguments = dict( policybindings=dict(type='list'), ssl_certkey=dict(type='str'), disabled=dict(type='bool', default=False), lbvserver=dict(type='str'), ) argument_spec = dict() argument_spec.update(netscaler_common_arguments) argument_spec.update(module_specific_arguments) argument_spec.update(hand_inserted_arguments) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) module_result = dict( changed=False, failed=False, loglines=loglines, ) # Fail the module if imports failed if not PYTHON_SDK_IMPORTED: module.fail_json(msg='Could not load nitro python sdk') # Fallthrough to rest of execution client = get_nitro_client(module) try: client.login() except nitro_exception as e: msg = "nitro exception during login. errorcode=%s, message=%s" % (str( e.errorcode), e.message) module.fail_json(msg=msg) except Exception as e: if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>": module.fail_json(msg='Connection error %s' % str(e)) elif str(type(e)) == "<class 'requests.exceptions.SSLError'>": module.fail_json(msg='SSL Error %s' % str(e)) else: module.fail_json(msg='Unexpected error during login %s' % str(e)) readwrite_attrs = [ 'name', 'td', 'servicetype', 'ipv46', 'dnsrecordtype', 'ippattern', 'ipmask', 'range', 'port', 'stateupdate', 'cacheable', 'redirecturl', 'clttimeout', 'precedence', 'casesensitive', 'somethod', 'sopersistence', 'sopersistencetimeout', 'sothreshold', 'sobackupaction', 'redirectportrewrite', 'downstateflush', 'disableprimaryondown', 'insertvserveripport', 'vipheader', 'rtspnat', 'authenticationhost', 'authentication', 'listenpolicy', 'authn401', 'authnvsname', 'push', 'pushvserver', 'pushlabel', 'pushmulticlients', 'tcpprofilename', 'httpprofilename', 'dbprofilename', 'oracleserverversion', 'comment', 'mssqlserverversion', 'l2conn', 'mysqlprotocolversion', 'mysqlserverversion', 'mysqlcharacterset', 'mysqlservercapabilities', 'appflowlog', 'netprofile', 'icmpvsrresponse', 'rhistate', 'authnprofile', 'dnsprofilename', ] readonly_attrs = [ 'ip', 'value', 'ngname', 'type', 'curstate', 'sc', 'status', 'cachetype', 'redirect', 'homepage', 'dnsvservername', 'domain', 'policyname', 'servicename', 'weight', 'cachevserver', 'targetvserver', 'priority', 'url', 'gotopriorityexpression', 'bindpoint', 'invoke', 'labeltype', 'labelname', 'gt2gb', 'statechangetimesec', 'statechangetimemsec', 'tickssincelaststatechange', 'ruletype', 'lbvserver', 'targetlbvserver', ] immutable_attrs = [ 'name', 'td', 'servicetype', 'ipv46', 'targettype', 'range', 'port', 'state', 'vipheader', 'newname', ] transforms = { 'cacheable': ['bool_yes_no'], 'rtspnat': ['bool_on_off'], 'authn401': ['bool_on_off'], 'casesensitive': ['bool_on_off'], 'authentication': ['bool_on_off'], 'l2conn': ['bool_on_off'], 'pushmulticlients': ['bool_yes_no'], 'stateupdate': [lambda v: v.upper()], 'sopersistence': [lambda v: v.upper()], 'redirectportrewrite': [lambda v: v.upper()], 'downstateflush': [lambda v: v.upper()], 'disableprimaryondown': [lambda v: v.upper()], 'push': [lambda v: v.upper()], 'appflowlog': [lambda v: v.upper()], } # Instantiate config proxy csvserver_proxy = ConfigProxy( actual=csvserver(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, immutable_attrs=immutable_attrs, transforms=transforms, ) try: ensure_feature_is_enabled(client, 'CS') # Apply appropriate state if module.params['state'] == 'present': log('Applying actions for state present') if not cs_vserver_exists(client, module): if not module.check_mode: csvserver_proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not cs_vserver_identical(client, module, csvserver_proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection( csvserver_proxy, diff_list(client, module, csvserver_proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed, ), diff=diff_list(client, module, csvserver_proxy), **module_result) if not module.check_mode: csvserver_proxy.update() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Check policybindings if not cs_policybindings_identical(client, module): if not module.check_mode: sync_cs_policybindings(client, module) if module.params['save_config']: client.save_config() module_result['changed'] = True if module.params['servicetype'] != 'SSL' and module.params[ 'ssl_certkey'] is not None: module.fail_json( msg='ssl_certkey is applicable only to SSL vservers', **module_result) # Check ssl certkey bindings if module.params['servicetype'] == 'SSL': if not ssl_certkey_bindings_identical(client, module): if not module.check_mode: ssl_certkey_bindings_sync(client, module) module_result['changed'] = True # Check default lb vserver if not default_lb_vserver_identical(client, module): if not module.check_mode: sync_default_lb_vserver(client, module) module_result['changed'] = True if not module.check_mode: res = do_state_change(client, module, csvserver_proxy) if res.errorcode != 0: msg = 'Error when setting disabled state. errorcode: %s message: %s' % ( res.errorcode, res.message) module.fail_json(msg=msg, **module_result) # Sanity check for state if not module.check_mode: log('Sanity checks for state present') if not cs_vserver_exists(client, module): module.fail_json(msg='CS vserver does not exist', **module_result) if not cs_vserver_identical(client, module, csvserver_proxy): module.fail_json(msg='CS vserver differs from configured', diff=diff_list(client, module, csvserver_proxy), **module_result) if not cs_policybindings_identical(client, module): module.fail_json(msg='Policy bindings differ') if module.params['servicetype'] == 'SSL': if not ssl_certkey_bindings_identical(client, module): module.fail_json( msg='sll certkey bindings not identical', **module_result) elif module.params['state'] == 'absent': log('Applying actions for state absent') if cs_vserver_exists(client, module): if not module.check_mode: csvserver_proxy.delete() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state absent') if cs_vserver_exists(client, module): module.fail_json(msg='CS vserver still exists', **module_result) except nitro_exception as e: msg = "nitro exception errorcode=%s, message=%s" % (str( e.errorcode), e.message) module.fail_json(msg=msg, **module_result) client.logout() module.exit_json(**module_result)
def main(): module_specific_arguments = dict( name=dict(type='str'), ipaddress=dict(type='str'), domain=dict(type='str'), translationip=dict(type='str'), translationmask=dict(type='str'), domainresolveretry=dict(type='int'), ipv6address=dict( type='bool', default=False ), comment=dict(type='str'), td=dict(type='float'), graceful=dict(type='bool'), delay=dict(type='float') ) hand_inserted_arguments = dict( disabled=dict( type='bool', default=False, ), ) argument_spec = dict() argument_spec.update(netscaler_common_arguments) argument_spec.update(module_specific_arguments) argument_spec.update(hand_inserted_arguments) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) module_result = dict( changed=False, failed=False, loglines=loglines, ) # Fail the module if imports failed if not PYTHON_SDK_IMPORTED: module.fail_json(msg='Could not load nitro python sdk') # Fallthrough to rest of execution client = get_nitro_client(module) try: client.login() except nitro_exception as e: msg = "nitro exception during login. errorcode=%s, message=%s" % (str(e.errorcode), e.message) module.fail_json(msg=msg) except Exception as e: if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>": module.fail_json(msg='Connection error %s' % str(e)) elif str(type(e)) == "<class 'requests.exceptions.SSLError'>": module.fail_json(msg='SSL Error %s' % str(e)) else: module.fail_json(msg='Unexpected error during login %s' % str(e)) # Instantiate Server Config object readwrite_attrs = [ 'name', 'ipaddress', 'domain', 'translationip', 'translationmask', 'domainresolveretry', 'ipv6address', 'graceful', 'delay', 'comment', 'td', ] readonly_attrs = [ 'statechangetimesec', 'tickssincelaststatechange', 'autoscale', 'customserverid', 'monthreshold', 'maxclient', 'maxreq', 'maxbandwidth', 'usip', 'cka', 'tcpb', 'cmp', 'clttimeout', 'svrtimeout', 'cipheader', 'cip', 'cacheable', 'sc', 'sp', 'downstateflush', 'appflowlog', 'boundtd', '__count', ] immutable_attrs = [ 'name', 'domain', 'ipv6address', 'td', ] transforms = { 'graceful': ['bool_yes_no'], 'ipv6address': ['bool_yes_no'], } server_proxy = ConfigProxy( actual=server(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, immutable_attrs=immutable_attrs, transforms=transforms, ) try: # Apply appropriate state if module.params['state'] == 'present': log('Applying actions for state present') if not server_exists(client, module): if not module.check_mode: server_proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not server_identical(client, module, server_proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection(server_proxy, diff_list(client, module, server_proxy).keys()) if immutables_changed != []: msg = 'Cannot update immutable attributes %s' % (immutables_changed,) module.fail_json(msg=msg, diff=diff_list(client, module, server_proxy), **module_result) if not module.check_mode: server_proxy.update() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False if not module.check_mode: res = do_state_change(client, module, server_proxy) if res.errorcode != 0: msg = 'Error when setting disabled state. errorcode: %s message: %s' % (res.errorcode, res.message) module.fail_json(msg=msg, **module_result) # Sanity check for result log('Sanity checks for state present') if not module.check_mode: if not server_exists(client, module): module.fail_json(msg='Server does not seem to exist', **module_result) if not server_identical(client, module, server_proxy): module.fail_json( msg='Server is not configured according to parameters given', diff=diff_list(client, module, server_proxy), **module_result ) elif module.params['state'] == 'absent': log('Applying actions for state absent') if server_exists(client, module): if not module.check_mode: server_proxy.delete() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for result log('Sanity checks for state absent') if not module.check_mode: if server_exists(client, module): module.fail_json(msg='Server seems to be present', **module_result) except nitro_exception as e: msg = "nitro exception errorcode=%s, message=%s" % (str(e.errorcode), e.message) module.fail_json(msg=msg, **module_result) client.logout() module.exit_json(**module_result)
def server_exists(client, module): log('Checking if server exists') if server.count_filtered(client, 'name:%s' % module.params['name']) > 0: return True else: return False
def main(): module_specific_arguments = dict( servicegroupname=dict(type='str'), servicetype=dict( type='str', choices=[ 'HTTP', 'FTP', 'TCP', 'UDP', 'SSL', 'SSL_BRIDGE', 'SSL_TCP', 'DTLS', 'NNTP', 'RPCSVR', 'DNS', 'ADNS', 'SNMP', 'RTSP', 'DHCPRA', 'ANY', 'SIP_UDP', 'SIP_TCP', 'SIP_SSL', 'DNS_TCP', 'ADNS_TCP', 'MYSQL', 'MSSQL', 'ORACLE', 'RADIUS', 'RADIUSListener', 'RDP', 'DIAMETER', 'SSL_DIAMETER', 'TFTP', 'SMPP', 'PPTP', 'GRE', 'SYSLOGTCP', 'SYSLOGUDP', 'FIX', 'SSL_FIX', ] ), cachetype=dict( type='str', choices=[ 'TRANSPARENT', 'REVERSE', 'FORWARD', ] ), maxclient=dict(type='float'), maxreq=dict(type='float'), cacheable=dict(type='bool'), cip=dict( type='str', choices=[ 'enabled', 'disabled', ] ), cipheader=dict(type='str'), usip=dict(type='bool'), pathmonitor=dict(type='bool'), pathmonitorindv=dict(type='bool'), useproxyport=dict(type='bool'), healthmonitor=dict(type='bool'), sp=dict(type='bool'), rtspsessionidremap=dict(type='bool'), clttimeout=dict(type='float'), svrtimeout=dict(type='float'), cka=dict(type='bool'), tcpb=dict(type='bool'), cmp=dict(type='bool'), maxbandwidth=dict(type='float'), monthreshold=dict(type='float'), downstateflush=dict( type='str', choices=[ 'enabled', 'disabled', ] ), tcpprofilename=dict(type='str'), httpprofilename=dict(type='str'), comment=dict(type='str'), appflowlog=dict( type='str', choices=[ 'enabled', 'disabled', ] ), netprofile=dict(type='str'), autoscale=dict( type='str', choices=[ 'DISABLED', 'DNS', 'POLICY', ] ), memberport=dict(type='int'), graceful=dict(type='bool'), ) hand_inserted_arguments = dict( servicemembers=dict(type='list'), monitorbindings=dict(type='list'), disabled=dict( type='bool', default=False, ), ) argument_spec = dict() argument_spec.update(netscaler_common_arguments) argument_spec.update(module_specific_arguments) argument_spec.update(hand_inserted_arguments) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) module_result = dict( changed=False, failed=False, loglines=loglines, ) # Fail the module if imports failed if not PYTHON_SDK_IMPORTED: module.fail_json(msg='Could not load nitro python sdk') # Fallthrough to rest of execution client = get_nitro_client(module) try: client.login() except nitro_exception as e: msg = "nitro exception during login. errorcode=%s, message=%s" % (str(e.errorcode), e.message) module.fail_json(msg=msg) except Exception as e: if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>": module.fail_json(msg='Connection error %s' % str(e)) elif str(type(e)) == "<class 'requests.exceptions.SSLError'>": module.fail_json(msg='SSL Error %s' % str(e)) else: module.fail_json(msg='Unexpected error during login %s' % str(e)) # Instantiate service group configuration object readwrite_attrs = [ 'servicegroupname', 'servicetype', 'cachetype', 'maxclient', 'maxreq', 'cacheable', 'cip', 'cipheader', 'usip', 'pathmonitor', 'pathmonitorindv', 'useproxyport', 'healthmonitor', 'sp', 'rtspsessionidremap', 'clttimeout', 'svrtimeout', 'cka', 'tcpb', 'cmp', 'maxbandwidth', 'monthreshold', 'downstateflush', 'tcpprofilename', 'httpprofilename', 'comment', 'appflowlog', 'netprofile', 'autoscale', 'memberport', 'graceful', ] readonly_attrs = [ 'numofconnections', 'serviceconftype', 'value', 'svrstate', 'ip', 'monstatcode', 'monstatparam1', 'monstatparam2', 'monstatparam3', 'statechangetimemsec', 'stateupdatereason', 'clmonowner', 'clmonview', 'groupcount', 'riseapbrstatsmsgcode2', 'serviceipstr', 'servicegroupeffectivestate' ] immutable_attrs = [ 'servicegroupname', 'servicetype', 'cachetype', 'td', 'cipheader', 'state', 'autoscale', 'memberport', 'servername', 'port', 'serverid', 'monitor_name_svc', 'dup_weight', 'riseapbrstatsmsgcode', 'delay', 'graceful', 'includemembers', 'newname', ] transforms = { 'pathmonitorindv': ['bool_yes_no'], 'cacheable': ['bool_yes_no'], 'cka': ['bool_yes_no'], 'pathmonitor': ['bool_yes_no'], 'tcpb': ['bool_yes_no'], 'sp': ['bool_on_off'], 'usip': ['bool_yes_no'], 'healthmonitor': ['bool_yes_no'], 'useproxyport': ['bool_yes_no'], 'rtspsessionidremap': ['bool_on_off'], 'graceful': ['bool_yes_no'], 'cmp': ['bool_yes_no'], 'cip': [lambda v: v.upper()], 'downstateflush': [lambda v: v.upper()], 'appflowlog': [lambda v: v.upper()], } # Instantiate config proxy servicegroup_proxy = ConfigProxy( actual=servicegroup(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, immutable_attrs=immutable_attrs, transforms=transforms, ) try: if module.params['state'] == 'present': log('Applying actions for state present') if not servicegroup_exists(client, module): if not module.check_mode: log('Adding service group') servicegroup_proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not servicegroup_identical(client, module, servicegroup_proxy): # Check if we try to change value of immutable attributes diff_dict = diff(client, module, servicegroup_proxy) immutables_changed = get_immutables_intersection(servicegroup_proxy, diff_dict.keys()) if immutables_changed != []: msg = 'Cannot update immutable attributes %s. Must delete and recreate entity.' % (immutables_changed,) module.fail_json(msg=msg, diff=diff_dict, **module_result) if not module.check_mode: servicegroup_proxy.update() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Check bindings if not monitor_bindings_identical(client, module): if not module.check_mode: sync_monitor_bindings(client, module) if module.params['save_config']: client.save_config() module_result['changed'] = True if not servicemembers_identical(client, module): if not module.check_mode: sync_service_members(client, module) if module.params['save_config']: client.save_config() module_result['changed'] = True if not module.check_mode: res = do_state_change(client, module, servicegroup_proxy) if res.errorcode != 0: msg = 'Error when setting disabled state. errorcode: %s message: %s' % (res.errorcode, res.message) module.fail_json(msg=msg, **module_result) # Sanity check for state if not module.check_mode: log('Sanity checks for state present') if not servicegroup_exists(client, module): module.fail_json(msg='Service group is not present', **module_result) if not servicegroup_identical(client, module, servicegroup_proxy): module.fail_json( msg='Service group is not identical to configuration', diff=diff(client, module, servicegroup_proxy), **module_result ) if not servicemembers_identical(client, module): module.fail_json(msg='Service group members differ from configuration', **module_result) if not monitor_bindings_identical(client, module): module.fail_json(msg='Monitor bindings are not identical', **module_result) elif module.params['state'] == 'absent': log('Applying actions for state absent') if servicegroup_exists(client, module): if not module.check_mode: servicegroup_proxy.delete() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state absent') if servicegroup_exists(client, module): module.fail_json(msg='Service group is present', **module_result) except nitro_exception as e: msg = "nitro exception errorcode=" + str(e.errorcode) + ",message=" + e.message module.fail_json(msg=msg, **module_result) client.logout() module.exit_json(**module_result)
def main(): module_specific_arguments = dict( policyname=dict(type='str'), url=dict(type='str'), rule=dict(type='str'), domain=dict(type='str'), action=dict(type='str'), ) hand_inserted_arguments = dict() argument_spec = dict() argument_spec.update(netscaler_common_arguments) argument_spec.update(module_specific_arguments) argument_spec.update(hand_inserted_arguments) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) module_result = dict( changed=False, failed=False, loglines=loglines, ) # Fail the module if imports failed if not PYTHON_SDK_IMPORTED: module.fail_json(msg='Could not load nitro python sdk') # Fallthrough to rest of execution client = get_nitro_client(module) try: client.login() except nitro_exception as e: msg = "nitro exception during login. errorcode=%s, message=%s" % (str( e.errorcode), e.message) module.fail_json(msg=msg) except Exception as e: if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>": module.fail_json(msg='Connection error %s' % str(e)) elif str(type(e)) == "<class 'requests.exceptions.SSLError'>": module.fail_json(msg='SSL Error %s' % str(e)) else: module.fail_json(msg='Unexpected error during login %s' % str(e)) readwrite_attrs = [ 'policyname', 'url', 'rule', 'domain', 'action', ] readonly_attrs = [ 'vstype', 'hits', 'bindhits', 'labelname', 'labeltype', 'priority', 'activepolicy', 'cspolicytype', ] transforms = {} # Instantiate config proxy cspolicy_proxy = ConfigProxy( actual=cspolicy(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, transforms=transforms, ) try: ensure_feature_is_enabled(client, 'CS') # Apply appropriate state if module.params['state'] == 'present': log('Sanity checks for state present') if not policy_exists(client, module): if not module.check_mode: cspolicy_proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not policy_identical(client, module, cspolicy_proxy): if not module.check_mode: cspolicy_proxy.update() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state present') if not policy_exists(client, module): module.fail_json(msg='Policy does not exist', **module_result) if not policy_identical(client, module, cspolicy_proxy): module.fail_json(msg='Policy differs from configured', diff=diff_list(client, module, cspolicy_proxy), **module_result) elif module.params['state'] == 'absent': log('Applying actions for state absent') if policy_exists(client, module): if not module.check_mode: cspolicy_proxy.delete() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state absent') if policy_exists(client, module): module.fail_json(msg='Policy still exists', **module_result) except nitro_exception as e: msg = "nitro exception errorcode=%s, message=%s" % (str( e.errorcode), e.message) module.fail_json(msg=msg, **module_result) client.logout() module.exit_json(**module_result)
def main(): module_specific_arguments = dict( name=dict(type='str'), targetlbvserver=dict(type='str'), targetvserverexpr=dict(type='str'), comment=dict(type='str'), ) argument_spec = dict() argument_spec.update(netscaler_common_arguments) argument_spec.update(module_specific_arguments) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) module_result = dict(changed=False, failed=False, loglines=loglines) # Fail the module if imports failed if not PYTHON_SDK_IMPORTED: module.fail_json(msg='Could not load nitro python sdk') # Fallthrough to rest of execution client = get_nitro_client(module) try: client.login() except nitro_exception as e: msg = "nitro exception during login. errorcode=%s, message=%s" % (str( e.errorcode), e.message) module.fail_json(msg=msg) except Exception as e: if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>": module.fail_json(msg='Connection error %s' % str(e)) elif str(type(e)) == "<class 'requests.exceptions.SSLError'>": module.fail_json(msg='SSL Error %s' % str(e)) else: module.fail_json(msg='Unexpected error during login %s' % str(e)) readwrite_attrs = [ 'name', 'targetlbvserver', 'targetvserverexpr', 'comment', ] readonly_attrs = [ 'hits', 'referencecount', 'undefhits', 'builtin', ] immutable_attrs = [ 'name', 'targetvserverexpr', ] transforms = {} # Instantiate config proxy csaction_proxy = ConfigProxy( actual=csaction(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, immutable_attrs=immutable_attrs, transforms=transforms, ) try: ensure_feature_is_enabled(client, 'CS') # Apply appropriate state if module.params['state'] == 'present': log('Applying actions for state present') if not action_exists(client, module): if not module.check_mode: csaction_proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not action_identical(client, module, csaction_proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection( csaction_proxy, diff_list(client, module, csaction_proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed, ), diff=diff_list(client, module, csaction_proxy), **module_result) if not module.check_mode: csaction_proxy.update() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state log('Sanity checks for state present') if not module.check_mode: if not action_exists(client, module): module.fail_json( msg='Content switching action does not exist', **module_result) if not action_identical(client, module, csaction_proxy): module.fail_json( msg='Content switching action differs from configured', diff=diff_list(client, module, csaction_proxy), **module_result) elif module.params['state'] == 'absent': log('Applying actions for state absent') if action_exists(client, module): if not module.check_mode: csaction_proxy.delete() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state absent') if action_exists(client, module): module.fail_json( msg='Content switching action still exists', **module_result) except nitro_exception as e: msg = "nitro exception errorcode=%s, message=%s" % (str( e.errorcode), e.message) module.fail_json(msg=msg, **module_result) client.logout() module.exit_json(**module_result)
def main(): module_specific_arguments = dict( sitename=dict(type='str'), sitetype=dict( type='str', choices=[ 'REMOTE', 'LOCAL', ] ), siteipaddress=dict(type='str'), publicip=dict(type='str'), metricexchange=dict( type='str', choices=[ 'enabled', 'disabled', ] ), nwmetricexchange=dict( type='str', choices=[ 'enabled', 'disabled', ] ), sessionexchange=dict( type='str', choices=[ 'enabled', 'disabled', ] ), triggermonitor=dict( type='str', choices=[ 'ALWAYS', 'MEPDOWN', 'MEPDOWN_SVCDOWN', ] ), parentsite=dict(type='str'), clip=dict(type='str'), publicclip=dict(type='str'), naptrreplacementsuffix=dict(type='str'), ) hand_inserted_arguments = dict( ) argument_spec = dict() argument_spec.update(netscaler_common_arguments) argument_spec.update(module_specific_arguments) argument_spec.update(hand_inserted_arguments) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) module_result = dict( changed=False, failed=False, loglines=loglines, ) # Fail the module if imports failed if not PYTHON_SDK_IMPORTED: module.fail_json(msg='Could not load nitro python sdk') # Fallthrough to rest of execution client = get_nitro_client(module) try: client.login() except nitro_exception as e: msg = "nitro exception during login. errorcode=%s, message=%s" % (str(e.errorcode), e.message) module.fail_json(msg=msg) except Exception as e: if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>": module.fail_json(msg='Connection error %s' % str(e)) elif str(type(e)) == "<class 'requests.exceptions.SSLError'>": module.fail_json(msg='SSL Error %s' % str(e)) else: module.fail_json(msg='Unexpected error during login %s' % str(e)) readwrite_attrs = [ 'sitename', 'sitetype', 'siteipaddress', 'publicip', 'metricexchange', 'nwmetricexchange', 'sessionexchange', 'triggermonitor', 'parentsite', 'clip', 'publicclip', 'naptrreplacementsuffix', ] readonly_attrs = [ 'status', 'persistencemepstatus', 'version', '__count', ] immutable_attrs = [ 'sitename', 'sitetype', 'siteipaddress', 'publicip', 'parentsite', 'clip', 'publicclip', ] transforms = { 'metricexchange': [lambda v: v.upper()], 'nwmetricexchange': [lambda v: v.upper()], 'sessionexchange': [lambda v: v.upper()], } # Instantiate config proxy gslb_site_proxy = ConfigProxy( actual=gslbsite(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, immutable_attrs=immutable_attrs, transforms=transforms, ) try: ensure_feature_is_enabled(client, 'GSLB') # Apply appropriate state if module.params['state'] == 'present': log('Applying actions for state present') if not gslb_site_exists(client, module): if not module.check_mode: gslb_site_proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not gslb_site_identical(client, module, gslb_site_proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection(gslb_site_proxy, diff_list(client, module, gslb_site_proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed,), diff=diff_list(client, module, gslb_site_proxy), **module_result ) if not module.check_mode: gslb_site_proxy.update() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state present') if not gslb_site_exists(client, module): module.fail_json(msg='GSLB site does not exist', **module_result) if not gslb_site_identical(client, module, gslb_site_proxy): module.fail_json(msg='GSLB site differs from configured', diff=diff_list(client, module, gslb_site_proxy), **module_result) elif module.params['state'] == 'absent': log('Applying actions for state absent') if gslb_site_exists(client, module): if not module.check_mode: gslb_site_proxy.delete() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state absent') if gslb_site_exists(client, module): module.fail_json(msg='GSLB site still exists', **module_result) except nitro_exception as e: msg = "nitro exception errorcode=%s, message=%s" % (str(e.errorcode), e.message) module.fail_json(msg=msg, **module_result) client.logout() module.exit_json(**module_result)
def main(): module_specific_arguments = dict( certkey=dict(type='str'), cert=dict(type='str'), key=dict(type='str'), password=dict(type='bool'), inform=dict(type='str', choices=[ 'DER', 'PEM', 'PFX', ]), passplain=dict( type='str', no_log=True, ), expirymonitor=dict(type='str', choices=[ 'enabled', 'disabled', ]), notificationperiod=dict(type='float'), ) argument_spec = dict() argument_spec.update(netscaler_common_arguments) argument_spec.update(module_specific_arguments) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) module_result = dict( changed=False, failed=False, loglines=loglines, ) # Fail the module if imports failed if not PYTHON_SDK_IMPORTED: module.fail_json(msg='Could not load nitro python sdk') # Fallthrough to rest of execution client = get_nitro_client(module) try: client.login() except nitro_exception as e: msg = "nitro exception during login. errorcode=%s, message=%s" % (str( e.errorcode), e.message) module.fail_json(msg=msg) except Exception as e: if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>": module.fail_json(msg='Connection error %s' % str(e)) elif str(type(e)) == "<class 'requests.exceptions.SSLError'>": module.fail_json(msg='SSL Error %s' % str(e)) else: module.fail_json(msg='Unexpected error during login %s' % str(e)) readwrite_attrs = [ 'certkey', 'cert', 'key', 'password', 'inform', 'passplain', 'expirymonitor', 'notificationperiod', ] readonly_attrs = [ 'signaturealg', 'certificatetype', 'serial', 'issuer', 'clientcertnotbefore', 'clientcertnotafter', 'daystoexpiration', 'subject', 'publickey', 'publickeysize', 'version', 'priority', 'status', 'passcrypt', 'data', 'servicename', ] immutable_attrs = [ 'certkey', 'cert', 'key', 'password', 'inform', 'passplain', ] transforms = { 'expirymonitor': [lambda v: v.upper()], } # Instantiate config proxy sslcertkey_proxy = ConfigProxy( actual=sslcertkey(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, immutable_attrs=immutable_attrs, transforms=transforms, ) try: if module.params['state'] == 'present': log('Applying actions for state present') if not key_exists(client, module): if not module.check_mode: log('Adding certificate key') sslcertkey_proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not key_identical(client, module, sslcertkey_proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection( sslcertkey_proxy, diff_list(client, module, sslcertkey_proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed, ), diff=diff_list(client, module, sslcertkey_proxy), **module_result) if not module.check_mode: sslcertkey_proxy.update() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state present') if not key_exists(client, module): module.fail_json(msg='SSL certkey does not exist') if not key_identical(client, module, sslcertkey_proxy): module.fail_json(msg='SSL certkey differs from configured', diff=diff_list(client, module, sslcertkey_proxy)) elif module.params['state'] == 'absent': log('Applying actions for state absent') if key_exists(client, module): if not module.check_mode: sslcertkey_proxy.delete() if module.params['save_config']: client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state absent') if key_exists(client, module): module.fail_json(msg='SSL certkey still exists') except nitro_exception as e: msg = "nitro exception errorcode=%s, message=%s" % (str( e.errorcode), e.message) module.fail_json(msg=msg, **module_result) client.logout() module.exit_json(**module_result)
def sync_monitor_bindings(client, module): log('sync_monitor_bindings') actual_monitor_bindings = get_actual_monitor_bindings(client, module) configured_monitor_proxys = get_configured_monitor_bindings(client, module) # Delete actual bindings not in configured bindings for monitor_name, actual_binding in actual_monitor_bindings.items(): if monitor_name not in configured_monitor_proxys.keys(): log('Deleting absent binding for monitor %s' % monitor_name) log('dir is %s' % dir(actual_binding)) gslbservice_lbmonitor_binding.delete(client, actual_binding) # Delete and re-add actual bindings that differ from configured for proxy_key, binding_proxy in configured_monitor_proxys.items(): if proxy_key in actual_monitor_bindings: actual_binding = actual_monitor_bindings[proxy_key] if not binding_proxy.has_equal_attributes(actual_binding): log('Deleting differing binding for monitor %s' % actual_binding.monitor_name) log('dir %s' % dir(actual_binding)) log('attribute monitor_name %s' % getattr(actual_binding, 'monitor_name')) log('attribute monitorname %s' % getattr(actual_binding, 'monitorname', None)) gslbservice_lbmonitor_binding.delete(client, actual_binding) log('Adding anew binding for monitor %s' % binding_proxy.monitor_name) binding_proxy.add() # Add configured monitors that are missing from actual for proxy_key, binding_proxy in configured_monitor_proxys.items(): if proxy_key not in actual_monitor_bindings.keys(): log('Adding monitor binding for monitor %s' % binding_proxy.monitor_name) binding_proxy.add()