def sync_bindings(): delete_all_bindings() if 'servicebindings' in module.params and module.params['servicebindings'] is not None: for servicebinding in module.params['servicebindings']: attribute_values_dict = copy.deepcopy(servicebinding) readwrite_attrs = [ 'servicename', 'servicegroupname', 'weight', 'monitorname', ] attribute_values_dict['monitorname'] = module.params['monitorname'] readonly_attrs = [] binding_proxy = ConfigProxy( actual=lbmonitor_service_binding(), client=client, attribute_values_dict=attribute_values_dict, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) binding_proxy.add()
def main(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines try: from nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey import sslcertkey from nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding import sslvserver_sslcertkey_binding from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( certkey=dict(type='str'), cert=dict(type='str'), key=dict(type='str'), password=dict(type='bool'), fipskey=dict(type='str'), hsmkey=dict(type='str'), inform=dict(type='str', choices=[u'DER', u'PEM', u'PFX']), passplain=dict(type='str'), expirymonitor=dict(type='str', choices=[u'ENABLED', u'DISABLED']), notificationperiod=dict(type='float'), bundle=dict(type='str', choices=[u'YES', u'NO']), linkcertkeyname=dict(type='str'), nodomaincheck=dict(type='bool'), ) 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) client.login() # Instantiate Service Config object readwrite_attrs = [ 'certkey', 'cert', 'key', 'password', 'fipskey', 'hsmkey', 'inform', 'passplain', 'expirymonitor', 'notificationperiod', 'bundle', 'linkcertkeyname', 'nodomaincheck' ] readonly_attrs = [ 'signaturealg', 'certificatetype', 'serial', 'issuer', 'clientcertnotbefore', 'clientcertnotafter', 'daystoexpiration', 'subject', 'publickey', 'publickeysize', 'version', 'priority', 'status', 'passcrypt', 'data', 'servicename', ] sslcertkey_proxy = ConfigProxy( actual=sslcertkey(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) def key_exists(): log('Entering key_exists') log('certkey is %s' % module.params['certkey']) all_certificates = sslcertkey.get(client) certkeys = [item.certkey for item in all_certificates] if module.params['certkey'] in certkeys: return True else: return False def key_identical(): log('Entering key_identical') sslcertkey_list = sslcertkey.get_filtered( client, 'certkey:%s' % module.params['certkey']) diff_dict = sslcertkey_proxy.diff_object(sslcertkey_list[0]) if 'password' in diff_dict: del diff_dict['password'] if 'passplain' in diff_dict: del diff_dict['passplain'] if len(diff_dict) == 0: return True else: return False def diff_list(): sslcertkey_list = sslcertkey.get_filtered( client, 'certkey:%s' % module.params['certkey']) return sslcertkey_proxy.diff_object(sslcertkey_list[0]) try: # Apply appropriate operation if module.params['operation'] == 'present': log('Applying present operation') if not key_exists(): if not module.check_mode: log('Adding certificate key') sslcertkey_proxy.add() client.save_config() module_result['changed'] = True elif not key_identical(): if not module.check_mode: sslcertkey_proxy.update() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if not key_exists(): module.fail_json(msg='Service does not exist') if not key_identical(): module.fail_json(msg='Service differs from configured', diff=diff_list()) elif module.params['operation'] == 'absent': if key_exists(): if not module.check_mode: sslcertkey_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if key_exists(): module.fail_json(msg='Service still exists') 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( 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 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'), targettype=dict(type='str', choices=[ 'GSLB', ]), dnsrecordtype=dict(type='str', choices=[ 'A', 'AAAA', 'CNAME', 'NAPTR', ]), persistenceid=dict(type='float'), ippattern=dict(type='str'), ipmask=dict(type='str'), range=dict(type='float'), port=dict(type='int'), state=dict(type='str', choices=[ 'enabled', 'disabled', ]), 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', ]), backupvserver=dict(type='str'), 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'), listenpriority=dict(type='float'), 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'), domainname=dict(type='str'), ttl=dict(type='float'), backupip=dict(type='str'), cookiedomain=dict(type='str'), cookietimeout=dict(type='float'), sitedomainttl=dict(type='float'), newname=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 = [ 'name', 'td', 'servicetype', 'ipv46', 'targettype', 'dnsrecordtype', 'persistenceid', 'ippattern', 'ipmask', 'range', 'port', 'state', 'stateupdate', 'cacheable', 'redirecturl', 'clttimeout', 'precedence', 'casesensitive', 'somethod', 'sopersistence', 'sopersistencetimeout', 'sothreshold', 'sobackupaction', 'redirectportrewrite', 'downstateflush', 'backupvserver', 'disableprimaryondown', 'insertvserveripport', 'vipheader', 'rtspnat', 'authenticationhost', 'authentication', 'listenpolicy', 'listenpriority', 'authn401', 'authnvsname', 'push', 'pushvserver', 'pushlabel', 'pushmulticlients', 'tcpprofilename', 'httpprofilename', 'dbprofilename', 'oracleserverversion', 'comment', 'mssqlserverversion', 'l2conn', 'mysqlprotocolversion', 'mysqlserverversion', 'mysqlcharacterset', 'mysqlservercapabilities', 'appflowlog', 'netprofile', 'icmpvsrresponse', 'rhistate', 'authnprofile', 'dnsprofilename', 'domainname', 'ttl', 'backupip', 'cookiedomain', 'cookietimeout', 'sitedomainttl', 'newname', ] 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', '__count', ] 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'], } # Instantiate config proxy _proxy = ConfigProxy( actual=_(), 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, ' _') # Apply appropriate state if module.params['state'] == 'present': if not _exists(client, module): if not module.check_mode: _proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not _identical(client, module, _proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection( _proxy, diff_list(client, module, _proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed, ), diff=diff(client, module, _proxy), **module_result) if not module.check_mode: _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: if not _exists(client, module): module.fail_json(msg='_ does not exist', **module_result) if not _identical(client, module, _proxy): module.fail_json(msg='_ differs from configured', diff=diff(client, module, _proxy), **module_result) elif module.params['state'] == 'absent': if _exists(client, module): if not module.check_mode: _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: if _exists(client, module): module.fail_json(msg='_ 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( policyname=dict(type='str'), url=dict(type='str'), rule=dict(type='str'), domain=dict(type='str'), action=dict(type='str'), logaction=dict(type='str'), newname=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', 'logaction', 'newname', ] readonly_attrs = [ 'vstype', 'hits', 'bindhits', 'labelname', 'labeltype', 'priority', 'activepolicy', 'cspolicytype', '__count', ] immutable_attrs = [ 'policyname', 'newname', ] transforms = {} # Instantiate config proxy _proxy = ConfigProxy( actual=_(), 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, ' _') # Apply appropriate state if module.params['state'] == 'present': if not _exists(client, module): if not module.check_mode: _proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not _identical(client, module, _proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection( _proxy, diff_list(client, module, _proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed, ), diff=diff(client, module, _proxy), **module_result) if not module.check_mode: _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: if not _exists(client, module): module.fail_json(msg='_ does not exist', **module_result) if not _identical(client, module, _proxy): module.fail_json(msg='_ differs from configured', diff=diff(client, module, _proxy), **module_result) elif module.params['state'] == 'absent': if _exists(client, module): if not module.check_mode: _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: if _exists(client, module): module.fail_json(msg='_ 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( servicename=dict(type='str'), cnameentry=dict(type='str'), ip=dict(type='str'), servername=dict(type='str'), servicetype=dict(type='str', choices=[ 'HTTP', 'FTP', 'TCP', 'UDP', 'SSL', 'SSL_BRIDGE', 'SSL_TCP', 'NNTP', 'ANY', 'SIP_UDP', 'SIP_TCP', 'SIP_SSL', 'RADIUS', 'RDP', 'RTSP', 'MYSQL', 'MSSQL', 'ORACLE', ]), port=dict(type='int'), publicip=dict(type='str'), publicport=dict(type='int'), maxclient=dict(type='float'), healthmonitor=dict(type='bool'), sitename=dict(type='str'), state=dict(type='str', choices=[ 'enabled', 'disabled', ]), cip=dict(type='str', choices=[ 'enabled', 'disabled', ]), cipheader=dict(type='str'), sitepersistence=dict(type='str', choices=[ 'ConnectionProxy', 'HTTPRedirect', 'NONE', ]), cookietimeout=dict(type='float'), siteprefix=dict(type='str'), clttimeout=dict(type='float'), svrtimeout=dict(type='float'), maxbandwidth=dict(type='float'), downstateflush=dict(type='str', choices=[ 'enabled', 'disabled', ]), maxaaausers=dict(type='float'), monthreshold=dict(type='float'), hashid=dict(type='float'), comment=dict(type='str'), appflowlog=dict(type='str', choices=[ 'enabled', 'disabled', ]), naptrreplacement=dict(type='str'), naptrorder=dict(type='float'), naptrservices=dict(type='str'), naptrdomainttl=dict(type='float'), naptrpreference=dict(type='float'), ipaddress=dict(type='str'), viewname=dict(type='str'), viewip=dict(type='str'), weight=dict(type='float'), monitor_name_svc=dict(type='str'), newname=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 = [ 'servicename', 'cnameentry', 'ip', 'servername', 'servicetype', 'port', 'publicip', 'publicport', 'maxclient', 'healthmonitor', 'sitename', 'state', 'cip', 'cipheader', 'sitepersistence', 'cookietimeout', 'siteprefix', 'clttimeout', 'svrtimeout', 'maxbandwidth', 'downstateflush', 'maxaaausers', 'monthreshold', 'hashid', 'comment', 'appflowlog', 'naptrreplacement', 'naptrorder', 'naptrservices', 'naptrdomainttl', 'naptrpreference', 'ipaddress', 'viewname', 'viewip', 'weight', 'monitor_name_svc', 'newname', ] readonly_attrs = [ 'gslb', 'svrstate', 'svreffgslbstate', 'gslbthreshold', 'gslbsvcstats', 'monstate', 'preferredlocation', 'monitor_state', 'statechangetimesec', 'tickssincelaststatechange', 'threshold', 'clmonowner', 'clmonview', '__count', ] immutable_attrs = [ 'servicename', 'cnameentry', 'ip', 'servername', 'servicetype', 'port', 'sitename', 'state', 'cipheader', 'cookietimeout', 'clttimeout', 'svrtimeout', 'viewip', 'monitor_name_svc', 'newname', ] transforms = { 'healthmonitor': ['bool_yes_no'], } # Instantiate config proxy _proxy = ConfigProxy( actual=_(), 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, ' _') # Apply appropriate state if module.params['state'] == 'present': if not _exists(client, module): if not module.check_mode: _proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not _identical(client, module, _proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection( _proxy, diff_list(client, module, _proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed, ), diff=diff(client, module, _proxy), **module_result) if not module.check_mode: _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: if not _exists(client, module): module.fail_json(msg='_ does not exist', **module_result) if not _identical(client, module, _proxy): module.fail_json(msg='_ differs from configured', diff=diff(client, module, _proxy), **module_result) elif module.params['state'] == 'absent': if _exists(client, module): if not module.check_mode: _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: if _exists(client, module): module.fail_json(msg='_ 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'), ) 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', '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 = { '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 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(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines try: from nssrc.com.citrix.netscaler.nitro.resource.config.basic.service import service from nssrc.com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding import service_lbmonitor_binding from nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonitor_service_binding import lbmonitor_service_binding from nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonbindings_service_binding import lbmonbindings_service_binding from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( name=dict( type='str',), ip=dict(type='str'), servicetype=dict( type='str', choices=[u'HTTP', u'FTP', u'TCP', u'UDP', u'SSL', u'SSL_BRIDGE', u'SSL_TCP', u'DTLS', u'NNTP', u'RPCSVR', u'DNS', u'ADNS', u'SNMP', u'RTSP', u'DHCPRA', u'ANY', u'SIP_UDP', u'SIP_TCP', u'SIP_SSL', u'DNS_TCP', u'ADNS_TCP', u'MYSQL', u'MSSQL', u'ORACLE', u'RADIUS', u'RADIUSListener', u'RDP', u'DIAMETER', u'SSL_DIAMETER', u'TFTP', u'SMPP', u'PPTP', u'GRE', u'SYSLOGTCP', u'SYSLOGUDP', u'FIX', u'SSL_FIX'] ), port=dict(type='int'), cleartextport=dict(type='int'), cachetype=dict( type='str', choices=[u'TRANSPARENT', u'REVERSE', u'FORWARD'] ), maxclient=dict(type='float'), healthmonitor=dict( type='str', choices=[u'YES', u'NO'] ), maxreq=dict(type='float'), cacheable=dict( type='str', choices=[u'YES', u'NO'] ), cip=dict( type='str', choices=[u'ENABLED', u'DISABLED'] ), cipheader=dict(type='str'), usip=dict( type='str', choices=[u'YES', u'NO'] ), useproxyport=dict( type='str', choices=[u'YES', u'NO'] ), sc=dict( type='str', choices=[u'ON', u'OFF'] ), sp=dict( type='str', choices=[u'ON', u'OFF'] ), rtspsessionidremap=dict( type='str', choices=[u'ON', u'OFF'] ), clttimeout=dict(type='float'), svrtimeout=dict(type='float'), customserverid=dict(type='str'), cka=dict( type='str', choices=[u'YES', u'NO'] ), tcpb=dict( type='str', choices=[u'YES', u'NO'] ), cmp=dict( type='str', choices=[u'YES', u'NO'] ), maxbandwidth=dict(type='float'), accessdown=dict( type='str', choices=[u'YES', u'NO'] ), monthreshold=dict(type='float'), downstateflush=dict( type='str', choices=[u'ENABLED', u'DISABLED'] ), tcpprofilename=dict(type='str'), httpprofilename=dict(type='str'), hashid=dict(type='float'), comment=dict(type='str'), appflowlog=dict( type='str', choices=[u'ENABLED', u'DISABLED'] ), netprofile=dict(type='str'), processlocal=dict( type='str', choices=[u'ENABLED', u'DISABLED'] ), dnsprofilename=dict(type='str'), ipaddress=dict(type='str'), graceful=dict( type='str', choices=[u'YES', u'NO'] ), ) hand_inserted_arguments = dict( monitorbindings=dict(type='list'), ) 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) client.login() # Instantiate Service Config object readwrite_attrs = [ 'name', 'ip', 'servicetype', 'port', 'cleartextport', 'cachetype', 'maxclient', 'healthmonitor', 'maxreq', 'cacheable', 'cip', 'cipheader', 'usip', 'useproxyport', 'sc', 'sp', 'rtspsessionidremap', 'clttimeout', 'svrtimeout', 'customserverid', 'cka', 'tcpb', 'cmp', 'maxbandwidth', 'accessdown', 'monthreshold', 'downstateflush', 'tcpprofilename', 'httpprofilename', 'hashid', 'comment', 'appflowlog', 'netprofile', 'processlocal', 'dnsprofilename', 'ipaddress', 'graceful', ] readonly_attrs = [ 'numofconnections', 'policyname', 'serviceconftype', 'serviceconftype2', 'value', 'gslb', 'dup_state', 'publicip', 'publicport', 'svrstate', 'monitor_state', 'monstatcode', 'lastresponse', 'responsetime', 'riseapbrstatsmsgcode2', 'monstatparam1', 'monstatparam2', 'monstatparam3', 'statechangetimesec', 'statechangetimemsec', 'tickssincelaststatechange', 'stateupdatereason', 'clmonowner', 'clmonview', 'serviceipstr', 'oracleserverversion', ] # Translate module arguments to correspondign config oject attributes if module.params['ip'] is None: module.params['ip'] = module.params['ipaddress'] service_proxy = ConfigProxy( actual=service(), client=client, attribute_values_dict = module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) def service_exists(): if service.count_filtered(client, 'name:%s' % module.params['name']) > 0: return True else: return False def service_identical(): service_list = service.get_filtered(client, 'name:%s' % module.params['name']) diff_dict = service_proxy.diff_object(service_list[0]) log('other ipaddress is %s' % service_list[0].ipaddress) # the actual ip address is stored in the ipaddress attribute # of the retrieved object if 'ip' in diff_dict: del diff_dict['ip'] if len(diff_dict) == 0: return True else: return False def diff_list(): service_list = service.get_filtered(client, 'name:%s' % module.params['name']) diff_object = service_proxy.diff_object(service_list[0]) if 'ip' in diff_object: del diff_object['ip'] return diff_object def get_configured_monitor_bindings(): 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', 'servicename', ] readonly_attrs = [] if isinstance(binding, dict): attribute_values_dict = copy.deepcopy(binding) else: attribute_values_dict = { 'monitorname': binding } attribute_values_dict['servicename'] = module.params['name'] binding_proxy = ConfigProxy( actual=lbmonitor_service_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_actual_monitor_bindings(): log('Entering get_actual_monitor_bindings') bindings = {} if service_lbmonitor_binding.count(client, module.params['name']) == 0: return bindings # Fallthrough to rest of execution for binding in service_lbmonitor_binding.get(client, module.params['name']): log('Gettign actual monitor with name %s' % binding.monitor_name) key = binding.monitor_name bindings[key] = binding return bindings def monitor_bindings_identical(): log('Entering monitor_bindings_identical') configured_bindings = get_configured_monitor_bindings() actual_bindings = get_actual_monitor_bindings() 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] if any([configured_proxy.monitorname != actual_bindings[key].monitor_name, configured_proxy.servicename != actual_bindings[key].name]): return False # Fallthrought to success return True def sync_monitor_bindings(): log('Entering sync_monitor_bindings') # Delete existing bindings for binding in get_actual_monitor_bindings().values(): b = lbmonitor_service_binding() b.monitorname = binding.monitor_name b.servicename = module.params['name'] # Cannot remove default monitor bindings if b.monitorname in ('tcp-default', 'ping-default'): continue lbmonitor_service_binding.delete(client, b) continue binding.monitorname = binding.monitor_name log('Will delete %s' % dir(binding)) log('Name %s' % binding.name) log('monitor Name %s' % binding.monitor_name) binding.delete(client, binding) #service_lbmonitor_binding.delete(client, binding) # Apply configured bindings for binding in get_configured_monitor_bindings().values(): binding.add() try: # Apply appropriate operation if module.params['operation'] == 'present': if not service_exists(): if not module.check_mode: service_proxy.add() service_proxy.update() client.save_config() module_result['changed'] = True elif not service_identical(): if not module.check_mode: service_proxy.update() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Check bindings if not monitor_bindings_identical(): if not module.check_mode: sync_monitor_bindings() client.save_config() module_result['changed'] = True # Sanity check for operation if not service_exists(): module.fail_json(msg='Service does not exist', **module_result) if not service_identical(): module.fail_json(msg='Service differs from configured', diff=diff_list(), **module_result) if not monitor_bindings_identical(): module.fail_json(msg='Monitor bindings are not identical', **module_result) elif module.params['operation'] == 'absent': if service_exists(): if not module.check_mode: service_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if service_exists(): module.fail_json(msg='Service still exists', **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(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines try: from nssrc.com.citrix.netscaler.nitro.resource.config.basic.server import server from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( name=dict(type='str'), ipaddress=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) client.login() # Instantiate Server Config object readwrite_attrs = ['name', 'ip', 'ipaddress'] readonly_attrs = [] equivalent_attributes = { 'ip': [ 'ipaddress', ] } server_proxy = ConfigProxy( actual=server(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) def server_exists(): if server.count_filtered(client, 'name:%s' % module.params['name']) > 0: return True else: return False def server_identical(): if server.count_filtered(client, 'name:%s' % module.params['name']) == 0: return False server_list = server.get_filtered(client, 'name:%s' % module.params['name']) if server_proxy.has_equal_attributes(server_list[0]): return True else: return False def diff_list(): return server_proxy.diff_object( server.get_filtered(client, 'name:%s' % module.params['name'])[0]), try: # Apply appropriate operation if module.params['operation'] == 'present': if not server_exists(): if not module.check_mode: server_proxy.add() server_proxy.update() client.save_config() module_result['changed'] = True elif not server_identical(): if not module.check_mode: server_proxy.update() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for result if not module.check_mode: if not server_exists(): module.fail_json(msg='Server does not seem to exist', **module_result) if not server_identical(): module.fail_json( msg= 'Server is not configured according to parameters given', diff=diff_list(), **module_result) elif module.params['operation'] == 'absent': if server_exists(): if not module.check_mode: server_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for result if not module.check_mode: if server_exists(): module.fail_json(msg='Server seems to be present', **module_result) module_result[ 'actual_attributes'] = server_proxy.get_actual_rw_attributes() 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(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines try: from nssrc.com.citrix.netscaler.nitro.resource.config.basic.service import service from nssrc.com.citrix.netscaler.nitro.resource.stat.basic.service_stats import service_stats from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( name=dict(type='str', ), ip=dict(type='str', ), servername=dict(type='str', ), servicetype=dict( type='str', choices=[ u'HTTP', u'FTP', u'TCP', u'UDP', u'SSL', u'SSL_BRIDGE', u'SSL_TCP', u'DTLS', u'NNTP', u'RPCSVR', u'DNS', u'ADNS', u'SNMP', u'RTSP', u'DHCPRA', u'ANY', u'SIP_UDP', u'SIP_TCP', u'SIP_SSL', u'DNS_TCP', u'ADNS_TCP', u'MYSQL', u'MSSQL', u'ORACLE', u'RADIUS', u'RADIUSListener', u'RDP', u'DIAMETER', u'SSL_DIAMETER', u'TFTP', u'SMPP', u'PPTP', u'GRE', u'SYSLOGTCP', u'SYSLOGUDP', u'FIX', u'SSL_FIX' ]), port=dict(type='int', ), cleartextport=dict(type='int', ), cachetype=dict(type='str', choices=[u'TRANSPARENT', u'REVERSE', u'FORWARD']), maxclient=dict(type='float', ), healthmonitor=dict(type='str', choices=[u'YES', u'NO']), maxreq=dict(type='float', ), cacheable=dict(type='str', choices=[u'YES', u'NO']), cip=dict(type='str', choices=[u'ENABLED', u'DISABLED']), cipheader=dict(type='str', ), usip=dict(type='str', choices=[u'YES', u'NO']), pathmonitor=dict(type='str', choices=[u'YES', u'NO']), pathmonitorindv=dict(type='str', choices=[u'YES', u'NO']), useproxyport=dict(type='str', choices=[u'YES', u'NO']), sc=dict(type='str', choices=[u'ON', u'OFF']), sp=dict(type='str', choices=[u'ON', u'OFF']), rtspsessionidremap=dict(type='str', choices=[u'ON', u'OFF']), clttimeout=dict(type='float', ), svrtimeout=dict(type='float', ), customserverid=dict(type='str', ), serverid=dict(type='float', ), cka=dict(type='str', choices=[u'YES', u'NO']), tcpb=dict(type='str', choices=[u'YES', u'NO']), cmp=dict(type='str', choices=[u'YES', u'NO']), maxbandwidth=dict(type='float', ), accessdown=dict(type='str', choices=[u'YES', u'NO']), monthreshold=dict(type='float', ), state=dict(type='str', choices=[u'ENABLED', u'DISABLED']), downstateflush=dict(type='str', choices=[u'ENABLED', u'DISABLED']), tcpprofilename=dict(type='str', ), httpprofilename=dict(type='str', ), hashid=dict(type='float', ), comment=dict(type='str', ), appflowlog=dict(type='str', choices=[u'ENABLED', u'DISABLED']), netprofile=dict(type='str', ), td=dict(type='float', ), processlocal=dict(type='str', choices=[u'ENABLED', u'DISABLED']), dnsprofilename=dict(type='str', ), ipaddress=dict(type='str', ), weight=dict(type='float', ), monitor_name_svc=dict(type='str', ), riseapbrstatsmsgcode=dict(type='int', ), delay=dict(type='float', ), graceful=dict(type='str', choices=[u'YES', u'NO']), all=dict(type='bool', ), Internal=dict(type='bool', ), newname=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, ) # 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) client.login() # Instantiate Service Config object readwrite_attrs = [ u'name', u'ip', u'servername', u'servicetype', u'port', u'cleartextport', u'cachetype', u'maxclient', u'healthmonitor', u'maxreq', u'cacheable', u'cip', u'cipheader', u'usip', u'pathmonitor', u'pathmonitorindv', u'useproxyport', u'sc', u'sp', u'rtspsessionidremap', u'clttimeout', u'svrtimeout', u'customserverid', u'serverid', u'cka', u'tcpb', u'cmp', u'maxbandwidth', u'accessdown', u'monthreshold', u'state', u'downstateflush', u'tcpprofilename', u'httpprofilename', u'hashid', u'comment', u'appflowlog', u'netprofile', u'td', u'processlocal', u'dnsprofilename', u'monconnectionclose', u'ipaddress', u'weight', u'monitor_name_svc', u'riseapbrstatsmsgcode', u'delay', u'graceful', u'all', u'Internal', u'newname' ] readonly_attrs = [ u'numofconnections', u'policyname', u'serviceconftype', u'serviceconftype2', u'value', u'gslb', u'dup_state', u'publicip', u'publicport', u'svrstate', u'monitor_state', u'monstatcode', u'lastresponse', u'responsetime', u'riseapbrstatsmsgcode2', u'monstatparam1', u'monstatparam2', u'monstatparam3', u'statechangetimesec', u'statechangetimemsec', u'tickssincelaststatechange', u'stateupdatereason', u'clmonowner', u'clmonview', u'serviceipstr', u'oracleserverversion', u'__count' ] service_proxy = ConfigProxy( actual=service(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) def service_exists(): if service.count_filtered(client, 'name:%s' % module.params['name']) > 0: return True else: return False def service_identical(): service_list = service.get_filtered(client, 'name:%s' % module.params['name']) diff_dict = service_proxy.diff_object(service_list[0]) if 'ip' in diff_dict: del diff_dict['ip'] if len(diff_dict) == 0: return True else: return False def diff_list(): service_list = service.get_filtered(client, 'name:%s' % module.params['name']) return service_proxy.diff_object(service_list[0]) try: # Apply appropriate operation if module.params['operation'] == 'present': if not service_exists(): if not module.check_mode: service_proxy.add() client.save_config() module_result['changed'] = True elif not service_identical(): if not module.check_mode: service_proxy.update() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if not service_exists(): module.fail_json(msg='Service does not exist') if not service_identical(): module.fail_json(msg='Service differs from configured', diff=diff_list()) elif module.params['operation'] == 'absent': if service_exists(): if not module.check_mode: service_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if service_exists(): module.fail_json(msg='Service still exists') 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( name=dict(type='str'), servicetype=dict( type='str', choices=[ 'HTTP', 'FTP', 'TCP', 'UDP', 'SSL', 'SSL_BRIDGE', 'SSL_TCP', 'NNTP', 'ANY', 'SIP_UDP', 'SIP_TCP', 'SIP_SSL', 'RADIUS', 'RDP', 'RTSP', 'MYSQL', 'MSSQL', 'ORACLE', ] ), dnsrecordtype=dict( type='str', choices=[ 'A', 'AAAA', 'CNAME', 'NAPTR', ] ), lbmethod=dict( type='str', choices=[ 'ROUNDROBIN', 'LEASTCONNECTION', 'LEASTRESPONSETIME', 'SOURCEIPHASH', 'LEASTBANDWIDTH', 'LEASTPACKETS', 'STATICPROXIMITY', 'RTT', 'CUSTOMLOAD', ] ), backuplbmethod=dict( type='str', choices=[ 'ROUNDROBIN', 'LEASTCONNECTION', 'LEASTRESPONSETIME', 'SOURCEIPHASH', 'LEASTBANDWIDTH', 'LEASTPACKETS', 'STATICPROXIMITY', 'RTT', 'CUSTOMLOAD', ] ), netmask=dict(type='str'), v6netmasklen=dict(type='float'), tolerance=dict(type='float'), persistencetype=dict( type='str', choices=[ 'SOURCEIP', 'NONE', ] ), persistenceid=dict(type='float'), persistmask=dict(type='str'), v6persistmasklen=dict(type='float'), timeout=dict(type='float'), mir=dict( type='str', choices=[ 'enabled', 'disabled', ] ), disableprimaryondown=dict( type='str', choices=[ 'enabled', 'disabled', ] ), dynamicweight=dict( type='str', choices=[ 'SERVICECOUNT', 'SERVICEWEIGHT', 'DISABLED', ] ), considereffectivestate=dict( type='str', choices=[ 'NONE', 'STATE_ONLY', ] ), comment=dict(type='str'), 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', ] ), appflowlog=dict( type='str', choices=[ 'enabled', 'disabled', ] ), domainname=dict(type='str'), cookie_domain=dict(type='str'), ) hand_inserted_arguments = dict( domain_bindings=dict(type='list'), service_bindings=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)) readwrite_attrs = [ 'name', 'servicetype', 'dnsrecordtype', 'lbmethod', 'backuplbmethod', 'netmask', 'v6netmasklen', 'tolerance', 'persistencetype', 'persistenceid', 'persistmask', 'v6persistmasklen', 'timeout', 'mir', 'disableprimaryondown', 'dynamicweight', 'considereffectivestate', 'comment', 'somethod', 'sopersistence', 'sopersistencetimeout', 'sothreshold', 'sobackupaction', 'appflowlog', 'cookie_domain', ] readonly_attrs = [ 'curstate', 'status', 'lbrrreason', 'iscname', 'sitepersistence', 'totalservices', 'activeservices', 'statechangetimesec', 'statechangetimemsec', 'tickssincelaststatechange', 'health', 'policyname', 'priority', 'gotopriorityexpression', 'type', 'vsvrbindsvcip', 'vsvrbindsvcport', '__count', ] immutable_attrs = [ 'name', 'servicetype', ] transforms = { 'mir': [lambda v: v.upper()], 'disableprimaryondown': [lambda v: v.upper()], 'sopersistence': [lambda v: v.upper()], 'appflowlog': [lambda v: v.upper()], } # Instantiate config proxy gslb_vserver_proxy = ConfigProxy( actual=gslbvserver(), 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 state present') if not gslb_vserver_exists(client, module): log('Creating object') if not module.check_mode: gslb_vserver_proxy.add() sync_domain_bindings(client, module) sync_service_bindings(client, module) if module.params['save_config']: client.save_config() module_result['changed'] = True elif not all_identical(client, module, gslb_vserver_proxy): log('Entering update actions') # Check if we try to change value of immutable attributes if not gslb_vserver_identical(client, module, gslb_vserver_proxy): log('Updating gslb vserver') immutables_changed = get_immutables_intersection(gslb_vserver_proxy, diff_list(client, module, gslb_vserver_proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed,), diff=diff_list(client, module, gslb_vserver_proxy), **module_result ) if not module.check_mode: gslb_vserver_proxy.update() # Update domain bindings if not domain_bindings_identical(client, module): if not module.check_mode: sync_domain_bindings(client, module) # Update service bindings if not service_bindings_identical(client, module): if not module.check_mode: sync_service_bindings(client, module) module_result['changed'] = True if not module.check_mode: if module.params['save_config']: client.save_config() else: module_result['changed'] = False if not module.check_mode: res = do_state_change(client, module, gslb_vserver_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: if not gslb_vserver_exists(client, module): module.fail_json(msg='GSLB Vserver does not exist', **module_result) if not gslb_vserver_identical(client, module, gslb_vserver_proxy): module.fail_json(msg='GSLB Vserver differs from configured', diff=diff_list(client, module, gslb_vserver_proxy), **module_result) if not domain_bindings_identical(client, module): module.fail_json(msg='Domain bindings differ from configured', diff=diff_list(client, module, gslb_vserver_proxy), **module_result) if not service_bindings_identical(client, module): module.fail_json(msg='Service bindings differ from configured', diff=diff_list(client, module, gslb_vserver_proxy), **module_result) elif module.params['state'] == 'absent': if gslb_vserver_exists(client, module): if not module.check_mode: gslb_vserver_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: if gslb_vserver_exists(client, module): module.fail_json(msg='GSLB 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( 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 main(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines, ensure_feature_is_enabled try: from nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver import csvserver from nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver_cspolicy_binding import csvserver_cspolicy_binding from nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding import sslvserver_sslcertkey_binding from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( name=dict(type='str'), td=dict(type='float'), servicetype=dict(type='str', choices=[ u'HTTP', u'SSL', u'TCP', u'FTP', u'RTSP', u'SSL_TCP', u'UDP', u'DNS', u'SIP_UDP', u'SIP_TCP', u'SIP_SSL', u'ANY', u'RADIUS', u'RDP', u'MYSQL', u'MSSQL', u'DIAMETER', u'SSL_DIAMETER', u'DNS_TCP', u'ORACLE', u'SMPP' ]), ipv46=dict(type='str'), dnsrecordtype=dict(type='str', choices=[u'A', u'AAAA', u'CNAME', u'NAPTR']), ippattern=dict(type='str'), ipmask=dict(type='str'), range=dict(type='float'), port=dict(type='int'), stateupdate=dict(type='str', choices=[u'ENABLED', u'DISABLED']), cacheable=dict(type='str', choices=[u'YES', u'NO']), redirecturl=dict(type='str'), clttimeout=dict(type='float'), precedence=dict(type='str', choices=[u'RULE', u'URL']), casesensitive=dict(type='str', choices=[u'ON', u'OFF']), somethod=dict(type='str', choices=[ u'CONNECTION', u'DYNAMICCONNECTION', u'BANDWIDTH', u'HEALTH', u'NONE' ]), sopersistence=dict(type='str', choices=[u'ENABLED', u'DISABLED']), sopersistencetimeout=dict(type='float'), sothreshold=dict(type='float'), sobackupaction=dict(type='str', choices=[u'DROP', u'ACCEPT', u'REDIRECT']), redirectportrewrite=dict(type='str', choices=[u'ENABLED', u'DISABLED']), downstateflush=dict(type='str', choices=[u'ENABLED', u'DISABLED']), disableprimaryondown=dict(type='str', choices=[u'ENABLED', u'DISABLED']), insertvserveripport=dict( type='str', choices=[u'OFF', u'VIPADDR', u'V6TOV4MAPPING']), vipheader=dict(type='str'), rtspnat=dict(type='str', choices=[u'ON', u'OFF']), authenticationhost=dict(type='str'), authentication=dict(type='str', choices=[u'ON', u'OFF']), listenpolicy=dict(type='str'), authn401=dict(type='str', choices=[u'ON', u'OFF']), authnvsname=dict(type='str'), push=dict(type='str', choices=[u'ENABLED', u'DISABLED']), pushvserver=dict(type='str'), pushlabel=dict(type='str'), pushmulticlients=dict(type='str', choices=[u'YES', u'NO']), tcpprofilename=dict(type='str'), httpprofilename=dict(type='str'), dbprofilename=dict(type='str'), oracleserverversion=dict(type='str', choices=[u'10G', u'11G']), comment=dict(type='str'), mssqlserverversion=dict(type='str', choices=[ u'70', u'2000', u'2000SP1', u'2005', u'2008', u'2008R2', u'2012', u'2014' ]), l2conn=dict(type='str', choices=[u'ON', u'OFF']), mysqlprotocolversion=dict(type='float'), mysqlserverversion=dict(type='str'), mysqlcharacterset=dict(type='float'), mysqlservercapabilities=dict(type='float'), appflowlog=dict(type='str', choices=[u'ENABLED', u'DISABLED']), netprofile=dict(type='str'), icmpvsrresponse=dict(type='str', choices=[u'PASSIVE', u'ACTIVE']), rhistate=dict(type='str', choices=[u'PASSIVE', u'ACTIVE']), authnprofile=dict(type='str'), dnsprofilename=dict(type='str'), ) hand_inserted_arguments = dict( policybindings=dict(type='list'), ssl_certkey=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) client.login() # Instantiate Service Config object 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', ] csvserver_proxy = ConfigProxy( actual=csvserver(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) def cs_vserver_exists(): if csvserver.count_filtered(client, 'name:%s' % module.params['name']) > 0: return True else: return False def cs_vserver_identical(): csvserver_list = csvserver.get_filtered( client, 'name:%s' % module.params['name']) diff_dict = csvserver_proxy.diff_object(csvserver_list[0]) if len(diff_dict) == 0: return True else: return False def get_configured_policybindings(): bindings = {} if module.params['policybindings'] is None: return bindings for binding in module.params['policybindings']: binding['name'] = module.params['name'] key = binding['policyname'] binding_proxy = ConfigProxy(actual=csvserver_cspolicy_binding(), client=client, readwrite_attrs=[ 'priority', 'bindpoint', 'policyname', 'labelname', 'name', 'gotopriorityexpression', 'targetlbvserver', 'invoke', 'labeltype', ], readonly_attrs=[], attribute_values_dict=binding) bindings[key] = binding_proxy return bindings def get_actual_policybindings(): bindings = {} if csvserver_cspolicy_binding.count(client, name=module.params['name']) == 0: return bindings for binding in csvserver_cspolicy_binding.get( client, name=module.params['name']): key = binding.policyname bindings[key] = binding return bindings def cs_policybindings_identical(): actual_bindings = get_actual_policybindings() configured_bindings = get_configured_policybindings() 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 sync_cs_policybindings(): # Delete all actual bindings for binding in get_actual_policybindings().values(): csvserver_cspolicy_binding.delete(client, binding) # Add all configured bindings for binding in get_configured_policybindings().values(): binding.add() def ssl_certkey_bindings_identical(): log('Entering ssl_certkey_bindings_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 ssl_certkey_bindings_sync(): vservername = module.params['name'] if sslvserver_sslcertkey_binding.count(client, vservername) == 0: bindings = [] else: bindings = sslvserver_sslcertkey_binding.get(client, vservername) log('bindings len is %s' % len(bindings)) # Delete existing bindings for binding in bindings: sslvserver_sslcertkey_binding.delete(client, binding) # Add binding if appropriate if module.params['ssl_certkey'] is not None: binding = sslvserver_sslcertkey_binding() binding.vservername = module.params['name'] binding.certkeyname = module.params['ssl_certkey'] sslvserver_sslcertkey_binding.add(client, binding) def diff_list(): csvserver_list = csvserver.get_filtered( client, 'name:%s' % module.params['name']) return csvserver_proxy.diff_object(csvserver_list[0]) try: ensure_feature_is_enabled(client, 'CS') # Apply appropriate operation if module.params['operation'] == 'present': if not cs_vserver_exists(): if not module.check_mode: csvserver_proxy.add() client.save_config() module_result['changed'] = True elif not cs_vserver_identical(): if not module.check_mode: csvserver_proxy.update() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Check policybindings if not cs_policybindings_identical(): if not module.check_mode: sync_cs_policybindings() 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(): if not module.check_mode: ssl_certkey_bindings_sync() module_result['changed'] = True # Sanity check for operation if not module.check_mode: if not cs_vserver_exists(): module.fail_json(msg='Service does not exist', **module_result) if not cs_vserver_identical(): module.fail_json(msg='Service differs from configured', diff=diff_list(), **module_result) if not cs_policybindings_identical(): module.fail_json(msg='Policy bindings differ') if module.params['servicetype'] == 'SSL': if not ssl_certkey_bindings_identical(): module.fail_json( msg='sll certkey bindings not identical', **module_result) elif module.params['operation'] == 'absent': if cs_vserver_exists(): if not module.check_mode: csvserver_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if cs_vserver_exists(): module.fail_json(msg='Service still exists', **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( 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(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines try: from nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver import csvserver from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( name=dict(type='str', ), td=dict(type='float', ), servicetype=dict(type='str', choices=[ u'HTTP', u'SSL', u'TCP', u'FTP', u'RTSP', u'SSL_TCP', u'UDP', u'DNS', u'SIP_UDP', u'SIP_TCP', u'SIP_SSL', u'ANY', u'RADIUS', u'RDP', u'MYSQL', u'MSSQL', u'DIAMETER', u'SSL_DIAMETER', u'DNS_TCP', u'ORACLE', u'SMPP' ]), ipv46=dict(type='str', ), targettype=dict(type='str', choices=[u'GSLB']), dnsrecordtype=dict(type='str', choices=[u'A', u'AAAA', u'CNAME', u'NAPTR']), persistenceid=dict(type='float', ), ippattern=dict(type='str', ), ipmask=dict(type='str', ), range=dict(type='float', ), port=dict(type='int', ), state=dict(type='str', choices=[u'ENABLED', u'DISABLED']), stateupdate=dict(type='str', choices=[u'ENABLED', u'DISABLED']), cacheable=dict(type='str', choices=[u'YES', u'NO']), redirecturl=dict(type='str', ), clttimeout=dict(type='float', ), precedence=dict(type='str', choices=[u'RULE', u'URL']), casesensitive=dict(type='str', choices=[u'ON', u'OFF']), somethod=dict(type='str', choices=[ u'CONNECTION', u'DYNAMICCONNECTION', u'BANDWIDTH', u'HEALTH', u'NONE' ]), sopersistence=dict(type='str', choices=[u'ENABLED', u'DISABLED']), sopersistencetimeout=dict(type='float', ), sothreshold=dict(type='float', ), sobackupaction=dict(type='str', choices=[u'DROP', u'ACCEPT', u'REDIRECT']), redirectportrewrite=dict(type='str', choices=[u'ENABLED', u'DISABLED']), downstateflush=dict(type='str', choices=[u'ENABLED', u'DISABLED']), backupvserver=dict(type='str', ), disableprimaryondown=dict(type='str', choices=[u'ENABLED', u'DISABLED']), insertvserveripport=dict( type='str', choices=[u'OFF', u'VIPADDR', u'V6TOV4MAPPING']), vipheader=dict(type='str', ), rtspnat=dict(type='str', choices=[u'ON', u'OFF']), authenticationhost=dict(type='str', ), authentication=dict(type='str', choices=[u'ON', u'OFF']), listenpolicy=dict(type='str', ), listenpriority=dict(type='float', ), authn401=dict(type='str', choices=[u'ON', u'OFF']), authnvsname=dict(type='str', ), push=dict(type='str', choices=[u'ENABLED', u'DISABLED']), pushvserver=dict(type='str', ), pushlabel=dict(type='str', ), pushmulticlients=dict(type='str', choices=[u'YES', u'NO']), tcpprofilename=dict(type='str', ), httpprofilename=dict(type='str', ), dbprofilename=dict(type='str', ), oracleserverversion=dict(type='str', choices=[u'10G', u'11G']), comment=dict(type='str', ), mssqlserverversion=dict(type='str', choices=[ u'70', u'2000', u'2000SP1', u'2005', u'2008', u'2008R2', u'2012', u'2014' ]), l2conn=dict(type='str', choices=[u'ON', u'OFF']), mysqlprotocolversion=dict(type='float', ), mysqlserverversion=dict(type='str', ), mysqlcharacterset=dict(type='float', ), mysqlservercapabilities=dict(type='float', ), appflowlog=dict(type='str', choices=[u'ENABLED', u'DISABLED']), netprofile=dict(type='str', ), icmpvsrresponse=dict(type='str', choices=[u'PASSIVE', u'ACTIVE']), rhistate=dict(type='str', choices=[u'PASSIVE', u'ACTIVE']), authnprofile=dict(type='str', ), dnsprofilename=dict(type='str', ), domainname=dict(type='str', ), ttl=dict(type='float', ), backupip=dict(type='str', ), cookiedomain=dict(type='str', ), cookietimeout=dict(type='float', ), sitedomainttl=dict(type='float', ), newname=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, ) # 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) client.login() # Instantiate Service Config object readwrite_attrs = [ u'name', u'td', u'servicetype', u'ipv46', u'targettype', u'dnsrecordtype', u'persistenceid', u'ippattern', u'ipmask', u'range', u'port', u'state', u'stateupdate', u'cacheable', u'redirecturl', u'clttimeout', u'precedence', u'casesensitive', u'somethod', u'sopersistence', u'sopersistencetimeout', u'sothreshold', u'sobackupaction', u'redirectportrewrite', u'downstateflush', u'backupvserver', u'disableprimaryondown', u'insertvserveripport', u'vipheader', u'rtspnat', u'authenticationhost', u'authentication', u'listenpolicy', u'listenpriority', u'authn401', u'authnvsname', u'push', u'pushvserver', u'pushlabel', u'pushmulticlients', u'tcpprofilename', u'httpprofilename', u'dbprofilename', u'oracleserverversion', u'comment', u'mssqlserverversion', u'l2conn', u'mysqlprotocolversion', u'mysqlserverversion', u'mysqlcharacterset', u'mysqlservercapabilities', u'appflowlog', u'netprofile', u'icmpvsrresponse', u'rhistate', u'authnprofile', u'dnsprofilename', u'domainname', u'ttl', u'backupip', u'cookiedomain', u'cookietimeout', u'sitedomainttl', u'newname' ] readonly_attrs = [ u'ip', u'value', u'ngname', u'type', u'curstate', u'sc', u'status', u'cachetype', u'redirect', u'homepage', u'dnsvservername', u'domain', u'policyname', u'servicename', u'weight', u'cachevserver', u'targetvserver', u'priority', u'url', u'gotopriorityexpression', u'bindpoint', u'invoke', u'labeltype', u'labelname', u'gt2gb', u'statechangetimesec', u'statechangetimemsec', u'tickssincelaststatechange', u'ruletype', u'lbvserver', u'targetlbvserver', u'__count' ] service_proxy = ConfigProxy( actual=service(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) def service_exists(): if service.count_filtered(client, 'name:%s' % module.params['name']) > 0: return True else: return False def service_identical(): service_list = service.get_filtered(client, 'name:%s' % module.params['name']) diff_dict = service_proxy.diff_object(service_list[0]) if 'ip' in diff_dict: del diff_dict['ip'] if len(diff_dict) == 0: return True else: return False def diff_list(): service_list = service.get_filtered(client, 'name:%s' % module.params['name']) return service_proxy.diff_object(service_list[0]) try: # Apply appropriate operation if module.params['operation'] == 'present': if not service_exists(): if not module.check_mode: service_proxy.add() client.save_config() module_result['changed'] = True elif not service_identical(): if not module.check_mode: service_proxy.update() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if not service_exists(): module.fail_json(msg='Service does not exist') if not service_identical(): module.fail_json(msg='Service differs from configured', diff=diff_list()) elif module.params['operation'] == 'absent': if service_exists(): if not module.check_mode: service_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if service_exists(): module.fail_json(msg='Service still exists') 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( name=dict(type='str'), ip=dict(type='str'), servername=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' ] ), port=dict(type='int'), cleartextport=dict(type='int'), cachetype=dict( type='str', choices=[ 'TRANSPARENT', 'REVERSE', 'FORWARD', ] ), maxclient=dict(type='float'), healthmonitor=dict( type='bool', default=True, ), maxreq=dict(type='float'), cacheable=dict( type='bool', default=False, ), cip=dict( type='str', choices=[ 'enabled', 'disabled', ] ), cipheader=dict(type='str'), usip=dict(type='bool'), useproxyport=dict(type='bool'), sp=dict(type='bool'), rtspsessionidremap=dict( type='bool', default=False, ), clttimeout=dict(type='float'), svrtimeout=dict(type='float'), customserverid=dict( type='str', default='None', ), cka=dict(type='bool'), tcpb=dict(type='bool'), cmp=dict(type='bool'), maxbandwidth=dict(type='float'), accessdown=dict( type='bool', default=False ), monthreshold=dict(type='float'), downstateflush=dict( type='str', choices=[ 'enabled', 'disabled', ], ), tcpprofilename=dict(type='str'), httpprofilename=dict(type='str'), hashid=dict(type='float'), comment=dict(type='str'), appflowlog=dict( type='str', choices=[ 'enabled', 'disabled', ], ), netprofile=dict(type='str'), processlocal=dict( type='str', choices=[ 'enabled', 'disabled', ], ), dnsprofilename=dict(type='str'), ipaddress=dict(type='str'), graceful=dict( type='bool', default=False, ), ) hand_inserted_arguments = dict( monitor_bindings=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') 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)) # Fallthrough to rest of execution # Instantiate Service Config object readwrite_attrs = [ 'name', 'ip', 'servername', 'servicetype', 'port', 'cleartextport', 'cachetype', 'maxclient', 'healthmonitor', 'maxreq', 'cacheable', 'cip', 'cipheader', 'usip', 'useproxyport', 'sp', 'rtspsessionidremap', 'clttimeout', 'svrtimeout', 'customserverid', 'cka', 'tcpb', 'cmp', 'maxbandwidth', 'accessdown', 'monthreshold', 'downstateflush', 'tcpprofilename', 'httpprofilename', 'hashid', 'comment', 'appflowlog', 'netprofile', 'processlocal', 'dnsprofilename', 'ipaddress', 'graceful', ] readonly_attrs = [ 'numofconnections', 'policyname', 'serviceconftype', 'serviceconftype2', 'value', 'gslb', 'dup_state', 'publicip', 'publicport', 'svrstate', 'monitor_state', 'monstatcode', 'lastresponse', 'responsetime', 'riseapbrstatsmsgcode2', 'monstatparam1', 'monstatparam2', 'monstatparam3', 'statechangetimesec', 'statechangetimemsec', 'tickssincelaststatechange', 'stateupdatereason', 'clmonowner', 'clmonview', 'serviceipstr', 'oracleserverversion', ] immutable_attrs = [ 'name', 'ip', 'servername', 'servicetype', 'port', 'cleartextport', 'cachetype', 'cipheader', 'serverid', 'state', 'td', 'monitor_name_svc', 'riseapbrstatsmsgcode', 'graceful', 'all', 'Internal', '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'], 'graceful': ['bool_yes_no'], 'usip': ['bool_yes_no'], 'healthmonitor': ['bool_yes_no'], 'useproxyport': ['bool_yes_no'], 'rtspsessionidremap': ['bool_on_off'], 'accessdown': ['bool_yes_no'], 'cmp': ['bool_yes_no'], 'cip': [lambda v: v.upper()], 'downstateflush': [lambda v: v.upper()], 'appflowlog': [lambda v: v.upper()], 'processlocal': [lambda v: v.upper()], } monitor_bindings_rw_attrs = [ 'servicename', 'servicegroupname', 'dup_state', 'dup_weight', 'monitorname', 'weight', ] # Translate module arguments to correspondign config oject attributes if module.params['ip'] is None: module.params['ip'] = module.params['ipaddress'] service_proxy = ConfigProxy( actual=service(), 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 service_exists(client, module): if not module.check_mode: service_proxy.add() sync_monitor_bindings(client, module, monitor_bindings_rw_attrs) if module.params['save_config']: client.save_config() module_result['changed'] = True elif not all_identical(client, module, service_proxy, monitor_bindings_rw_attrs): # Check if we try to change value of immutable attributes diff_dict = diff(client, module, service_proxy) immutables_changed = get_immutables_intersection(service_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) # Service sync if not service_identical(client, module, service_proxy): if not module.check_mode: service_proxy.update() # Monitor bindings sync if not monitor_bindings_identical(client, module, monitor_bindings_rw_attrs): if not module.check_mode: sync_monitor_bindings(client, module, monitor_bindings_rw_attrs) module_result['changed'] = True if not module.check_mode: if module.params['save_config']: client.save_config() else: module_result['changed'] = False if not module.check_mode: res = do_state_change(client, module, service_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 service_exists(client, module): module.fail_json(msg='Service does not exist', **module_result) if not service_identical(client, module, service_proxy): module.fail_json(msg='Service differs from configured', diff=diff(client, module, service_proxy), **module_result) if not monitor_bindings_identical(client, module, monitor_bindings_rw_attrs): module.fail_json(msg='Monitor bindings are not identical', **module_result) elif module.params['state'] == 'absent': log('Applying actions for state absent') if service_exists(client, module): if not module.check_mode: service_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 service_exists(client, module): module.fail_json(msg='Service 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(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines try: from nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup import servicegroup from nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup_servicegroupmember_binding import servicegroup_servicegroupmember_binding from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( servicegroupname=dict(type='str', ), servicetype=dict( type='str', choices=[ u'HTTP', u'FTP', u'TCP', u'UDP', u'SSL', u'SSL_BRIDGE', u'SSL_TCP', u'DTLS', u'NNTP', u'RPCSVR', u'DNS', u'ADNS', u'SNMP', u'RTSP', u'DHCPRA', u'ANY', u'SIP_UDP', u'SIP_TCP', u'SIP_SSL', u'DNS_TCP', u'ADNS_TCP', u'MYSQL', u'MSSQL', u'ORACLE', u'RADIUS', u'RADIUSListener', u'RDP', u'DIAMETER', u'SSL_DIAMETER', u'TFTP', u'SMPP', u'PPTP', u'GRE', u'SYSLOGTCP', u'SYSLOGUDP', u'FIX', u'SSL_FIX' ]), cachetype=dict(type='str', choices=[u'TRANSPARENT', u'REVERSE', u'FORWARD']), td=dict(type='float', ), maxclient=dict(type='float', ), maxreq=dict(type='float', ), cacheable=dict(type='str', choices=[u'YES', u'NO']), cip=dict(type='str', choices=[u'ENABLED', u'DISABLED']), cipheader=dict(type='str', ), usip=dict(type='str', choices=[u'YES', u'NO']), pathmonitor=dict(type='str', choices=[u'YES', u'NO']), pathmonitorindv=dict(type='str', choices=[u'YES', u'NO']), useproxyport=dict(type='str', choices=[u'YES', u'NO']), healthmonitor=dict(type='str', choices=[u'YES', u'NO']), sc=dict(type='str', choices=[u'ON', u'OFF']), sp=dict(type='str', choices=[u'ON', u'OFF']), rtspsessionidremap=dict(type='str', choices=[u'ON', u'OFF']), clttimeout=dict(type='float', ), svrtimeout=dict(type='float', ), cka=dict(type='str', choices=[u'YES', u'NO']), tcpb=dict(type='str', choices=[u'YES', u'NO']), cmp=dict(type='str', choices=[u'YES', u'NO']), maxbandwidth=dict(type='float', ), monthreshold=dict(type='float', ), state=dict(type='str', choices=[u'ENABLED', u'DISABLED']), downstateflush=dict(type='str', choices=[u'ENABLED', u'DISABLED']), tcpprofilename=dict(type='str', ), httpprofilename=dict(type='str', ), comment=dict(type='str', ), appflowlog=dict(type='str', choices=[u'ENABLED', u'DISABLED']), netprofile=dict(type='str', ), autoscale=dict(type='str', choices=[u'DISABLED', u'DNS', u'POLICY']), memberport=dict(type='int', ), servername=dict(type='str', ), port=dict(type='int', ), weight=dict(type='float', ), customserverid=dict(type='str', ), serverid=dict(type='float', ), hashid=dict(type='float', ), monitor_name_svc=dict(type='str', ), dup_weight=dict(type='float', ), riseapbrstatsmsgcode=dict(type='int', ), delay=dict(type='float', ), graceful=dict(type='str', choices=[u'YES', u'NO']), includemembers=dict(type='bool', ), newname=dict(type='str', ), # These are hand inserted servicemembers=dict(type='list'), ) 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, ) # 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) client.login() # Instantiate service group configuration object readwrite_attrs = [ u'servicegroupname', u'servicetype', u'cachetype', u'td', u'maxclient', u'maxreq', u'cacheable', u'cip', u'cipheader', u'usip', u'pathmonitor', u'pathmonitorindv', u'useproxyport', u'healthmonitor', u'sc', u'sp', u'rtspsessionidremap', u'clttimeout', u'svrtimeout', u'cka', u'tcpb', u'cmp', u'maxbandwidth', u'monthreshold', u'state', u'downstateflush', u'tcpprofilename', u'httpprofilename', u'comment', u'appflowlog', u'netprofile', u'autoscale', u'memberport', u'monconnectionclose', u'servername', u'port', u'weight', u'customserverid', u'serverid', u'hashid', u'monitor_name_svc', u'dup_weight', u'riseapbrstatsmsgcode', u'delay', u'graceful', u'includemembers', u'newname' ] readonly_attrs = [ u'numofconnections', u'serviceconftype', u'value', u'svrstate', u'ip', u'monstatcode', u'monstatparam1', u'monstatparam2', u'monstatparam3', u'statechangetimemsec', u'stateupdatereason', u'clmonowner', u'clmonview', u'groupcount', u'riseapbrstatsmsgcode2', u'serviceipstr', u'servicegroupeffectivestate', u'__count' ] servicegroup_proxy = ConfigProxy(actual=servicegroup(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs) def service_group_exists(): log('service_group_exists') if servicegroup.count_filtered( client, 'servicegroupname:%s' % module.params['servicegroupname']) > 0: return True else: return False def service_group_identical(): log('service_group_identical') servicegroups = servicegroup.get_filtered( client, 'servicegroupname:%s' % module.params['servicegroupname']) if servicegroup_proxy.has_equal_attributes(servicegroups[0]): return True else: return False def get_servicegroups_from_module_params(): log('get_servicegroups_from_module_params') readwrite_attrs = [ u'servicegroupname', u'ip', u'port', u'state', u'hashid', u'serverid', u'servername', u'customserverid', u'weight' ] readonly_attrs = [ u'delay', u'statechangetimesec', u'svrstate', u'tickssincelaststatechange', u'graceful', u'__count' ] 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 service_group_servicemembers_identical(): log('service_group_servicemembers_identical') service_group_members = servicegroup_servicegroupmember_binding.get( client, module.params['servicegroupname']) module_service_groups = get_servicegroups_from_module_params() log('Number of service group members %s' % len(service_group_members)) if len(service_group_members) != len(module_service_groups): return False # Fallthrough to member evaluation identical_count = 0 for actual_member in service_group_members: for member in module_service_groups: if member.has_equal_attributes(actual_member): identical_count += 1 break if identical_count != len(service_group_members): return False # Fallthrough to success return True def delete_all_servicegroup_members(): log('delete_all_servicegroup_members') if servicegroup_servicegroupmember_binding.count( client, module.params['servicegroupname']) == 0: return service_group_members = servicegroup_servicegroupmember_binding.get( client, module.params['servicegroupname']) log('len %s' % len(service_group_members)) log('count %s' % servicegroup_servicegroupmember_binding.count( client, module.params['servicegroupname'])) for member in service_group_members: log('%s' % dir(member)) log('ip %s' % member.ip) log('servername %s' % member.servername) if all([ hasattr(member, 'ip'), member.ip is not None, hasattr(member, 'servername'), member.servername is not None, ]): member.ip = None member.servicegroupname = module.params['servicegroupname'] servicegroup_servicegroupmember_binding.delete(client, member) def add_all_servicegroup_members(): log('add_all_servicegroup_members') for member in get_servicegroups_from_module_params(): member.add() try: if module.params['operation'] == 'present': log('Checking present') if not service_group_exists(): if not module.check_mode: servicegroup_proxy.add() client.save_config() module_result['changed'] = True elif not service_group_identical(): if not module.check_mode: servicegroup_proxy.update() client.save_config() module_result['changed'] = True if not service_group_servicemembers_identical(): if not module.check_mode: delete_all_servicegroup_members() add_all_servicegroup_members() client.save_config() module_result['changed'] = True # Sanity check for operation log('sanity check') if not service_group_exists(): module.fail_json(msg='Service group is not present', loglines=loglines) if not service_group_identical(): module.fail_json( msg='Service group is not identical to configuration', loglines=loglines) if not service_group_servicemembers_identical(): module.fail_json( msg='Service group members differ from configuration', loglines=loglines) elif module.params['operation'] == 'absent': if service_group_exists(): if not module.check_mode: servicegroup_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if service_group_exists(): module.fail_json(msg='Service group is present') except nitro_exception as e: msg = "nitro exception errorcode=" + str( e.errorcode) + ",message=" + e.message module.fail_json(msg=msg, loglines=loglines) client.logout() module.exit_json(loglines=loglines, **module_result)
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', ]), td=dict(type='float'), 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'), sc=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'), state=dict(type='str', choices=[ 'enabled', 'disabled', ]), 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'), servername=dict(type='str'), port=dict(type='int'), weight=dict(type='float'), customserverid=dict(type='str'), serverid=dict(type='float'), hashid=dict(type='float'), monitor_name_svc=dict(type='str'), dup_weight=dict(type='float'), riseapbrstatsmsgcode=dict(type='int'), delay=dict(type='float'), graceful=dict(type='bool'), includemembers=dict(type='bool'), newname=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 = [ 'servicegroupname', 'servicetype', 'cachetype', 'td', 'maxclient', 'maxreq', 'cacheable', 'cip', 'cipheader', 'usip', 'pathmonitor', 'pathmonitorindv', 'useproxyport', 'healthmonitor', 'sc', 'sp', 'rtspsessionidremap', 'clttimeout', 'svrtimeout', 'cka', 'tcpb', 'cmp', 'maxbandwidth', 'monthreshold', 'state', 'downstateflush', 'tcpprofilename', 'httpprofilename', 'comment', 'appflowlog', 'netprofile', 'autoscale', 'memberport', 'monconnectionclose', 'servername', 'port', 'weight', 'customserverid', 'serverid', 'hashid', 'monitor_name_svc', 'dup_weight', 'riseapbrstatsmsgcode', 'delay', 'graceful', 'includemembers', 'newname', ] readonly_attrs = [ 'numofconnections', 'serviceconftype', 'value', 'svrstate', 'ip', 'monstatcode', 'monstatparam1', 'monstatparam2', 'monstatparam3', 'statechangetimemsec', 'stateupdatereason', 'clmonowner', 'clmonview', 'groupcount', 'riseapbrstatsmsgcode2', 'serviceipstr', 'servicegroupeffectivestate', '__count', ] 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'], 'sc': ['bool_on_off'], 'graceful': ['bool_yes_no'], 'cmp': ['bool_yes_no'], } # Instantiate config proxy _proxy = ConfigProxy( actual=_(), 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, ' _') # Apply appropriate state if module.params['state'] == 'present': if not _exists(client, module): if not module.check_mode: _proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not _identical(client, module, _proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection( _proxy, diff_list(client, module, _proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed, ), diff=diff(client, module, _proxy), **module_result) if not module.check_mode: _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: if not _exists(client, module): module.fail_json(msg='_ does not exist', **module_result) if not _identical(client, module, _proxy): module.fail_json(msg='_ differs from configured', diff=diff(client, module, _proxy), **module_result) elif module.params['state'] == 'absent': if _exists(client, module): if not module.check_mode: _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: if _exists(client, module): module.fail_json(msg='_ 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(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines try: from nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver import csvserver from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( policyname=dict(type='str', ), url=dict(type='str', ), rule=dict(type='str', ), domain=dict(type='str', ), action=dict(type='str', ), logaction=dict(type='str', ), newname=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, ) # 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) client.login() # Instantiate Service Config object readwrite_attrs = [ u'policyname', u'url', u'rule', u'domain', u'action', u'logaction', u'newname' ] readonly_attrs = [ u'vstype', u'hits', u'bindhits', u'labelname', u'labeltype', u'priority', u'activepolicy', u'cspolicytype', u'__count' ] service_proxy = ConfigProxy( actual=service(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) def service_exists(): if service.count_filtered(client, 'name:%s' % module.params['name']) > 0: return True else: return False def service_identical(): service_list = service.get_filtered(client, 'name:%s' % module.params['name']) diff_dict = service_proxy.diff_object(service_list[0]) if 'ip' in diff_dict: del diff_dict['ip'] if len(diff_dict) == 0: return True else: return False def diff_list(): service_list = service.get_filtered(client, 'name:%s' % module.params['name']) return service_proxy.diff_object(service_list[0]) try: # Apply appropriate operation if module.params['operation'] == 'present': if not service_exists(): if not module.check_mode: service_proxy.add() client.save_config() module_result['changed'] = True elif not service_identical(): if not module.check_mode: service_proxy.update() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if not service_exists(): module.fail_json(msg='Service does not exist') if not service_identical(): module.fail_json(msg='Service differs from configured', diff=diff_list()) elif module.params['operation'] == 'absent': if service_exists(): if not module.check_mode: service_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if service_exists(): module.fail_json(msg='Service still exists') 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'), servicetype=dict( type='str', choices=[ 'HTTP', 'FTP', 'TCP', 'UDP', 'SSL', 'SSL_BRIDGE', 'SSL_TCP', 'NNTP', 'ANY', 'SIP_UDP', 'SIP_TCP', 'SIP_SSL', 'RADIUS', 'RDP', 'RTSP', 'MYSQL', 'MSSQL', 'ORACLE', ] ), dnsrecordtype=dict( type='str', choices=[ 'A', 'AAAA', 'CNAME', 'NAPTR', ] ), lbmethod=dict( type='str', choices=[ 'ROUNDROBIN', 'LEASTCONNECTION', 'LEASTRESPONSETIME', 'SOURCEIPHASH', 'LEASTBANDWIDTH', 'LEASTPACKETS', 'STATICPROXIMITY', 'RTT', 'CUSTOMLOAD', ] ), backuplbmethod=dict( type='str', choices=[ 'ROUNDROBIN', 'LEASTCONNECTION', 'LEASTRESPONSETIME', 'SOURCEIPHASH', 'LEASTBANDWIDTH', 'LEASTPACKETS', 'STATICPROXIMITY', 'RTT', 'CUSTOMLOAD', ] ), netmask=dict(type='str'), v6netmasklen=dict(type='float'), tolerance=dict(type='float'), persistencetype=dict( type='str', choices=[ 'SOURCEIP', 'NONE', ] ), persistenceid=dict(type='float'), persistmask=dict(type='str'), v6persistmasklen=dict(type='float'), timeout=dict(type='float'), mir=dict( type='str', choices=[ 'ENABLED', 'DISABLED', ] ), disableprimaryondown=dict( type='str', choices=[ 'ENABLED', 'DISABLED', ] ), dynamicweight=dict( type='str', choices=[ 'SERVICECOUNT', 'SERVICEWEIGHT', 'DISABLED', ] ), considereffectivestate=dict( type='str', choices=[ 'NONE', 'STATE_ONLY', ] ), comment=dict(type='str'), 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', ] ), appflowlog=dict( type='str', choices=[ 'ENABLED', 'DISABLED', ] ), domainname=dict(type='str'), cookie_domain=dict(type='str'), ) hand_inserted_arguments = dict( domain_bindings=dict(type='list'), service_bindings=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)) readwrite_attrs = [ 'name', 'servicetype', 'dnsrecordtype', 'lbmethod', 'backuplbmethod', 'netmask', 'v6netmasklen', 'tolerance', 'persistencetype', 'persistenceid', 'persistmask', 'v6persistmasklen', 'timeout', 'mir', 'disableprimaryondown', 'dynamicweight', 'considereffectivestate', 'comment', 'somethod', 'sopersistence', 'sopersistencetimeout', 'sothreshold', 'sobackupaction', 'appflowlog', 'cookie_domain', ] readonly_attrs = [ 'curstate', 'status', 'lbrrreason', 'iscname', 'sitepersistence', 'totalservices', 'activeservices', 'statechangetimesec', 'statechangetimemsec', 'tickssincelaststatechange', 'health', 'policyname', 'priority', 'gotopriorityexpression', 'type', 'vsvrbindsvcip', 'vsvrbindsvcport', '__count', ] immutable_attrs = [ 'name', 'servicetype', ] # Instantiate config proxy gslb_vserver_proxy = ConfigProxy( actual=gslbvserver(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, immutable_attrs=immutable_attrs, ) try: ensure_feature_is_enabled(client, 'GSLB') # Apply appropriate state if module.params['state'] == 'present': log('Applying state present') if not gslb_vserver_exists(client, module): log('Creating object') if not module.check_mode: gslb_vserver_proxy.add() sync_domain_bindings(client, module) sync_service_bindings(client, module) if module.params['save_config']: client.save_config() module_result['changed'] = True elif not all_identical(client, module, gslb_vserver_proxy): log('Entering update actions') # Check if we try to change value of immutable attributes if not gslb_vserver_identical(client, module, gslb_vserver_proxy): log('Updating gslb vserver') immutables_changed = get_immutables_intersection(gslb_vserver_proxy, diff_list(client, module, gslb_vserver_proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed,), diff=diff_list(client, module, gslb_vserver_proxy), **module_result ) if not module.check_mode: gslb_vserver_proxy.update() # Update domain bindings if not domain_bindings_identical(client, module): if not module.check_mode: sync_domain_bindings(client, module) # Update service bindings if not service_bindings_identical(client, module): if not module.check_mode: sync_service_bindings(client, module) module_result['changed'] = True if not module.check_mode: if module.params['save_config']: client.save_config() else: module_result['changed'] = False if not module.check_mode: res = do_state_change(client, module, gslb_vserver_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: if not gslb_vserver_exists(client, module): module.fail_json(msg='GSLB Vserver does not exist', **module_result) if not gslb_vserver_identical(client, module, gslb_vserver_proxy): module.fail_json(msg='GSLB Vserver differs from configured', diff=diff_list(client, module, gslb_vserver_proxy), **module_result) if not domain_bindings_identical(client, module): module.fail_json(msg='Domain bindings differ from configured', diff=diff_list(client, module, gslb_vserver_proxy), **module_result) if not service_bindings_identical(client, module): module.fail_json(msg='Service bindings differ from configured', diff=diff_list(client, module, gslb_vserver_proxy), **module_result) elif module.params['state'] == 'absent': if gslb_vserver_exists(client, module): if not module.check_mode: gslb_vserver_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: if gslb_vserver_exists(client, module): module.fail_json(msg='GSLB 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(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines, ensure_feature_is_enabled try: from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonitor import lbmonitor from nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonbindings_service_binding import lbmonbindings_service_binding from nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonitor_service_binding import lbmonitor_service_binding from nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonitor_servicegroup_binding import lbmonitor_servicegroup_binding python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( monitorname=dict(type='str'), type=dict( type='str', choices=[u'PING', u'TCP', u'HTTP', u'TCP-ECV', u'HTTP-ECV', u'UDP-ECV', u'DNS', u'FTP', u'LDNS-PING', u'LDNS-TCP', u'LDNS-DNS', u'RADIUS', u'USER', u'HTTP-INLINE', u'SIP-UDP', u'SIP-TCP', u'LOAD', u'FTP-EXTENDED', u'SMTP', u'SNMP', u'NNTP', u'MYSQL', u'MYSQL-ECV', u'MSSQL-ECV', u'ORACLE-ECV', u'LDAP', u'POP3', u'CITRIX-XML-SERVICE', u'CITRIX-WEB-INTERFACE', u'DNS-TCP', u'RTSP', u'ARP', u'CITRIX-AG', u'CITRIX-AAC-LOGINPAGE', u'CITRIX-AAC-LAS', u'CITRIX-XD-DDC', u'ND6', u'CITRIX-WI-EXTENDED', u'DIAMETER', u'RADIUS_ACCOUNTING', u'STOREFRONT', u'APPC', u'SMPP', u'CITRIX-XNC-ECV', u'CITRIX-XDM', u'CITRIX-STA-SERVICE', u'CITRIX-STA-SERVICE-NHOP'] ), action=dict( type='str', choices=[u'NONE', u'LOG', u'DOWN'] ), respcode=dict(type='list'), httprequest=dict(type='str',), rtsprequest=dict(type='str'), customheaders=dict(type='str'), maxforwards=dict(type='float'), sipmethod=dict( type='str', choices=[u'OPTIONS', u'INVITE', u'REGISTER'] ), sipuri=dict(type='str'), sipreguri=dict(type='str'), send=dict(type='str'), recv=dict(type='str'), query=dict(type='str'), querytype=dict( type='str', choices=[u'Address', u'Zone', u'AAAA'] ), scriptname=dict(type='str'), scriptargs=dict(type='str'), dispatcherip=dict(type='str'), dispatcherport=dict(type='int'), username=dict(type='str'), password=dict(type='str'), secondarypassword=dict(type='str'), logonpointname=dict(type='str'), lasversion=dict(type='str'), radkey=dict(type='str'), radnasid=dict(type='str'), radnasip=dict(type='str'), radaccounttype=dict(type='float'), radframedip=dict(type='str'), radapn=dict(type='str'), radmsisdn=dict(type='str'), radaccountsession=dict(type='str'), lrtm=dict( type='str', choices=[u'ENABLED', u'DISABLED'] ), deviation=dict(type='float'), units1=dict( type='str', choices=[u'SEC', u'MSEC', u'MIN'] ), interval=dict(type='int'), units3=dict( type='str', choices=[u'SEC', u'MSEC', u'MIN'] ), resptimeout=dict(type='int'), units4=dict( type='str', choices=[u'SEC', u'MSEC', u'MIN'] ), resptimeoutthresh=dict(type='float'), retries=dict(type='int'), failureretries=dict(type='int'), alertretries=dict(type='int'), successretries=dict(type='int'), downtime=dict(type='int'), units2=dict( type='str', choices=[u'SEC', u'MSEC', u'MIN'] ), destip=dict(type='str'), destport=dict(type='int'), state=dict( type='str', choices=[u'ENABLED', u'DISABLED'] ), reverse=dict( type='str', choices=[u'YES', u'NO'] ), transparent=dict( type='str', choices=[u'YES', u'NO'] ), iptunnel=dict( type='str', choices=[u'YES', u'NO'] ), tos=dict( type='str', choices=[u'YES', u'NO'] ), tosid=dict(type='float'), secure=dict( type='str', choices=[u'YES', u'NO'] ), validatecred=dict( type='str', choices=[u'YES', u'NO'] ), domain=dict(type='str'), ipaddress=dict(type='list'), group=dict(type='str'), filename=dict(type='str'), basedn=dict(type='str'), binddn=dict(type='str'), filter=dict(type='str'), attribute=dict(type='str'), database=dict(type='str'), oraclesid=dict(type='str'), sqlquery=dict(type='str'), evalrule=dict(type='str'), mssqlprotocolversion=dict( type='str', choices=[u'70', u'2000', u'2000SP1', u'2005', u'2008', u'2008R2', u'2012', u'2014'] ), Snmpoid=dict(type='str'), snmpcommunity=dict(type='str'), snmpthreshold=dict(type='str'), snmpversion=dict( type='str', choices=[u'V1', u'V2'] ), application=dict(type='str'), sitepath=dict(type='str'), storename=dict(type='str'), storefrontacctservice=dict( type='str', choices=[u'YES', u'NO'] ), netprofile=dict(type='str'), originhost=dict(type='str'), originrealm=dict(type='str'), hostipaddress=dict(type='str'), vendorid=dict(type='float'), productname=dict(type='str'), firmwarerevision=dict(type='float'), authapplicationid=dict(type='list'), acctapplicationid=dict(type='list'), inbandsecurityid=dict( type='str', choices=[u'NO_INBAND_SECURITY', u'TLS'] ), supportedvendorids=dict(type='list'), vendorspecificvendorid=dict(type='float'), vendorspecificauthapplicationids=dict(type='list'), vendorspecificacctapplicationids=dict(type='list'), storedb=dict( type='str', choices=[u'ENABLED', u'DISABLED'] ), storefrontcheckbackendservices=dict( type='str', choices=[u'YES', u'NO'] ), trofscode=dict(type='float'), trofsstring=dict(type='str'), ) argument_spec = dict() argument_spec.update(module_specific_arguments) argument_spec.update(netscaler_common_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', **module_result) # Fallthrough to rest of execution client = get_nitro_client(module) client.login() # Instantiate lb monitor object readwrite_attrs = [ 'monitorname', 'type', 'action', 'respcode', 'httprequest', 'rtsprequest', 'customheaders', 'maxforwards', 'sipmethod', 'sipuri', 'sipreguri', 'send', 'recv', 'query', 'querytype', 'scriptname', 'scriptargs', 'dispatcherip', 'dispatcherport', 'username', 'password', 'secondarypassword', 'logonpointname', 'lasversion', 'radkey', 'radnasid', 'radnasip', 'radaccounttype', 'radframedip', 'radapn', 'radmsisdn', 'radaccountsession', 'lrtm', 'deviation', 'units1', 'interval', 'units3', 'resptimeout', 'units4', 'resptimeoutthresh', 'retries', 'failureretries', 'alertretries', 'successretries', 'downtime', 'units2', 'destip', 'destport', 'state', 'reverse', 'transparent', 'iptunnel', 'tos', 'tosid', 'secure', 'validatecred', 'domain', 'ipaddress', 'group', 'filename', 'basedn', 'binddn', 'filter', 'attribute', 'database', 'oraclesid', 'sqlquery', 'evalrule', 'mssqlprotocolversion', 'Snmpoid', 'snmpcommunity', 'snmpthreshold', 'snmpversion', 'application', 'sitepath', 'storename', 'storefrontacctservice', 'netprofile', 'originhost', 'originrealm', 'hostipaddress', 'vendorid', 'productname', 'firmwarerevision', 'authapplicationid', 'acctapplicationid', 'inbandsecurityid', 'supportedvendorids', 'vendorspecificvendorid', 'vendorspecificauthapplicationids', 'vendorspecificacctapplicationids', 'storedb', 'storefrontcheckbackendservices', 'trofscode', 'trofsstring', ] readonly_attrs = [ 'lrtmconf', 'lrtmconfstr', 'dynamicresponsetimeout', 'dynamicinterval', 'multimetrictable', 'dup_state', 'dup_weight', 'weight', ] lbmonitor_proxy = ConfigProxy( actual=lbmonitor(), client=client, attribute_values_dict = module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, json_encodes=['evalrule'], ) def lbmonitor_exists(): log('Entering lbmonitor_exists') if lbmonitor.count_filtered(client, 'monitorname:%s' % module.params['monitorname']) > 0: return True else: return False def lbmonitor_identical(): log('Entering lbmonitor_identical') count = lbmonitor.count_filtered(client, 'monitorname:%s' % module.params['monitorname']) if count == 0: return False lbmonitor_list = lbmonitor.get_filtered(client, 'monitorname:%s' % module.params['monitorname']) diff_dict = lbmonitor_proxy.diff_object(lbmonitor_list[0]) # Skipping hashed fields since the cannot be compared directly # TODO emulate the hash function for effective equality comparison hashed_fields = [ 'password', 'secondarypassword', 'radkey', ] for key in hashed_fields: if key in diff_dict: del diff_dict[key] if diff_dict == {}: return True else: return False def get_configured_service_bindings(): readwrite_attrs = [ 'weight', 'name', 'passive', 'monstate', ] readonly_attrs = [] configured_bindings = {} if 'servicebindings' in module.params and module.params['servicebindings'] is not None: for binding in module.params['servicebindings']: attribute_values_dict = copy.deepcopy(binding) attribute_values_dict['monitor_name'] = module.params['monitorname'] key = binding['name'].strip() configured_bindings[key] = ConfigProxy( actual=service_lbmonitor_binding(), client=client, attribute_values_dict=attribute_values_dict, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) return configured_bindings def get_actual_service_bindings(): log('entering get_actual_service_bindings') if lbmonbindings_service_binding.count(client, module.params['monitorname']) == 0: return {} bindigs_list = lbmonbindings_service_binding.get(client, module.params['monitorname']) bindings = {} for item in bindigs_list: key = item.servicename log('bound service name %s' % key) bindings[key] = item return bindings def service_bindings_identical(): log('service_bindings_identical') # Compare servicegroup keysets configured_servicegroup_bindings = get_configured_servicegroup_bindings() servicegroup_bindings = get_actual_servicegroup_bindings() configured_keyset = set(configured_servicegroup_bindings.keys()) service_keyset = set(servicegroup_bindings.keys()) log('len %s' % len(configured_keyset ^ service_keyset)) if len(configured_keyset ^ service_keyset) > 0: return False # Compare servicegroup item to item for key in configured_servicegroup_bindings.keys(): conf = configured_servicegroup_bindings[key] serv = servicegroup_bindings[key] log('sg diff %s' % conf.diff_object(serv)) if not conf.has_equal_attributes(serv): return False # Compare service keysets configured_service_bindings = get_configured_service_bindings() service_bindings = get_actual_service_bindings() configured_keyset = set(configured_service_bindings.keys()) service_keyset = set(service_bindings.keys()) if len(configured_keyset ^ service_keyset) > 0: return False # Compare service item to item for key in configured_service_bindings.keys(): conf = configured_service_bindings[key] serv = service_bindings[key] log('s diff %s' % conf.diff_object(serv)) if not conf.has_equal_attributes(serv): return False # Fallthrough to success return True def delete_all_bindings(): log('Entering delete_all_bindings') actual_bindings = get_actual_service_bindings() for binding in actual_bindings.values(): lbmonitor_service_binding.delete(client, binding) def sync_bindings(): delete_all_bindings() if 'servicebindings' in module.params and module.params['servicebindings'] is not None: for servicebinding in module.params['servicebindings']: attribute_values_dict = copy.deepcopy(servicebinding) readwrite_attrs = [ 'servicename', 'servicegroupname', 'weight', 'monitorname', ] attribute_values_dict['monitorname'] = module.params['monitorname'] readonly_attrs = [] binding_proxy = ConfigProxy( actual=lbmonitor_service_binding(), client=client, attribute_values_dict=attribute_values_dict, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) binding_proxy.add() def get_configured_servicegroup_bindings(): readwrite_attrs = [ 'servicegroupname', 'port', 'state', 'hashid', 'serverid', 'customserverid', 'weight', 'passive', 'monstate' ] readonly_attrs = [] configured_bindings = {} if 'servicegroupbindings' in module.params and module.params['servicegroupbindings'] is not None: for binding in module.params['servicegroupbindings']: attribute_values_dict = copy.deepcopy(binding) attribute_values_dict['monitor_name'] = module.params['monitorname'] key = binding['servicegroupname'].strip() configured_bindings[key] = ConfigProxy( actual=servicegroup_lbmonitor_binding(), client=client, attribute_values_dict=attribute_values_dict, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, ) return configured_bindings def diff_list(): return lbmonitor_proxy.diff_object(lbmonitor.get_filtered(client, 'monitorname:%s' % module.params['monitorname'])[0]), try: ensure_feature_is_enabled(client, 'LB') #get_actual_servicegroup_bindings() if module.params['operation'] == 'present': if not lbmonitor_exists(): if not module.check_mode: log('Adding monitor') lbmonitor_proxy.add() lbmonitor_proxy.update() sync_bindings() client.save_config() module_result['changed'] = True elif not lbmonitor_identical(): if not module.check_mode: log('Updating monitor') lbmonitor_proxy.update() client.save_config() module_result['changed'] = True else: log('Doing nothing for monitor') module_result['changed'] = False # Sanity check for result if not module.check_mode: if not lbmonitor_exists(): module.fail_json(msg='Monitor does not seem to exist', **module_result) if not lbmonitor_identical(): module.fail_json( msg='Monitor is not configured according to parameters given', diff=diff_list(), **module_result ) get_actual_service_bindings() elif module.params['operation'] == 'absent': if lbmonitor_exists(): if not module.check_mode: lbmonitor_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for result if not module.check_mode: if lbmonitor_exists(): module.fail_json(msg='Server seems to be present', **module_result) module_result['actual_attributes'] = lbmonitor_proxy.get_actual_rw_attributes(filter='monitorname') 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( monitorname=dict(type='str'), type=dict(type='str', choices=[ 'PING', 'TCP', 'HTTP', 'TCP-ECV', 'HTTP-ECV', 'UDP-ECV', 'DNS', 'FTP', 'LDNS-PING', 'LDNS-TCP', 'LDNS-DNS', 'RADIUS', 'USER', 'HTTP-INLINE', 'SIP-UDP', 'SIP-TCP', 'LOAD', 'FTP-EXTENDED', 'SMTP', 'SNMP', 'NNTP', 'MYSQL', 'MYSQL-ECV', 'MSSQL-ECV', 'ORACLE-ECV', 'LDAP', 'POP3', 'CITRIX-XML-SERVICE', 'CITRIX-WEB-INTERFACE', 'DNS-TCP', 'RTSP', 'ARP', 'CITRIX-AG', 'CITRIX-AAC-LOGINPAGE', 'CITRIX-AAC-LAS', 'CITRIX-XD-DDC', 'ND6', 'CITRIX-WI-EXTENDED', 'DIAMETER', 'RADIUS_ACCOUNTING', 'STOREFRONT', 'APPC', 'SMPP', 'CITRIX-XNC-ECV', 'CITRIX-XDM', 'CITRIX-STA-SERVICE', 'CITRIX-STA-SERVICE-NHOP', ]), action=dict(type='str', choices=[ 'NONE', 'LOG', 'DOWN', ]), respcode=dict(type='list'), httprequest=dict(type='str'), rtsprequest=dict(type='str'), customheaders=dict(type='str'), maxforwards=dict(type='float'), sipmethod=dict(type='str', choices=[ 'OPTIONS', 'INVITE', 'REGISTER', ]), sipuri=dict(type='str'), sipreguri=dict(type='str'), send=dict(type='str'), recv=dict(type='str'), query=dict(type='str'), querytype=dict(type='str', choices=[ 'Address', 'Zone', 'AAAA', ]), scriptname=dict(type='str'), scriptargs=dict(type='str'), dispatcherip=dict(type='str'), dispatcherport=dict(type='int'), username=dict(type='str'), password=dict(type='str'), secondarypassword=dict(type='str'), logonpointname=dict(type='str'), lasversion=dict(type='str'), radkey=dict(type='str'), radnasid=dict(type='str'), radnasip=dict(type='str'), radaccounttype=dict(type='float'), radframedip=dict(type='str'), radapn=dict(type='str'), radmsisdn=dict(type='str'), radaccountsession=dict(type='str'), lrtm=dict(type='str', choices=[ 'enabled', 'disabled', ]), deviation=dict(type='float'), units1=dict(type='str', choices=[ 'SEC', 'MSEC', 'MIN', ]), interval=dict(type='int'), units3=dict(type='str', choices=[ 'SEC', 'MSEC', 'MIN', ]), resptimeout=dict(type='int'), units4=dict(type='str', choices=[ 'SEC', 'MSEC', 'MIN', ]), resptimeoutthresh=dict(type='float'), retries=dict(type='int'), failureretries=dict(type='int'), alertretries=dict(type='int'), successretries=dict(type='int'), downtime=dict(type='int'), units2=dict(type='str', choices=[ 'SEC', 'MSEC', 'MIN', ]), destip=dict(type='str'), destport=dict(type='int'), state=dict(type='str', choices=[ 'enabled', 'disabled', ]), reverse=dict(type='bool'), transparent=dict(type='bool'), iptunnel=dict(type='bool'), tos=dict(type='bool'), tosid=dict(type='float'), secure=dict(type='bool'), validatecred=dict(type='bool'), domain=dict(type='str'), ipaddress=dict(type='list'), group=dict(type='str'), filename=dict(type='str'), basedn=dict(type='str'), binddn=dict(type='str'), filter=dict(type='str'), attribute=dict(type='str'), database=dict(type='str'), oraclesid=dict(type='str'), sqlquery=dict(type='str'), evalrule=dict(type='str'), mssqlprotocolversion=dict(type='str', choices=[ '70', '2000', '2000SP1', '2005', '2008', '2008R2', '2012', '2014', ]), Snmpoid=dict(type='str'), snmpcommunity=dict(type='str'), snmpthreshold=dict(type='str'), snmpversion=dict(type='str', choices=[ 'V1', 'V2', ]), metrictable=dict(type='str'), application=dict(type='str'), sitepath=dict(type='str'), storename=dict(type='str'), storefrontacctservice=dict(type='bool'), hostname=dict(type='str'), netprofile=dict(type='str'), originhost=dict(type='str'), originrealm=dict(type='str'), hostipaddress=dict(type='str'), vendorid=dict(type='float'), productname=dict(type='str'), firmwarerevision=dict(type='float'), authapplicationid=dict(type='list'), acctapplicationid=dict(type='list'), inbandsecurityid=dict(type='str', choices=[ 'NO_INBAND_SECURITY', 'TLS', ]), supportedvendorids=dict(type='list'), vendorspecificvendorid=dict(type='float'), vendorspecificauthapplicationids=dict(type='list'), vendorspecificacctapplicationids=dict(type='list'), kcdaccount=dict(type='str'), storedb=dict(type='str', choices=[ 'enabled', 'disabled', ]), storefrontcheckbackendservices=dict(type='bool'), trofscode=dict(type='float'), trofsstring=dict(type='str'), metric=dict(type='str'), metricthreshold=dict(type='float'), metricweight=dict(type='float'), servicename=dict(type='str'), servicegroupname=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 = [ 'monitorname', 'type', 'action', 'respcode', 'httprequest', 'rtsprequest', 'customheaders', 'maxforwards', 'sipmethod', 'sipuri', 'sipreguri', 'send', 'recv', 'query', 'querytype', 'scriptname', 'scriptargs', 'dispatcherip', 'dispatcherport', 'username', 'password', 'secondarypassword', 'logonpointname', 'lasversion', 'radkey', 'radnasid', 'radnasip', 'radaccounttype', 'radframedip', 'radapn', 'radmsisdn', 'radaccountsession', 'lrtm', 'deviation', 'units1', 'interval', 'units3', 'resptimeout', 'units4', 'resptimeoutthresh', 'retries', 'failureretries', 'alertretries', 'successretries', 'downtime', 'units2', 'destip', 'destport', 'state', 'reverse', 'transparent', 'iptunnel', 'tos', 'tosid', 'secure', 'validatecred', 'domain', 'ipaddress', 'group', 'filename', 'basedn', 'binddn', 'filter', 'attribute', 'database', 'oraclesid', 'sqlquery', 'evalrule', 'mssqlprotocolversion', 'Snmpoid', 'snmpcommunity', 'snmpthreshold', 'snmpversion', 'metrictable', 'application', 'sitepath', 'storename', 'storefrontacctservice', 'hostname', 'netprofile', 'originhost', 'originrealm', 'hostipaddress', 'vendorid', 'productname', 'firmwarerevision', 'authapplicationid', 'acctapplicationid', 'inbandsecurityid', 'supportedvendorids', 'vendorspecificvendorid', 'vendorspecificauthapplicationids', 'vendorspecificacctapplicationids', 'kcdaccount', 'storedb', 'storefrontcheckbackendservices', 'trofscode', 'trofsstring', 'sslprofile', 'metric', 'metricthreshold', 'metricweight', 'servicename', 'servicegroupname', ] readonly_attrs = [ 'lrtmconf', 'lrtmconfstr', 'dynamicresponsetimeout', 'dynamicinterval', 'multimetrictable', 'dup_state', 'dup_weight', 'weight', '__count', ] immutable_attrs = [ 'monitorname', 'type', 'units1', 'units3', 'units4', 'units2', 'Snmpoid', 'hostname', 'servicename', 'servicegroupname', ] transforms = { 'storefrontcheckbackendservices': ['bool_yes_no'], 'secure': ['bool_yes_no'], 'tos': ['bool_yes_no'], 'validatecred': ['bool_yes_no'], 'storefrontacctservice': ['bool_yes_no'], 'iptunnel': ['bool_yes_no'], 'transparent': ['bool_yes_no'], 'reverse': ['bool_yes_no'], } # Instantiate config proxy _proxy = ConfigProxy( actual=_(), 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, ' _') # Apply appropriate state if module.params['state'] == 'present': if not _exists(client, module): if not module.check_mode: _proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not _identical(client, module, _proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection( _proxy, diff_list(client, module, _proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed, ), diff=diff(client, module, _proxy), **module_result) if not module.check_mode: _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: if not _exists(client, module): module.fail_json(msg='_ does not exist', **module_result) if not _identical(client, module, _proxy): module.fail_json(msg='_ differs from configured', diff=diff(client, module, _proxy), **module_result) elif module.params['state'] == 'absent': if _exists(client, module): if not module.check_mode: _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: if _exists(client, module): module.fail_json(msg='_ 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(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines, ensure_feature_is_enabled try: from nssrc.com.citrix.netscaler.nitro.resource.config.cs.csaction import csaction from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception python_sdk_imported = True except ImportError as e: python_sdk_imported = False 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) client.login() # Instantiate Service Config object readwrite_attrs = [ 'name', 'targetlbvserver', 'targetvserverexpr', 'comment', ] readonly_attrs = [ 'hits', 'referencecount', 'undefhits', 'builtin', ] ''' if 'targetvserverexpr' in module.params and module.params['targetvserverexpr'] is not None: module.params['targetvserverexpr'] = json.dumps(module.params['targetvserverexpr']) ''' csaction_proxy = ConfigProxy(actual=csaction(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, json_encodes=['targetvserverexpr']) def action_exists(): if csaction.count_filtered(client, 'name:%s' % module.params['name']) > 0: return True else: return False def action_identical(): if len(diff_list()) == 0: return True else: return False def diff_list(): action_list = csaction.get_filtered(client, 'name:%s' % module.params['name']) diff_list = csaction_proxy.diff_object(action_list[0]) if False and 'targetvserverexpr' in diff_list: json_value = json.loads(action_list[0].targetvserverexpr) if json_value == module.params['targetvserverexpr']: del diff_list['targetvserverexpr'] return diff_list try: ensure_feature_is_enabled(client, 'CS') # Apply appropriate operation if module.params['operation'] == 'present': if not action_exists(): if not module.check_mode: csaction_proxy.add() client.save_config() module_result['changed'] = True elif not action_identical(): if not module.check_mode: csaction_proxy.update() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if not action_exists(): module.fail_json(msg='Content switching action does not exist', **module_result) if not action_identical(): module.fail_json( msg='Content switching action differs from configured', diff=diff_list(), **module_result) elif module.params['operation'] == 'absent': if action_exists(): if not module.check_mode: csaction_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if action_exists(): module.fail_json(msg='Service still exists', **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(): from ansible.module_utils.netscaler import ConfigProxy, get_nitro_client, netscaler_common_arguments, log, loglines try: from nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup import servicegroup from nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup_servicegroupmember_binding import servicegroup_servicegroupmember_binding from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup_lbmonitor_binding import servicegroup_lbmonitor_binding from nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonitor_servicegroup_binding import lbmonitor_servicegroup_binding python_sdk_imported = True except ImportError as e: python_sdk_imported = False module_specific_arguments = dict( servicegroupname=dict(type='str'), servicetype=dict( type='str', choices=[ u'HTTP', u'FTP', u'TCP', u'UDP', u'SSL', u'SSL_BRIDGE', u'SSL_TCP', u'DTLS', u'NNTP', u'RPCSVR', u'DNS', u'ADNS', u'SNMP', u'RTSP', u'DHCPRA', u'ANY', u'SIP_UDP', u'SIP_TCP', u'SIP_SSL', u'DNS_TCP', u'ADNS_TCP', u'MYSQL', u'MSSQL', u'ORACLE', u'RADIUS', u'RADIUSListener', u'RDP', u'DIAMETER', u'SSL_DIAMETER', u'TFTP', u'SMPP', u'PPTP', u'GRE', u'SYSLOGTCP', u'SYSLOGUDP', u'FIX', u'SSL_FIX' ]), cachetype=dict(type='str', choices=[u'TRANSPARENT', u'REVERSE', u'FORWARD']), maxclient=dict(type='float'), maxreq=dict(type='float'), cacheable=dict(type='str', choices=[u'YES', u'NO']), cip=dict(type='str', choices=[u'ENABLED', u'DISABLED']), cipheader=dict(type='str'), usip=dict(type='str', choices=[u'YES', u'NO']), pathmonitor=dict(type='str', choices=[u'YES', u'NO']), pathmonitorindv=dict(type='str', choices=[u'YES', u'NO']), useproxyport=dict(type='str', choices=[u'YES', u'NO']), healthmonitor=dict(type='str', choices=[u'YES', u'NO']), sc=dict(type='str', choices=[u'ON', u'OFF']), sp=dict(type='str', choices=[u'ON', u'OFF']), rtspsessionidremap=dict(type='str', choices=[u'ON', u'OFF']), clttimeout=dict(type='float'), svrtimeout=dict(type='float'), cka=dict(type='str', choices=[u'YES', u'NO']), tcpb=dict(type='str', choices=[u'YES', u'NO']), cmp=dict(type='str', choices=[u'YES', u'NO']), maxbandwidth=dict(type='float'), monthreshold=dict(type='float'), state=dict(type='str', choices=[u'ENABLED', u'DISABLED']), downstateflush=dict(type='str', choices=[u'ENABLED', u'DISABLED']), tcpprofilename=dict(type='str'), httpprofilename=dict(type='str'), comment=dict(type='str'), appflowlog=dict(type='str', choices=[u'ENABLED', u'DISABLED']), netprofile=dict(type='str'), autoscale=dict(type='str', choices=[u'DISABLED', u'DNS', u'POLICY']), memberport=dict(type='int'), graceful=dict(type='str', choices=[u'YES', u'NO']), ) hand_inserted_arguments = dict( servicemembers=dict(type='list'), monitorbindings=dict(type='list'), ) 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) client.login() # Instantiate service group configuration object readwrite_attrs = [ 'servicegroupname', 'servicetype', 'cachetype', 'maxclient', 'maxreq', 'cacheable', 'cip', 'cipheader', 'usip', 'pathmonitor', 'pathmonitorindv', 'useproxyport', 'healthmonitor', 'sc', 'sp', 'rtspsessionidremap', 'clttimeout', 'svrtimeout', 'cka', 'tcpb', 'cmp', 'maxbandwidth', 'monthreshold', 'state', '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' ] servicegroup_proxy = ConfigProxy(actual=servicegroup(), client=client, attribute_values_dict=module.params, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs) def service_group_exists(): log('service_group_exists') if servicegroup.count_filtered( client, 'servicegroupname:%s' % module.params['servicegroupname']) > 0: return True else: return False def service_group_identical(): log('service_group_identical') servicegroups = servicegroup.get_filtered( client, 'servicegroupname:%s' % module.params['servicegroupname']) if servicegroup_proxy.has_equal_attributes(servicegroups[0]): return True else: return False def get_servicegroups_from_module_params(): log('get_servicegroups_from_module_params') readwrite_attrs = [ u'servicegroupname', u'ip', u'port', u'state', u'hashid', u'serverid', u'servername', u'customserverid', u'weight' ] readonly_attrs = [ u'delay', u'statechangetimesec', u'svrstate', u'tickssincelaststatechange', u'graceful', u'__count' ] 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 service_group_servicemembers_identical(): log('service_group_servicemembers_identical') service_group_members = servicegroup_servicegroupmember_binding.get( client, module.params['servicegroupname']) module_service_groups = get_servicegroups_from_module_params() log('Number of service group members %s' % len(service_group_members)) if len(service_group_members) != len(module_service_groups): return False # Fallthrough to member evaluation identical_count = 0 for actual_member in service_group_members: for member in module_service_groups: if member.has_equal_attributes(actual_member): identical_count += 1 break if identical_count != len(service_group_members): return False # Fallthrough to success return True def delete_all_servicegroup_members(): log('delete_all_servicegroup_members') if servicegroup_servicegroupmember_binding.count( client, module.params['servicegroupname']) == 0: return service_group_members = servicegroup_servicegroupmember_binding.get( client, module.params['servicegroupname']) log('len %s' % len(service_group_members)) log('count %s' % servicegroup_servicegroupmember_binding.count( client, module.params['servicegroupname'])) for member in service_group_members: log('%s' % dir(member)) log('ip %s' % member.ip) log('servername %s' % member.servername) if all([ hasattr(member, 'ip'), member.ip is not None, hasattr(member, 'servername'), member.servername is not None, ]): member.ip = None member.servicegroupname = module.params['servicegroupname'] servicegroup_servicegroupmember_binding.delete(client, member) def add_all_servicegroup_members(): log('add_all_servicegroup_members') for member in get_servicegroups_from_module_params(): member.add() def get_configured_monitor_bindings(): 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', ] readonly_attrs = [] if isinstance(binding, dict): attribute_values_dict = copy.deepcopy(binding) else: attribute_values_dict = {'monitorname': 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_actual_monitor_bindings(): log('Entering get_actual_monitor_bindings') bindings = {} if servicegroup_lbmonitor_binding.count( client, module.params['servicegroupname']) == 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 monitor_bindings_identical(): log('Entering monitor_bindings_identical') configured_bindings = get_configured_monitor_bindings() actual_bindings = get_actual_monitor_bindings() 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] if any([ configured_proxy.monitorname != actual_bindings[key].monitor_name, configured_proxy.servicegroupname != actual_bindings[key].servicegroupname ]): return False # Fallthrought to success return True def sync_monitor_bindings(): log('Entering sync_monitor_bindings') # Delete existing bindings for binding in get_actual_monitor_bindings().values(): b = lbmonitor_servicegroup_binding() b.monitorname = binding.monitor_name b.servicegroupname = module.params['servicegroupname'] # Cannot remove default monitor bindings if b.monitorname in ('tcp-default', 'ping-default'): continue lbmonitor_servicegroup_binding.delete(client, b) continue binding.monitorname = binding.monitor_name log('Will delete %s' % dir(binding)) log('Name %s' % binding.name) log('monitor Name %s' % binding.monitor_name) binding.delete(client, binding) #service_lbmonitor_binding.delete(client, binding) # Apply configured bindings for binding in get_configured_monitor_bindings().values(): binding.add() try: if module.params['operation'] == 'present': log('Checking present') if not service_group_exists(): if not module.check_mode: log('Adding service group') servicegroup_proxy.add() servicegroup_proxy.update() client.save_config() #log('Updating service group') #servicegroup_proxy.update() #client.save_config() module_result['changed'] = True elif not service_group_identical(): if not module.check_mode: servicegroup_proxy.update() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Check bindings if not monitor_bindings_identical(): if not module.check_mode: sync_monitor_bindings() client.save_config() module_result['changed'] = True if not service_group_servicemembers_identical(): if not module.check_mode: delete_all_servicegroup_members() add_all_servicegroup_members() client.save_config() module_result['changed'] = True # Sanity check for operation log('sanity check') if not service_group_exists(): module.fail_json(msg='Service group is not present', **module_result) if not service_group_identical(): module.fail_json( msg='Service group is not identical to configuration', **module_result) if not service_group_servicemembers_identical(): module.fail_json( msg='Service group members differ from configuration', **module_result) if not monitor_bindings_identical(): module.fail_json(msg='Monitor bindings are not identical', **module_result) elif module.params['operation'] == 'absent': if service_group_exists(): if not module.check_mode: servicegroup_proxy.delete() client.save_config() module_result['changed'] = True else: module_result['changed'] = False # Sanity check for operation if service_group_exists(): module.fail_json(msg='Service group is present', **module_result) module_result['configured_servicegroup'] = {} module_result['configured_servicegroup'][ 'actual_rw_attributes'] = servicegroup_proxy.get_actual_rw_attributes( filter='servicegroupname') module_result['configured_servicegroup'][ 'actual_ro_attributes'] = servicegroup_proxy.get_actual_ro_attributes( filter='servicegroupname') module_result['configured_servicegroup'][ 'missing_rw_attributes'] = list( set(readwrite_attrs) - set(module_result['configured_servicegroup'] ['actual_rw_attributes'].keys())) module_result['configured_servicegroup'][ 'missing_ro_attributes'] = list( set(readonly_attrs) - set(module_result['configured_servicegroup'] ['actual_ro_attributes'].keys())) 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( monitorname=dict(type='str'), type=dict( type='str', choices=[ 'PING', 'TCP', 'HTTP', 'TCP-ECV', 'HTTP-ECV', 'UDP-ECV', 'DNS', 'FTP', 'LDNS-PING', 'LDNS-TCP', 'LDNS-DNS', 'RADIUS', 'USER', 'HTTP-INLINE', 'SIP-UDP', 'SIP-TCP', 'LOAD', 'FTP-EXTENDED', 'SMTP', 'SNMP', 'NNTP', 'MYSQL', 'MYSQL-ECV', 'MSSQL-ECV', 'ORACLE-ECV', 'LDAP', 'POP3', 'CITRIX-XML-SERVICE', 'CITRIX-WEB-INTERFACE', 'DNS-TCP', 'RTSP', 'ARP', 'CITRIX-AG', 'CITRIX-AAC-LOGINPAGE', 'CITRIX-AAC-LAS', 'CITRIX-XD-DDC', 'ND6', 'CITRIX-WI-EXTENDED', 'DIAMETER', 'RADIUS_ACCOUNTING', 'STOREFRONT', 'APPC', 'SMPP', 'CITRIX-XNC-ECV', 'CITRIX-XDM', 'CITRIX-STA-SERVICE', 'CITRIX-STA-SERVICE-NHOP', ] ), action=dict( type='str', choices=[ 'NONE', 'LOG', 'DOWN', ] ), respcode=dict(type='list'), httprequest=dict(type='str'), rtsprequest=dict(type='str'), customheaders=dict(type='str'), maxforwards=dict(type='float'), sipmethod=dict( type='str', choices=[ 'OPTIONS', 'INVITE', 'REGISTER', ] ), sipuri=dict(type='str'), sipreguri=dict(type='str'), send=dict(type='str'), recv=dict(type='str'), query=dict(type='str'), querytype=dict( type='str', choices=[ 'Address', 'Zone', 'AAAA', ] ), scriptname=dict(type='str'), scriptargs=dict(type='str'), dispatcherip=dict(type='str'), dispatcherport=dict(type='int'), username=dict(type='str'), password=dict(type='str'), secondarypassword=dict(type='str'), logonpointname=dict(type='str'), lasversion=dict(type='str'), radkey=dict(type='str'), radnasid=dict(type='str'), radnasip=dict(type='str'), radaccounttype=dict(type='float'), radframedip=dict(type='str'), radapn=dict(type='str'), radmsisdn=dict(type='str'), radaccountsession=dict(type='str'), lrtm=dict( type='str', choices=[ 'enabled', 'disabled', ] ), deviation=dict(type='float'), units1=dict( type='str', choices=[ 'SEC', 'MSEC', 'MIN', ] ), interval=dict(type='int'), units3=dict( type='str', choices=[ 'SEC', 'MSEC', 'MIN', ] ), resptimeout=dict(type='int'), units4=dict( type='str', choices=[ 'SEC', 'MSEC', 'MIN', ] ), resptimeoutthresh=dict(type='float'), retries=dict(type='int'), failureretries=dict(type='int'), alertretries=dict(type='int'), successretries=dict(type='int'), downtime=dict(type='int'), units2=dict( type='str', choices=[ 'SEC', 'MSEC', 'MIN', ] ), destip=dict(type='str'), destport=dict(type='int'), reverse=dict(type='bool'), transparent=dict(type='bool'), iptunnel=dict(type='bool'), tos=dict(type='bool'), tosid=dict(type='float'), secure=dict(type='bool'), validatecred=dict(type='bool'), domain=dict(type='str'), ipaddress=dict(type='list'), group=dict(type='str'), filename=dict(type='str'), basedn=dict(type='str'), binddn=dict(type='str'), filter=dict(type='str'), attribute=dict(type='str'), database=dict(type='str'), oraclesid=dict(type='str'), sqlquery=dict(type='str'), evalrule=dict(type='str'), mssqlprotocolversion=dict( type='str', choices=[ '70', '2000', '2000SP1', '2005', '2008', '2008R2', '2012', '2014', ] ), Snmpoid=dict(type='str'), snmpcommunity=dict(type='str'), snmpthreshold=dict(type='str'), snmpversion=dict( type='str', choices=[ 'V1', 'V2', ] ), application=dict(type='str'), sitepath=dict(type='str'), storename=dict(type='str'), storefrontacctservice=dict(type='bool'), hostname=dict(type='str'), netprofile=dict(type='str'), originhost=dict(type='str'), originrealm=dict(type='str'), hostipaddress=dict(type='str'), vendorid=dict(type='float'), productname=dict(type='str'), firmwarerevision=dict(type='float'), authapplicationid=dict(type='list'), acctapplicationid=dict(type='list'), inbandsecurityid=dict( type='str', choices=[ 'NO_INBAND_SECURITY', 'TLS', ] ), supportedvendorids=dict(type='list'), vendorspecificvendorid=dict(type='float'), vendorspecificauthapplicationids=dict(type='list'), vendorspecificacctapplicationids=dict(type='list'), storedb=dict( type='str', choices=[ 'enabled', 'disabled', ] ), storefrontcheckbackendservices=dict(type='bool'), trofscode=dict(type='float'), trofsstring=dict(type='str'), ) hand_inserted_arguments = dict() argument_spec = dict() argument_spec.update(module_specific_arguments) argument_spec.update(netscaler_common_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', **module_result) # 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 lb monitor object readwrite_attrs = [ 'monitorname', 'type', 'action', 'respcode', 'httprequest', 'rtsprequest', 'customheaders', 'maxforwards', 'sipmethod', 'sipuri', 'sipreguri', 'send', 'recv', 'query', 'querytype', 'scriptname', 'scriptargs', 'dispatcherip', 'dispatcherport', 'username', 'password', 'secondarypassword', 'logonpointname', 'lasversion', 'radkey', 'radnasid', 'radnasip', 'radaccounttype', 'radframedip', 'radapn', 'radmsisdn', 'radaccountsession', 'lrtm', 'deviation', 'units1', 'interval', 'units3', 'resptimeout', 'units4', 'resptimeoutthresh', 'retries', 'failureretries', 'alertretries', 'successretries', 'downtime', 'units2', 'destip', 'destport', 'reverse', 'transparent', 'iptunnel', 'tos', 'tosid', 'secure', 'validatecred', 'domain', 'ipaddress', 'group', 'filename', 'basedn', 'binddn', 'filter', 'attribute', 'database', 'oraclesid', 'sqlquery', 'evalrule', 'mssqlprotocolversion', 'Snmpoid', 'snmpcommunity', 'snmpthreshold', 'snmpversion', 'application', 'sitepath', 'storename', 'storefrontacctservice', 'netprofile', 'originhost', 'originrealm', 'hostipaddress', 'vendorid', 'productname', 'firmwarerevision', 'authapplicationid', 'acctapplicationid', 'inbandsecurityid', 'supportedvendorids', 'vendorspecificvendorid', 'vendorspecificauthapplicationids', 'vendorspecificacctapplicationids', 'storedb', 'storefrontcheckbackendservices', 'trofscode', 'trofsstring', ] readonly_attrs = [ 'lrtmconf', 'lrtmconfstr', 'dynamicresponsetimeout', 'dynamicinterval', 'multimetrictable', 'dup_state', 'dup_weight', 'weight', ] immutable_attrs = [ 'monitorname', 'type', 'units1', 'units3', 'units4', 'units2', 'Snmpoid', 'hostname', 'servicename', 'servicegroupname', ] transforms = { 'storefrontcheckbackendservices': ['bool_yes_no'], 'secure': ['bool_yes_no'], 'tos': ['bool_yes_no'], 'validatecred': ['bool_yes_no'], 'storefrontacctservice': ['bool_yes_no'], 'iptunnel': ['bool_yes_no'], 'transparent': ['bool_yes_no'], 'reverse': ['bool_yes_no'], 'lrtm': [lambda v: v.upper()], 'storedb': [lambda v: v.upper()], } lbmonitor_proxy = ConfigProxy( actual=lbmonitor(), 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, 'LB') if module.params['state'] == 'present': log('Applying actions for state present') if not lbmonitor_exists(client, module): if not module.check_mode: log('Adding monitor') lbmonitor_proxy.add() if module.params['save_config']: client.save_config() module_result['changed'] = True elif not lbmonitor_identical(client, module, lbmonitor_proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection(lbmonitor_proxy, diff_list(client, module, lbmonitor_proxy).keys()) if immutables_changed != []: diff = diff_list(client, module, lbmonitor_proxy) msg = 'Cannot update immutable attributes %s' % (immutables_changed,) module.fail_json(msg=msg, diff=diff, **module_result) if not module.check_mode: log('Updating monitor') lbmonitor_proxy.update() if module.params['save_config']: client.save_config() module_result['changed'] = True else: log('Doing nothing for monitor') module_result['changed'] = False # Sanity check for result log('Sanity checks for state present') if not module.check_mode: if not lbmonitor_exists(client, module): module.fail_json(msg='lb monitor does not exist', **module_result) if not lbmonitor_identical(client, module, lbmonitor_proxy): module.fail_json( msg='lb monitor is not configured correctly', diff=diff_list(client, module, lbmonitor_proxy), **module_result ) elif module.params['state'] == 'absent': log('Applying actions for state absent') if lbmonitor_exists(client, module): if not module.check_mode: lbmonitor_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 lbmonitor_exists(client, module): module.fail_json(msg='lb monitor still exists', **module_result) module_result['actual_attributes'] = lbmonitor_proxy.get_actual_rw_attributes(filter='monitorname') 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'), ip=dict(type='str'), servername=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' ]), port=dict(type='int'), cleartextport=dict(type='int'), cachetype=dict(type='str', choices=[ 'TRANSPARENT', 'REVERSE', 'FORWARD', ]), maxclient=dict(type='float'), healthmonitor=dict( type='bool', default=True, ), maxreq=dict(type='float'), cacheable=dict( type='bool', default=False, ), cip=dict(type='str', choices=[ 'ENABLED', 'DISABLED', ]), cipheader=dict(type='str'), usip=dict(type='bool'), useproxyport=dict(type='bool'), sc=dict( type='bool', default=False, ), sp=dict(type='bool'), rtspsessionidremap=dict( type='bool', default=False, ), clttimeout=dict(type='float'), svrtimeout=dict(type='float'), customserverid=dict( type='str', default='None', ), cka=dict(type='bool'), tcpb=dict(type='bool'), cmp=dict(type='bool'), maxbandwidth=dict(type='float'), accessdown=dict(type='bool', default=False), monthreshold=dict(type='float'), downstateflush=dict( type='str', choices=[ 'ENABLED', 'DISABLED', ], default='ENABLED', ), tcpprofilename=dict(type='str'), httpprofilename=dict(type='str'), hashid=dict(type='float'), comment=dict(type='str'), appflowlog=dict( type='str', choices=[ 'ENABLED', 'DISABLED', ], default='ENABLED', ), netprofile=dict(type='str'), processlocal=dict( type='str', choices=[ 'ENABLED', 'DISABLED', ], default='DISABLED', ), dnsprofilename=dict(type='str'), ipaddress=dict(type='str'), graceful=dict( type='bool', default=False, ), ) hand_inserted_arguments = dict(monitor_bindings=dict(type='list'), ) 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') 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)) # Fallthrough to rest of execution # Instantiate Service Config object readwrite_attrs = [ 'name', 'ip', 'servername', 'servicetype', 'port', 'cleartextport', 'cachetype', 'maxclient', 'healthmonitor', 'maxreq', 'cacheable', 'cip', 'cipheader', 'usip', 'useproxyport', 'sc', 'sp', 'rtspsessionidremap', 'clttimeout', 'svrtimeout', 'customserverid', 'cka', 'tcpb', 'cmp', 'maxbandwidth', 'accessdown', 'monthreshold', 'downstateflush', 'tcpprofilename', 'httpprofilename', 'hashid', 'comment', 'appflowlog', 'netprofile', 'processlocal', 'dnsprofilename', 'ipaddress', 'graceful', ] readonly_attrs = [ 'numofconnections', 'policyname', 'serviceconftype', 'serviceconftype2', 'value', 'gslb', 'dup_state', 'publicip', 'publicport', 'svrstate', 'monitor_state', 'monstatcode', 'lastresponse', 'responsetime', 'riseapbrstatsmsgcode2', 'monstatparam1', 'monstatparam2', 'monstatparam3', 'statechangetimesec', 'statechangetimemsec', 'tickssincelaststatechange', 'stateupdatereason', 'clmonowner', 'clmonview', 'serviceipstr', 'oracleserverversion', ] immutable_attrs = [ 'name', 'ip', 'servername', 'servicetype', 'port', 'cleartextport', 'cachetype', 'cipheader', 'serverid', 'state', 'td', 'monitor_name_svc', 'riseapbrstatsmsgcode', 'graceful', 'all', 'Internal', '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'], 'graceful': ['bool_yes_no'], 'usip': ['bool_yes_no'], 'healthmonitor': ['bool_yes_no'], 'useproxyport': ['bool_yes_no'], 'rtspsessionidremap': ['bool_on_off'], 'sc': ['bool_on_off'], 'accessdown': ['bool_yes_no'], 'cmp': ['bool_yes_no'], } monitor_bindings_rw_attrs = [ 'servicename', 'servicegroupname', 'dup_state', 'dup_weight', 'monitorname', 'weight', ] # Translate module arguments to correspondign config oject attributes if module.params['ip'] is None: module.params['ip'] = module.params['ipaddress'] service_proxy = ConfigProxy( actual=service(), 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 service_exists(client, module): if not module.check_mode: service_proxy.add() sync_monitor_bindings(client, module, monitor_bindings_rw_attrs) if module.params['save_config']: client.save_config() module_result['changed'] = True elif not all_identical(client, module, service_proxy, monitor_bindings_rw_attrs): # Check if we try to change value of immutable attributes diff_dict = diff(client, module, service_proxy) immutables_changed = get_immutables_intersection( service_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) # Service sync if not service_identical(client, module, service_proxy): if not module.check_mode: service_proxy.update() # Monitor bindings sync if not monitor_bindings_identical(client, module, monitor_bindings_rw_attrs): if not module.check_mode: sync_monitor_bindings(client, module, monitor_bindings_rw_attrs) module_result['changed'] = True if not module.check_mode: if module.params['save_config']: client.save_config() else: module_result['changed'] = False # Sanity check for state if not module.check_mode: log('Sanity checks for state present') if not service_exists(client, module): module.fail_json(msg='Service does not exist', **module_result) if not service_identical(client, module, service_proxy): module.fail_json(msg='Service differs from configured', diff=diff(client, module, service_proxy), **module_result) if not monitor_bindings_identical(client, module, monitor_bindings_rw_attrs): module.fail_json(msg='Monitor bindings are not identical', **module_result) elif module.params['state'] == 'absent': log('Applying actions for state absent') if service_exists(client, module): if not module.check_mode: service_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 service_exists(client, module): module.fail_json(msg='Service 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( servicename=dict(type='str'), cnameentry=dict(type='str'), servername=dict(type='str'), servicetype=dict( type='str', choices=[ 'HTTP', 'FTP', 'TCP', 'UDP', 'SSL', 'SSL_BRIDGE', 'SSL_TCP', 'NNTP', 'ANY', 'SIP_UDP', 'SIP_TCP', 'SIP_SSL', 'RADIUS', 'RDP', 'RTSP', 'MYSQL', 'MSSQL', 'ORACLE', ] ), port=dict(type='int'), publicip=dict(type='str'), publicport=dict(type='int'), maxclient=dict(type='float'), healthmonitor=dict(type='bool'), sitename=dict(type='str'), cip=dict( type='str', choices=[ 'enabled', 'disabled', ] ), cipheader=dict(type='str'), sitepersistence=dict( type='str', choices=[ 'ConnectionProxy', 'HTTPRedirect', 'NONE', ] ), siteprefix=dict(type='str'), clttimeout=dict(type='float'), maxbandwidth=dict(type='float'), downstateflush=dict( type='str', choices=[ 'enabled', 'disabled', ] ), maxaaausers=dict(type='float'), monthreshold=dict(type='float'), hashid=dict(type='float'), comment=dict(type='str'), appflowlog=dict( type='str', choices=[ 'enabled', 'disabled', ] ), ipaddress=dict(type='str'), ) hand_inserted_arguments = dict( monitor_bindings=dict(type='list'), ) 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 = [ 'servicename', 'cnameentry', 'ip', 'servername', 'servicetype', 'port', 'publicip', 'publicport', 'maxclient', 'healthmonitor', 'sitename', 'cip', 'cipheader', 'sitepersistence', 'siteprefix', 'clttimeout', 'maxbandwidth', 'downstateflush', 'maxaaausers', 'monthreshold', 'hashid', 'comment', 'appflowlog', 'ipaddress', ] readonly_attrs = [ 'gslb', 'svrstate', 'svreffgslbstate', 'gslbthreshold', 'gslbsvcstats', 'monstate', 'preferredlocation', 'monitor_state', 'statechangetimesec', 'tickssincelaststatechange', 'threshold', 'clmonowner', 'clmonview', '__count', ] immutable_attrs = [ 'servicename', 'cnameentry', 'ip', 'servername', 'servicetype', 'port', 'sitename', 'state', 'cipheader', 'cookietimeout', 'clttimeout', 'svrtimeout', 'viewip', 'monitor_name_svc', 'newname', ] transforms = { 'healthmonitor': ['bool_yes_no'], 'cip': [lambda v: v.upper()], 'downstateflush': [lambda v: v.upper()], 'appflowlog': [lambda v: v.upper()], } # params = copy.deepcopy(module.params) module.params['ip'] = module.params['ipaddress'] # Instantiate config proxy gslb_service_proxy = ConfigProxy( actual=gslbservice(), client=client, attribute_values_dict=module.params, transforms=transforms, readwrite_attrs=readwrite_attrs, readonly_attrs=readonly_attrs, immutable_attrs=immutable_attrs, ) try: ensure_feature_is_enabled(client, 'GSLB') # Apply appropriate state if module.params['state'] == 'present': if not gslb_service_exists(client, module): if not module.check_mode: gslb_service_proxy.add() sync_monitor_bindings(client, module) if module.params['save_config']: client.save_config() module_result['changed'] = True elif not all_identical(client, module, gslb_service_proxy): # Check if we try to change value of immutable attributes immutables_changed = get_immutables_intersection(gslb_service_proxy, diff_list(client, module, gslb_service_proxy).keys()) if immutables_changed != []: module.fail_json( msg='Cannot update immutable attributes %s' % (immutables_changed,), diff=diff_list(client, module, gslb_service_proxy), **module_result ) # Update main configuration object if not gslb_service_identical(client, module, gslb_service_proxy): if not module.check_mode: gslb_service_proxy.update() # Update monitor bindigns if not monitor_bindings_identical(client, module): if not module.check_mode: sync_monitor_bindings(client, module) # Fallthrough to save and change status update module_result['changed'] = True if module.params['save_config']: client.save_config() else: module_result['changed'] = False # Sanity check for state if not module.check_mode: if not gslb_service_exists(client, module): module.fail_json(msg='GSLB service does not exist', **module_result) if not gslb_service_identical(client, module, gslb_service_proxy): module.fail_json( msg='GSLB service differs from configured', diff=diff_list(client, module, gslb_service_proxy), **module_result ) if not monitor_bindings_identical(client, module): module.fail_json( msg='Monitor bindings differ from configured', diff=diff_list(client, module, gslb_service_proxy), **module_result ) elif module.params['state'] == 'absent': if gslb_service_exists(client, module): if not module.check_mode: gslb_service_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: if gslb_service_exists(client, module): module.fail_json(msg='GSLB service 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 = { } json_encodes = ['targetvserverexpr'] # 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, json_encodes=json_encodes, ) 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( 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 ), ) 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 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)