コード例 #1
0
    def Create(self):
        print 'service create called'
        sslsvc = SERVICE.service()
        sslsvc.name = self.name
        sslsvc.servicetype = self.type
        sslsvc.port = self.port
        sslsvc.ip = self.ip

        try:
            self.svc = SERVICE.service.add(self.sess, sslsvc)
            if self.svc:
                test_util.BindMonitor(self.sess, sslsvc.name, 'quick_mon')
                self.svc = SERVICE.service.get(self.sess, sslsvc.name)
                self.sslsvc = SSLSERVICE.sslservice.get(self.sess, sslsvc.name)
            if not self.sslsvc:
                self.svc = None
        except NITROEXCEPTION as e:
            print 'SSLServiceEntity:Create: NitroException{}'.format(e.message)
            self.svc = None
            self.sslsvc = None
            print '{}'.format(e.message)
        except Exception as e:
            print 'SSLServiceEntity:Create: Exception{}'.format(e.message)
            self.svc = None
            self.sslsvc = None

        self.boundciphers.append('DEFAULT_BACKEND')
        return self.sslsvc
コード例 #2
0
    def rm_service(self, client , svc_name , SRVS,j) :

        try :
            svc = [service() for _ in range(j)]
            for l in range (1,j):
                svc[l].name = svc_name+"-"+SRVS+str(l)
                service.delete(client, svc[l])
                print("rm_service -"+svc[l].name+" - Done\n")
                l += 1
        except nitro_exception as e :
            print("Exception::add_service::errorcode="+str(e.errorcode)+",message="+ e.message)
        except Exception as e:
            print("Exception::add_service::message="+str(e.args))
コード例 #3
0
ファイル: set_config.py プロジェクト: benfinke/ns_python
 def add_service(self, client) :
     try :
         port=80
         service1 = service()
         service1.name = "svc10"
         service1.ip = "10.102.3.23"
         service1.port = port
         service1.servicetype = "http"
         service.add(client, service1)                
         print("add_service - Done")
     except nitro_exception as e :
         print("Exception::add_service::errorcode="+str(e.errorcode)+",message="+ e.message)
     except Exception as e:
         print("Exception::add_service::message="+str(e.args))
コード例 #4
0
    def add_service(self, client , svc_name , port, SRVS,j) :

        try :
            svc = [service() for _ in range(j)]
            for l in range (1,j):
                svc[l].name = svc_name+"-"+SRVS+str(l)
                svc[l].servername = SRVS+str(l)
                svc[l].port = port
                svc[l].servicetype = service.Servicetype.HTTP
                service.add(client, svc[l])
                print("add_service -"+svc[l].servername+" - Done\n")
                l += 1
        except nitro_exception as e :
            print("Exception::add_service::errorcode="+str(e.errorcode)+",message="+ e.message)
        except Exception as e:
            print("Exception::add_service::message="+str(e.args))
コード例 #5
0
ファイル: TestTemplateOne.py プロジェクト: ashokesaha/Tool
    def InstallSSLServices(self,num) :
        serverlist = self.GetServers()
        slist = [o.ipaddress for o in serverlist]
        newserverlist = []
        print 'InstallSSLServices: slist {}'.format(slist)
        
        count = 0
        svclist = []
        for bes in self.container.SSLBEServerList :
            if num == 0 :
                break
            s = NSSVC.service()
            sname  = self.templateName + '-svc-' + bes.name
            s.name = sname
            s.ip   = bes.ip
            s.port = bes.listen_port
            s.servicetype = bes.type
            s.maxreq = 1
            svclist.append(s)
            num -= 1
            count += 1
            
            if s.ip not in slist :
                newserverlist.append(s.ip)
                slist.append(s.ip)

        serverlist = []
        for n in newserverlist :
            S = SERVER.server()
            S.name = n
            S.ipaddress = n
            serverlist.append(S)
            print 'Adding server {}'.format(n)
        if len(serverlist) > 0 :
            SERVER.server.add(self.session,serverlist)


        if len(svclist) > 0 :
            try :
                NSSVC.service.add(self.session,svclist)
                self.sslservicelist = NSSVC.service.get(self.session)
            except NITROEXCEPTION.nitro_exception as e :
                print 'Service add failed {}'.format(e.message)

        return count
コード例 #6
0
    def Delete(self):
        sslv = SERVICE.service()
        sslv.name = self.name
        sslv.servicetype = self.type
        sslv.port = self.port
        sslv.ip = self.ip

        self.sess.relogin()
        try:
            SERVICE.service.delete(self.sess, sslv)
        except NITROEXCEPTION as e:
            self.lb = None
            self.ssl = None
            print '{}'.format(e.message)
        except Exception as e:
            self.lb = None
            self.ssl = None
            print '{}'.format(e.message)
コード例 #7
0
    def addServices(self):
        """Configure the services for the NetScaler"""
        try:

            #Setup the new service 1 HTTPS
            newSVC = service()
            newSVC.name = self.service1
            newSVC.ip = self.ip
            newSVC.port = "80"
            newSVC.servicetype = "http"
            #Add the new service1 and service
            service.add(self.ns_session, newSVC)

        except nitro_exception as e:
            print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
                  e.message)
        except Exception as e:
            print("Exception::message=" + str(e.args))
        return
コード例 #8
0
ファイル: nsAuto.py プロジェクト: MayankTahil/NTW-201
    def addServices(self):
        """Configure the services for the NetScaler"""
        if "services" in self.cfg.keys():
            #Lets loop through all the services
            for svc in self.cfg['services']:
                try:
                    #Setup the new service
                    newSVC = service()
                    newSVC.name = svc['name']
                    newSVC.ip = svc['ip']
                    newSVC.port = svc['port']
                    newSVC.servicetype = svc['type']

                    #Add the new service
                    service.add(self.ns_session, newSVC)

                except nitro_exception as e:
                    print("Exception::errorcode=" + str(e.errorcode) +
                          ",message=" + e.message)
                except Exception as e:
                    print("Exception::message=" + str(e.args))

        return
コード例 #9
0
ファイル: nsAuto.py プロジェクト: btannous/NetScalerNITRO
    def addServices(self):
        """Configure the services for the NetScaler"""
        if "services" in self.cfg.keys():
            #Lets loop through all the services
            for svc in self.cfg['services']:
                try:
                    #Setup the new service
                    newSVC = service()
                    newSVC.name = svc['name']
                    newSVC.ip = svc['ip']
                    newSVC.port = svc['port']
                    newSVC.servicetype = svc['type']

                    #Add the new service
                    service.add(self.ns_session, newSVC)

                except nitro_exception as e:
                    print("Exception::errorcode=" +
                          str(e.errorcode) + ",message=" + e.message)
                except Exception as e:
                    print("Exception::message=" + str(e.args))

        return
コード例 #10
0
ファイル: set_config.py プロジェクト: benfinke/ns_python
    def addlbvserver_bindings(self, client) :
        try :
            obj = lbvserver_service_binding()
            obj.name = "lb_vip"
            obj.servicename = "svc10"
            obj.weight = 77
            lbvserver_service_binding.add(client, obj)
            lbvserver_service_binding.delete(client, obj)
            print("addlbvserver_bindings - Done")
            svc = [ service() for _ in range(2)] 
            svc[0].name = "svc_1"
            svc[0].ip = "1.1.1.1"
            svc[0].port = 80
            svc[0].servicetype = service.Servicetype.HTTP

            svc[1].name = "svc_2"
            svc[1].ip = "1.1.1.1"
            svc[1].port = 81
            svc[1].servicetype = service.Servicetype.HTTP

            bindsvc = [lbvserver_service_binding() for _ in range(2)]
            bindsvc[0].name = "lb_vip"
            bindsvc[0].servicename = "svc_1"
            bindsvc[0].weight = 20

            bindsvc[1].name = "lb_vip"
            bindsvc[1].servicename = "svc_2"
            bindsvc[1].weight = 30

            service.add(client, svc)
            lbvserver_service_binding.add(client, bindsvc)			
            print("addlbvserver_bindings - Done")
        except nitro_exception as e :
            print("Exception::addlbvserver_bindings::errorcode="+str(e.errorcode)+",message="+ e.message)
        except Exception as e:
            print("Exception::addlbvserver_bindings::message="+str(e.args))
コード例 #11
0
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)
コード例 #12
0
ファイル: basicNitro.py プロジェクト: btannous/NetScalerNITRO
# Nitro Imports
from nssrc.com.citrix.netscaler.nitro.service.nitro_service import nitro_service
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.resource.config.basic.service import service

if __name__ == '__main__':
    """Create the NetScaler session using HTTP, passing in the credentials to
    the NSIP"""
    try:  # Error Handling
        ns_session = nitro_service("192.168.1.50", "HTTP")  # Create session

        ns_session.set_credential("nsroot", "nsroot")  # Set the session creds
        ns_session.timeout = 300  # Set Timeout in seconds

        ns_session.login()  # Preform login

        newSVC = service()  # Create new Service instance
        newSVC.name = "service1"  # Define a name
        newSVC.ip = "8.8.8.8"  # Define the service IP
        newSVC.port = "80"  # Define the service port
        newSVC.servicetype = "HTTP"  # Define the service type

        #Add the new service
        service.add(ns_session, newSVC)  # Add the service to the NetScaler

    except nitro_exception as e:  # Error Handling
        print("Exception::errorcode=" +
              str(e.errorcode) + ",message=" + e.message)
    except Exception as e:
        print("Exception::message=" + str(e.args))
コード例 #13
0
# Nitro Imports
from nssrc.com.citrix.netscaler.nitro.service.nitro_service import nitro_service
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.resource.config.basic.service import service

if __name__ == '__main__':
    """Create the NetScaler session using HTTP, passing in the credentials to
    the NSIP"""
    try:  # Error Handling
        ns_session = nitro_service("192.168.1.50", "HTTP")  # Create session

        ns_session.set_credential("nsroot", "nsroot")  # Set the session creds
        ns_session.timeout = 300  # Set Timeout in seconds

        ns_session.login()  # Preform login

        newSVC = service()  # Create new Service instance
        newSVC.name = "service1"  # Define a name
        newSVC.ip = "8.8.8.8"  # Define the service IP
        newSVC.port = "80"  # Define the service port
        newSVC.servicetype = "HTTP"  # Define the service type

        #Add the new service
        service.add(ns_session, newSVC)  # Add the service to the NetScaler

    except nitro_exception as e:  # Error Handling
        print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
              e.message)
    except Exception as e:
        print("Exception::message=" + str(e.args))
コード例 #14
0
ファイル: TestTemplateOne.py プロジェクト: ashokesaha/Tool
            
        except NITROEXCEPTION as e :
            print 'TestTemplateOne Apply failed. {}'.format(e.message)
        



if __name__ == "__main__":
    sess = Login('10.102.28.201')
    tt = TestTemplateOne('tone')
    vlist = tt.PrepareSSLVservers()
    tt.InstallSSLVservers(sess,vlist)
    tt.BindSSLCertkey(sess)

    svclist = []
    s = NSSVC.service()
    s.name = 'one'
    s.ip   = '10.102.28.72'
    s.port = 4443
    s.servicetype = 'SSL'
    s.maxreq = 1
    svclist.append(s)

    s = NSSVC.service()
    s.name = 'two'
    s.ip   = '10.102.28.72'
    s.port = 4445
    s.servicetype = 'SSL'
    s.maxreq = 1
    svclist.append(s)
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)
コード例 #16
0
ファイル: basic_lbvServer.py プロジェクト: jeff-brown/pyNitro
	def main(cls, args_):
		if(len(args_) < 3):
			print("Usage: run.bat <ip> <username> <password>")
			return

		config = basic_lbvServer()
		config.ip = args_[1]
		config.username = args_[2]
		config.password = args_[3] 
		
		try :
			
			#Create an instance of the nitro_service class to connect to the appliance
			ns_session = nitro_service("10.217.242.90","HTTP")
			
			ns_session.set_credential("nsroot", config.password)
			ns_session.timeout = 310
			#Log on to the appliance using your credentials
			ns_session.login()
			
			#Enable the load balancing feature.
			features_to_be_enabled = "lb"			
			ns_session.enable_features(features_to_be_enabled)
			
			#Create an instance of the server class
			server_obj = server()

			#Create an instance of the service class
			service_obj = service()

			#Create an instance of the virtual server class
			new_lbvserver_obj = lbvserver()

			#Create a new virtual server
			new_lbvserver_obj.name = "MyFirstLbVServer"
			new_lbvserver_obj.ipv46 = "10.102.29.88"
			new_lbvserver_obj.servicetype = "HTTP"
			new_lbvserver_obj.port = 80
			new_lbvserver_obj.lbmethod = "ROUNDROBIN"
			#lbvserver.delete(ns_session, new_lbvserver_obj.name)
			#lbvserver.add(ns_session, new_lbvserver_obj)
					
			#Retrieve the details of the virtual server
			new_lbvserver_obj = lbvserver.get(ns_session,new_lbvserver_obj.name)
			print("Name : " +new_lbvserver_obj.name +"\n" +"Protocol : " +new_lbvserver_obj.servicetype)

			#Retrieve state of a lbvserver
			obj_lbv = lbvserver_stats.get(ns_session, "MyFirstLbVServer")
			print("statlbvserver_byname result::name="+obj_lbv.name+", servicetype="+obj_lbv.type +",state="+obj_lbv.state)

			#Retrieve state of a servicegroup
			obj_svcg = servicegroup.get(ns_session, "http_svcg")
			print("statsvcg_byname result::name="+obj_svcg.servicegroupname+", servicetype="+obj_svcg.servicetype +",state="+obj_svcg.servicegroupeffectivestate)

			#Delete the virtual server
			#lbvserver.delete(ns_session, new_lbvserver_obj.name)
			
			#Save the configurations
			ns_session.save_config()
			
			#Logout from the NetScaler appliance
			ns_session.logout()
			
		except nitro_exception as  e:
			print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
		except Exception as e:         
			print("Exception::message="+str(e.args))
		return
コード例 #17
0
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',
        '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 object 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)
コード例 #18
0
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)