Exemple #1
0
def sync_default_lb_vserver(client, module):
    d = get_default_lb_vserver(client, module)

    if module.params['lbvserver'] is not None:
        configured = ConfigProxy(actual=csvserver_lbvserver_binding(),
                                 client=client,
                                 readwrite_attrs=[
                                     'name',
                                     'lbvserver',
                                 ],
                                 attribute_values_dict={
                                     'name': module.params['name'],
                                     'lbvserver': module.params['lbvserver'],
                                 })

        if not configured.has_equal_attributes(d):
            if d.name is not None:
                log('Deleting default lb vserver %s' % d.lbvserver)
                csvserver_lbvserver_binding.delete(client, d)
            log('Adding default lb vserver %s' % configured.lbvserver)
            configured.add()
    else:
        if d.name is not None:
            log('Deleting default lb vserver %s' % d.lbvserver)
            csvserver_lbvserver_binding.delete(client, d)
Exemple #2
0
def default_lb_vserver_identical(client, module):
    d = get_default_lb_vserver(client, module)
    configured = ConfigProxy(actual=csvserver_lbvserver_binding(),
                             client=client,
                             readwrite_attrs=[
                                 'name',
                                 'lbvserver',
                             ],
                             attribute_values_dict={
                                 'name': module.params['name'],
                                 'lbvserver': module.params['lbvserver'],
                             })
    log('default lb vserver %s' % ((d.name, d.lbvserver), ))
    if d.name is None and module.params['lbvserver'] is None:
        log('Default lb vserver identical missing')
        return True
    elif d.name is not None and module.params['lbvserver'] is None:
        log('Default lb vserver needs removing')
        return False
    elif configured.has_equal_attributes(d):
        log('Default lb vserver identical')
        return True
    else:
        log('Default lb vserver not identical')
        return False
def get_configured_monitor_bindings(client, module):
    log('Entering get_configured_monitor_bindings')
    bindings = {}
    if 'monitorbindings' in module.params and module.params[
            'monitorbindings'] is not None:
        for binding in module.params['monitorbindings']:
            readwrite_attrs = [
                'monitorname',
                'servicegroupname',
                'weight',
            ]
            readonly_attrs = []
            attribute_values_dict = copy.deepcopy(binding)
            attribute_values_dict['servicegroupname'] = module.params[
                'servicegroupname']
            binding_proxy = ConfigProxy(
                actual=lbmonitor_servicegroup_binding(),
                client=client,
                attribute_values_dict=attribute_values_dict,
                readwrite_attrs=readwrite_attrs,
                readonly_attrs=readonly_attrs,
            )
            key = attribute_values_dict['monitorname']
            bindings[key] = binding_proxy
    return bindings
Exemple #4
0
def get_configured_policybindings(client, module):
    log('Getting configured policy bindigs')
    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',
                                        'gotopriorityexpression',
                                        'targetlbvserver',
                                        'name',
                                        'invoke',
                                        'labeltype',
                                    ],
                                    readonly_attrs=[],
                                    attribute_values_dict=binding)
        bindings[key] = binding_proxy
    return bindings
def get_configured_service_members(client, module):
    log('get_configured_service_members')
    readwrite_attrs = [
        'servicegroupname', 'ip', 'port', 'state', 'hashid', 'serverid',
        'servername', 'customserverid', 'weight'
    ]
    readonly_attrs = [
        'delay',
        'statechangetimesec',
        'svrstate',
        'tickssincelaststatechange',
        'graceful',
    ]

    members = []
    if module.params['servicemembers'] is None:
        return members

    for config in module.params['servicemembers']:
        # Make a copy to update
        config = copy.deepcopy(config)
        config['servicegroupname'] = module.params['servicegroupname']
        member_proxy = ConfigProxy(
            actual=servicegroup_servicegroupmember_binding(),
            client=client,
            attribute_values_dict=config,
            readwrite_attrs=readwrite_attrs,
            readonly_attrs=readonly_attrs)
        members.append(member_proxy)
    return members
 def test_values_copied_to_actual(self):
     actual = Mock()
     client = Mock()
     values = {
         'some_key': 'some_value',
     }
     ConfigProxy(actual=actual,
                 client=client,
                 attribute_values_dict=values,
                 readwrite_attrs=['some_key'])
     self.assertEqual(actual.some_key,
                      values['some_key'],
                      msg='Failed to pass correct value from values dict')
 def test_missing_from_values_dict_not_copied_to_actual(self):
     actual = Mock()
     client = Mock()
     values = {
         'irrelevant_key': 'irrelevant_value',
     }
     print('value %s' % actual.key_for_none)
     ConfigProxy(actual=actual,
                 client=client,
                 attribute_values_dict=values,
                 readwrite_attrs=['key_for_none'])
     print('none %s' % getattr(actual, 'key_for_none'))
     self.assertIsInstance(actual.key_for_none, Mock)
 def test_none_values_not_copied_to_actual(self):
     actual = Mock()
     client = Mock()
     actual.key_for_none = 'initial'
     print('actual %s' % actual.key_for_none)
     values = {
         'key_for_none': None,
     }
     print('value %s' % actual.key_for_none)
     ConfigProxy(actual=actual,
                 client=client,
                 attribute_values_dict=values,
                 readwrite_attrs=['key_for_none'])
     self.assertEqual(actual.key_for_none, 'initial')
Exemple #9
0
def get_configured_monitor_bindings(client, module, monitor_bindings_rw_attrs):
    bindings = {}
    if module.params['monitor_bindings'] is not None:
        for binding in module.params['monitor_bindings']:
            attribute_values_dict = copy.deepcopy(binding)
            # attribute_values_dict['servicename'] = module.params['name']
            attribute_values_dict['servicegroupname'] = module.params['name']
            binding_proxy = ConfigProxy(
                actual=lbmonitor_service_binding(),
                client=client,
                attribute_values_dict=attribute_values_dict,
                readwrite_attrs=monitor_bindings_rw_attrs,
            )
            key = binding_proxy.monitorname
            bindings[key] = binding_proxy
    return bindings
 def test_bool_on_off_transform(self):
     actual = Mock()
     client = Mock()
     values = {
         'on_key': True,
         'off_key': False,
     }
     transforms = {'on_key': ['bool_on_off'], 'off_key': ['bool_on_off']}
     ConfigProxy(
         actual=actual,
         client=client,
         attribute_values_dict=values,
         readwrite_attrs=['on_key', 'off_key'],
         transforms=transforms,
     )
     actual_values = [actual.on_key, actual.off_key]
     self.assertListEqual(actual_values, ['ON', 'OFF'])
 def test_bool_yes_no_transform(self):
     actual = Mock()
     client = Mock()
     values = {
         'yes_key': True,
         'no_key': False,
     }
     transforms = {'yes_key': ['bool_yes_no'], 'no_key': ['bool_yes_no']}
     ConfigProxy(
         actual=actual,
         client=client,
         attribute_values_dict=values,
         readwrite_attrs=['yes_key', 'no_key'],
         transforms=transforms,
     )
     actual_values = [actual.yes_key, actual.no_key]
     self.assertListEqual(actual_values, ['YES', 'NO'])
 def test_immutables_intersection(self):
     actual = Mock()
     client = Mock()
     values = {
         'mutable_key': 'some value',
         'immutable_key': 'some other value',
     }
     proxy = ConfigProxy(
         actual=actual,
         client=client,
         attribute_values_dict=values,
         readwrite_attrs=['mutable_key', 'immutable_key'],
         immutable_attrs=['immutable_key'],
     )
     keys_to_check = ['mutable_key', 'immutable_key', 'non_existant_key']
     result = get_immutables_intersection(proxy, keys_to_check)
     self.assertListEqual(result, ['immutable_key'])
def get_configured_service_bindings(client, module):
    log('get_configured_service_bindings_proxys')
    configured_proxys = {}
    # Get configured domain bindings and index them by domainname
    if module.params['service_bindings'] is not None:
        for configured_binding in module.params['service_bindings']:
            binding_values = copy.deepcopy(configured_binding)
            binding_values['name'] = module.params['name']
            gslbvserver_service_binding_proxy = ConfigProxy(
                actual=gslbvserver_gslbservice_binding(),
                client=client,
                attribute_values_dict=binding_values,
                readwrite_attrs=gslbvserver_gslbservice_binding_rw_attrs,
                readonly_attrs=[],
            )
            configured_proxys[configured_binding[
                'servicename']] = gslbvserver_service_binding_proxy
    return configured_proxys
 def test_callable_transform(self):
     actual = Mock()
     client = Mock()
     values = {
         'transform_key': 'hello',
         'transform_chain': 'hello',
     }
     transforms = {
         'transform_key': [lambda v: v.upper()],
         'transform_chain': [lambda v: v.upper(), lambda v: v[:4]]
     }
     ConfigProxy(
         actual=actual,
         client=client,
         attribute_values_dict=values,
         readwrite_attrs=['transform_key', 'transform_chain'],
         transforms=transforms,
     )
     actual_values = [actual.transform_key, actual.transform_chain]
     self.assertListEqual(actual_values, ['HELLO', 'HELL'])
def get_configured_monitor_bindings(client, module):
    log('get_configured_monitor_bindings')
    configured_monitor_proxys = {}
    gslbservice_lbmonitor_binding_rw_attrs = [
        'weight',
        'servicename',
        'monitor_name',
    ]
    # Get configured monitor bindings and index them by monitor_name
    if module.params['monitor_bindings'] is not None:
        for configured_monitor_bindings in module.params['monitor_bindings']:
            binding_values = copy.deepcopy(configured_monitor_bindings)
            binding_values['servicename'] = module.params['servicename']
            proxy = ConfigProxy(
                actual=gslbservice_lbmonitor_binding(),
                client=client,
                attribute_values_dict=binding_values,
                readwrite_attrs=gslbservice_lbmonitor_binding_rw_attrs,
                readonly_attrs=[],
            )
            configured_monitor_proxys[configured_monitor_bindings['monitor_name']] = proxy
    return configured_monitor_proxys
def main():

    module_specific_arguments = dict(name=dict(type='str'),
                                     ipaddress=dict(type='str'),
                                     domain=dict(type='str'),
                                     translationip=dict(type='str'),
                                     translationmask=dict(type='str'),
                                     domainresolveretry=dict(type='int'),
                                     ipv6address=dict(type='bool',
                                                      default=False),
                                     comment=dict(type='str'),
                                     td=dict(type='float'),
                                     graceful=dict(type='bool'),
                                     delay=dict(type='float'))

    hand_inserted_arguments = dict(disabled=dict(
        type='bool',
        default=False,
    ), )

    argument_spec = dict()

    argument_spec.update(netscaler_common_arguments)
    argument_spec.update(module_specific_arguments)
    argument_spec.update(hand_inserted_arguments)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    # Fallthrough to rest of execution

    client = get_nitro_client(module)
    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(
            e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    # Instantiate Server Config object
    readwrite_attrs = [
        'name',
        'ipaddress',
        'domain',
        'translationip',
        'translationmask',
        'domainresolveretry',
        'ipv6address',
        'graceful',
        'delay',
        'comment',
        'td',
    ]

    readonly_attrs = [
        'statechangetimesec',
        'tickssincelaststatechange',
        'autoscale',
        'customserverid',
        'monthreshold',
        'maxclient',
        'maxreq',
        'maxbandwidth',
        'usip',
        'cka',
        'tcpb',
        'cmp',
        'clttimeout',
        'svrtimeout',
        'cipheader',
        'cip',
        'cacheable',
        'sc',
        'sp',
        'downstateflush',
        'appflowlog',
        'boundtd',
        '__count',
    ]

    immutable_attrs = [
        'name',
        'domain',
        'ipv6address',
        'td',
    ]

    transforms = {
        'graceful': ['bool_yes_no'],
        'ipv6address': ['bool_yes_no'],
    }

    server_proxy = ConfigProxy(
        actual=server(),
        client=client,
        attribute_values_dict=module.params,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        immutable_attrs=immutable_attrs,
        transforms=transforms,
    )

    try:

        # Apply appropriate state
        if module.params['state'] == 'present':
            log('Applying actions for state present')
            if not server_exists(client, module):
                if not module.check_mode:
                    server_proxy.add()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not server_identical(client, module, server_proxy):

                # Check if we try to change value of immutable attributes
                immutables_changed = get_immutables_intersection(
                    server_proxy,
                    diff_list(client, module, server_proxy).keys())
                if immutables_changed != []:
                    msg = 'Cannot update immutable attributes %s' % (
                        immutables_changed, )
                    module.fail_json(msg=msg,
                                     diff=diff_list(client, module,
                                                    server_proxy),
                                     **module_result)
                if not module.check_mode:
                    server_proxy.update()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            if not module.check_mode:
                res = do_state_change(client, module, server_proxy)
                if res.errorcode != 0:
                    msg = 'Error when setting disabled state. errorcode: %s message: %s' % (
                        res.errorcode, res.message)
                    module.fail_json(msg=msg, **module_result)

            # Sanity check for result
            log('Sanity checks for state present')
            if not module.check_mode:
                if not server_exists(client, module):
                    module.fail_json(msg='Server does not seem to exist',
                                     **module_result)
                if not server_identical(client, module, server_proxy):
                    module.fail_json(
                        msg=
                        'Server is not configured according to parameters given',
                        diff=diff_list(client, module, server_proxy),
                        **module_result)

        elif module.params['state'] == 'absent':
            log('Applying actions for state absent')
            if server_exists(client, module):
                if not module.check_mode:
                    server_proxy.delete()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for result
            log('Sanity checks for state absent')
            if not module.check_mode:
                if server_exists(client, module):
                    module.fail_json(msg='Server seems to be present',
                                     **module_result)

    except nitro_exception as e:
        msg = "nitro exception errorcode=%s, message=%s" % (str(
            e.errorcode), e.message)
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)
Exemple #17
0
def main():

    module_specific_arguments = dict(
        name=dict(type='str'),
        td=dict(type='float'),
        servicetype=dict(type='str',
                         choices=[
                             'HTTP', 'SSL', 'TCP', 'FTP', 'RTSP', 'SSL_TCP',
                             'UDP', 'DNS', 'SIP_UDP', 'SIP_TCP', 'SIP_SSL',
                             'ANY', 'RADIUS', 'RDP', 'MYSQL', 'MSSQL',
                             'DIAMETER', 'SSL_DIAMETER', 'DNS_TCP', 'ORACLE',
                             'SMPP'
                         ]),
        ipv46=dict(type='str'),
        dnsrecordtype=dict(type='str',
                           choices=[
                               'A',
                               'AAAA',
                               'CNAME',
                               'NAPTR',
                           ]),
        ippattern=dict(type='str'),
        ipmask=dict(type='str'),
        range=dict(type='float'),
        port=dict(type='int'),
        stateupdate=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        cacheable=dict(type='bool'),
        redirecturl=dict(type='str'),
        clttimeout=dict(type='float'),
        precedence=dict(type='str', choices=[
            'RULE',
            'URL',
        ]),
        casesensitive=dict(type='bool'),
        somethod=dict(type='str',
                      choices=[
                          'CONNECTION',
                          'DYNAMICCONNECTION',
                          'BANDWIDTH',
                          'HEALTH',
                          'NONE',
                      ]),
        sopersistence=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        sopersistencetimeout=dict(type='float'),
        sothreshold=dict(type='float'),
        sobackupaction=dict(type='str',
                            choices=[
                                'DROP',
                                'ACCEPT',
                                'REDIRECT',
                            ]),
        redirectportrewrite=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        downstateflush=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        disableprimaryondown=dict(type='str',
                                  choices=[
                                      'enabled',
                                      'disabled',
                                  ]),
        insertvserveripport=dict(type='str',
                                 choices=[
                                     'OFF',
                                     'VIPADDR',
                                     'V6TOV4MAPPING',
                                 ]),
        vipheader=dict(type='str'),
        rtspnat=dict(type='bool'),
        authenticationhost=dict(type='str'),
        authentication=dict(type='bool'),
        listenpolicy=dict(type='str'),
        authn401=dict(type='bool'),
        authnvsname=dict(type='str'),
        push=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        pushvserver=dict(type='str'),
        pushlabel=dict(type='str'),
        pushmulticlients=dict(type='bool'),
        tcpprofilename=dict(type='str'),
        httpprofilename=dict(type='str'),
        dbprofilename=dict(type='str'),
        oracleserverversion=dict(type='str', choices=[
            '10G',
            '11G',
        ]),
        comment=dict(type='str'),
        mssqlserverversion=dict(type='str',
                                choices=[
                                    '70',
                                    '2000',
                                    '2000SP1',
                                    '2005',
                                    '2008',
                                    '2008R2',
                                    '2012',
                                    '2014',
                                ]),
        l2conn=dict(type='bool'),
        mysqlprotocolversion=dict(type='float'),
        mysqlserverversion=dict(type='str'),
        mysqlcharacterset=dict(type='float'),
        mysqlservercapabilities=dict(type='float'),
        appflowlog=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        netprofile=dict(type='str'),
        icmpvsrresponse=dict(type='str', choices=[
            'PASSIVE',
            'ACTIVE',
        ]),
        rhistate=dict(type='str', choices=[
            'PASSIVE',
            'ACTIVE',
        ]),
        authnprofile=dict(type='str'),
        dnsprofilename=dict(type='str'),
    )

    hand_inserted_arguments = dict(
        policybindings=dict(type='list'),
        ssl_certkey=dict(type='str'),
        disabled=dict(type='bool', default=False),
        lbvserver=dict(type='str'),
    )

    argument_spec = dict()

    argument_spec.update(netscaler_common_arguments)

    argument_spec.update(module_specific_arguments)
    argument_spec.update(hand_inserted_arguments)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    # Fallthrough to rest of execution
    client = get_nitro_client(module)

    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(
            e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    readwrite_attrs = [
        'name',
        'td',
        'servicetype',
        'ipv46',
        'dnsrecordtype',
        'ippattern',
        'ipmask',
        'range',
        'port',
        'stateupdate',
        'cacheable',
        'redirecturl',
        'clttimeout',
        'precedence',
        'casesensitive',
        'somethod',
        'sopersistence',
        'sopersistencetimeout',
        'sothreshold',
        'sobackupaction',
        'redirectportrewrite',
        'downstateflush',
        'disableprimaryondown',
        'insertvserveripport',
        'vipheader',
        'rtspnat',
        'authenticationhost',
        'authentication',
        'listenpolicy',
        'authn401',
        'authnvsname',
        'push',
        'pushvserver',
        'pushlabel',
        'pushmulticlients',
        'tcpprofilename',
        'httpprofilename',
        'dbprofilename',
        'oracleserverversion',
        'comment',
        'mssqlserverversion',
        'l2conn',
        'mysqlprotocolversion',
        'mysqlserverversion',
        'mysqlcharacterset',
        'mysqlservercapabilities',
        'appflowlog',
        'netprofile',
        'icmpvsrresponse',
        'rhistate',
        'authnprofile',
        'dnsprofilename',
    ]

    readonly_attrs = [
        'ip',
        'value',
        'ngname',
        'type',
        'curstate',
        'sc',
        'status',
        'cachetype',
        'redirect',
        'homepage',
        'dnsvservername',
        'domain',
        'policyname',
        'servicename',
        'weight',
        'cachevserver',
        'targetvserver',
        'priority',
        'url',
        'gotopriorityexpression',
        'bindpoint',
        'invoke',
        'labeltype',
        'labelname',
        'gt2gb',
        'statechangetimesec',
        'statechangetimemsec',
        'tickssincelaststatechange',
        'ruletype',
        'lbvserver',
        'targetlbvserver',
    ]

    immutable_attrs = [
        'name',
        'td',
        'servicetype',
        'ipv46',
        'targettype',
        'range',
        'port',
        'state',
        'vipheader',
        'newname',
    ]

    transforms = {
        'cacheable': ['bool_yes_no'],
        'rtspnat': ['bool_on_off'],
        'authn401': ['bool_on_off'],
        'casesensitive': ['bool_on_off'],
        'authentication': ['bool_on_off'],
        'l2conn': ['bool_on_off'],
        'pushmulticlients': ['bool_yes_no'],
        'stateupdate': [lambda v: v.upper()],
        'sopersistence': [lambda v: v.upper()],
        'redirectportrewrite': [lambda v: v.upper()],
        'downstateflush': [lambda v: v.upper()],
        'disableprimaryondown': [lambda v: v.upper()],
        'push': [lambda v: v.upper()],
        'appflowlog': [lambda v: v.upper()],
    }

    # Instantiate config proxy
    csvserver_proxy = ConfigProxy(
        actual=csvserver(),
        client=client,
        attribute_values_dict=module.params,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        immutable_attrs=immutable_attrs,
        transforms=transforms,
    )

    try:
        ensure_feature_is_enabled(client, 'CS')

        # Apply appropriate state
        if module.params['state'] == 'present':
            log('Applying actions for state present')
            if not cs_vserver_exists(client, module):
                if not module.check_mode:
                    csvserver_proxy.add()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not cs_vserver_identical(client, module, csvserver_proxy):

                # Check if we try to change value of immutable attributes
                immutables_changed = get_immutables_intersection(
                    csvserver_proxy,
                    diff_list(client, module, csvserver_proxy).keys())
                if immutables_changed != []:
                    module.fail_json(
                        msg='Cannot update immutable attributes %s' %
                        (immutables_changed, ),
                        diff=diff_list(client, module, csvserver_proxy),
                        **module_result)

                if not module.check_mode:
                    csvserver_proxy.update()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Check policybindings
            if not cs_policybindings_identical(client, module):
                if not module.check_mode:
                    sync_cs_policybindings(client, module)
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True

            if module.params['servicetype'] != 'SSL' and module.params[
                    'ssl_certkey'] is not None:
                module.fail_json(
                    msg='ssl_certkey is applicable only to SSL vservers',
                    **module_result)

            # Check ssl certkey bindings
            if module.params['servicetype'] == 'SSL':
                if not ssl_certkey_bindings_identical(client, module):
                    if not module.check_mode:
                        ssl_certkey_bindings_sync(client, module)

                    module_result['changed'] = True

            # Check default lb vserver
            if not default_lb_vserver_identical(client, module):
                if not module.check_mode:
                    sync_default_lb_vserver(client, module)
                module_result['changed'] = True

            if not module.check_mode:
                res = do_state_change(client, module, csvserver_proxy)
                if res.errorcode != 0:
                    msg = 'Error when setting disabled state. errorcode: %s message: %s' % (
                        res.errorcode, res.message)
                    module.fail_json(msg=msg, **module_result)

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state present')
                if not cs_vserver_exists(client, module):
                    module.fail_json(msg='CS vserver does not exist',
                                     **module_result)
                if not cs_vserver_identical(client, module, csvserver_proxy):
                    module.fail_json(msg='CS vserver differs from configured',
                                     diff=diff_list(client, module,
                                                    csvserver_proxy),
                                     **module_result)
                if not cs_policybindings_identical(client, module):
                    module.fail_json(msg='Policy bindings differ')

                if module.params['servicetype'] == 'SSL':
                    if not ssl_certkey_bindings_identical(client, module):
                        module.fail_json(
                            msg='sll certkey bindings not identical',
                            **module_result)

        elif module.params['state'] == 'absent':
            log('Applying actions for state absent')
            if cs_vserver_exists(client, module):
                if not module.check_mode:
                    csvserver_proxy.delete()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state absent')
                if cs_vserver_exists(client, module):
                    module.fail_json(msg='CS vserver still exists',
                                     **module_result)

    except nitro_exception as e:
        msg = "nitro exception errorcode=%s, message=%s" % (str(
            e.errorcode), e.message)
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)
def main():

    module_specific_arguments = dict(
        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(
        sitename=dict(type='str'),
        sitetype=dict(
            type='str',
            choices=[
                'REMOTE',
                'LOCAL',
            ]
        ),
        siteipaddress=dict(type='str'),
        publicip=dict(type='str'),
        metricexchange=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        nwmetricexchange=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        sessionexchange=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        triggermonitor=dict(
            type='str',
            choices=[
                'ALWAYS',
                'MEPDOWN',
                'MEPDOWN_SVCDOWN',
            ]
        ),
        parentsite=dict(type='str'),
        clip=dict(type='str'),
        publicclip=dict(type='str'),
        naptrreplacementsuffix=dict(type='str'),
    )

    hand_inserted_arguments = dict(
    )

    argument_spec = dict()

    argument_spec.update(netscaler_common_arguments)
    argument_spec.update(module_specific_arguments)
    argument_spec.update(hand_inserted_arguments)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    # Fallthrough to rest of execution
    client = get_nitro_client(module)

    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    readwrite_attrs = [
        'sitename',
        'sitetype',
        'siteipaddress',
        'publicip',
        'metricexchange',
        'nwmetricexchange',
        'sessionexchange',
        'triggermonitor',
        'parentsite',
        'clip',
        'publicclip',
        'naptrreplacementsuffix',
    ]

    readonly_attrs = [
        'status',
        'persistencemepstatus',
        'version',
        '__count',
    ]

    immutable_attrs = [
        'sitename',
        'sitetype',
        'siteipaddress',
        'publicip',
        'parentsite',
        'clip',
        'publicclip',
    ]

    transforms = {
        'metricexchange': [lambda v: v.upper()],
        'nwmetricexchange': [lambda v: v.upper()],
        'sessionexchange': [lambda v: v.upper()],
    }

    # Instantiate config proxy
    gslb_site_proxy = ConfigProxy(
        actual=gslbsite(),
        client=client,
        attribute_values_dict=module.params,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        immutable_attrs=immutable_attrs,
        transforms=transforms,
    )

    try:
        ensure_feature_is_enabled(client, 'GSLB')

        # Apply appropriate state
        if module.params['state'] == 'present':
            log('Applying actions for state present')
            if not gslb_site_exists(client, module):
                if not module.check_mode:
                    gslb_site_proxy.add()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not gslb_site_identical(client, module, gslb_site_proxy):

                # Check if we try to change value of immutable attributes
                immutables_changed = get_immutables_intersection(gslb_site_proxy, diff_list(client, module, gslb_site_proxy).keys())
                if immutables_changed != []:
                    module.fail_json(
                        msg='Cannot update immutable attributes %s' % (immutables_changed,),
                        diff=diff_list(client, module, gslb_site_proxy),
                        **module_result
                    )

                if not module.check_mode:
                    gslb_site_proxy.update()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state present')
                if not gslb_site_exists(client, module):
                    module.fail_json(msg='GSLB site does not exist', **module_result)
                if not gslb_site_identical(client, module, gslb_site_proxy):
                    module.fail_json(msg='GSLB site differs from configured', diff=diff_list(client, module, gslb_site_proxy), **module_result)

        elif module.params['state'] == 'absent':
            log('Applying actions for state absent')
            if gslb_site_exists(client, module):
                if not module.check_mode:
                    gslb_site_proxy.delete()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state absent')
                if gslb_site_exists(client, module):
                    module.fail_json(msg='GSLB site still exists', **module_result)

    except nitro_exception as e:
        msg = "nitro exception errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)
def main():

    module_specific_arguments = dict(
        servicegroupname=dict(type='str'),
        servicetype=dict(type='str',
                         choices=[
                             'HTTP',
                             'FTP',
                             'TCP',
                             'UDP',
                             'SSL',
                             'SSL_BRIDGE',
                             'SSL_TCP',
                             'DTLS',
                             'NNTP',
                             'RPCSVR',
                             'DNS',
                             'ADNS',
                             'SNMP',
                             'RTSP',
                             'DHCPRA',
                             'ANY',
                             'SIP_UDP',
                             'SIP_TCP',
                             'SIP_SSL',
                             'DNS_TCP',
                             'ADNS_TCP',
                             'MYSQL',
                             'MSSQL',
                             'ORACLE',
                             'RADIUS',
                             'RADIUSListener',
                             'RDP',
                             'DIAMETER',
                             'SSL_DIAMETER',
                             'TFTP',
                             'SMPP',
                             'PPTP',
                             'GRE',
                             'SYSLOGTCP',
                             'SYSLOGUDP',
                             'FIX',
                             'SSL_FIX',
                         ]),
        cachetype=dict(type='str',
                       choices=[
                           'TRANSPARENT',
                           'REVERSE',
                           'FORWARD',
                       ]),
        maxclient=dict(type='float'),
        maxreq=dict(type='float'),
        cacheable=dict(type='bool'),
        cip=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        cipheader=dict(type='str'),
        usip=dict(type='bool'),
        pathmonitor=dict(type='bool'),
        pathmonitorindv=dict(type='bool'),
        useproxyport=dict(type='bool'),
        healthmonitor=dict(type='bool'),
        sp=dict(type='bool'),
        rtspsessionidremap=dict(type='bool'),
        clttimeout=dict(type='float'),
        svrtimeout=dict(type='float'),
        cka=dict(type='bool'),
        tcpb=dict(type='bool'),
        cmp=dict(type='bool'),
        maxbandwidth=dict(type='float'),
        monthreshold=dict(type='float'),
        downstateflush=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        tcpprofilename=dict(type='str'),
        httpprofilename=dict(type='str'),
        comment=dict(type='str'),
        appflowlog=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        netprofile=dict(type='str'),
        autoscale=dict(type='str', choices=[
            'DISABLED',
            'DNS',
            'POLICY',
        ]),
        memberport=dict(type='int'),
        graceful=dict(type='bool'),
    )

    hand_inserted_arguments = dict(
        servicemembers=dict(type='list'),
        monitorbindings=dict(type='list'),
        disabled=dict(
            type='bool',
            default=False,
        ),
    )

    argument_spec = dict()

    argument_spec.update(netscaler_common_arguments)
    argument_spec.update(module_specific_arguments)
    argument_spec.update(hand_inserted_arguments)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    # Fallthrough to rest of execution
    client = get_nitro_client(module)

    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(
            e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    # Instantiate service group configuration object
    readwrite_attrs = [
        'servicegroupname',
        'servicetype',
        'cachetype',
        'maxclient',
        'maxreq',
        'cacheable',
        'cip',
        'cipheader',
        'usip',
        'pathmonitor',
        'pathmonitorindv',
        'useproxyport',
        'healthmonitor',
        'sp',
        'rtspsessionidremap',
        'clttimeout',
        'svrtimeout',
        'cka',
        'tcpb',
        'cmp',
        'maxbandwidth',
        'monthreshold',
        'downstateflush',
        'tcpprofilename',
        'httpprofilename',
        'comment',
        'appflowlog',
        'netprofile',
        'autoscale',
        'memberport',
        'graceful',
    ]

    readonly_attrs = [
        'numofconnections', 'serviceconftype', 'value', 'svrstate', 'ip',
        'monstatcode', 'monstatparam1', 'monstatparam2', 'monstatparam3',
        'statechangetimemsec', 'stateupdatereason', 'clmonowner', 'clmonview',
        'groupcount', 'riseapbrstatsmsgcode2', 'serviceipstr',
        'servicegroupeffectivestate'
    ]

    immutable_attrs = [
        'servicegroupname',
        'servicetype',
        'cachetype',
        'td',
        'cipheader',
        'state',
        'autoscale',
        'memberport',
        'servername',
        'port',
        'serverid',
        'monitor_name_svc',
        'dup_weight',
        'riseapbrstatsmsgcode',
        'delay',
        'graceful',
        'includemembers',
        'newname',
    ]

    transforms = {
        'pathmonitorindv': ['bool_yes_no'],
        'cacheable': ['bool_yes_no'],
        'cka': ['bool_yes_no'],
        'pathmonitor': ['bool_yes_no'],
        'tcpb': ['bool_yes_no'],
        'sp': ['bool_on_off'],
        'usip': ['bool_yes_no'],
        'healthmonitor': ['bool_yes_no'],
        'useproxyport': ['bool_yes_no'],
        'rtspsessionidremap': ['bool_on_off'],
        'graceful': ['bool_yes_no'],
        'cmp': ['bool_yes_no'],
        'cip': [lambda v: v.upper()],
        'downstateflush': [lambda v: v.upper()],
        'appflowlog': [lambda v: v.upper()],
    }

    # Instantiate config proxy
    servicegroup_proxy = ConfigProxy(
        actual=servicegroup(),
        client=client,
        attribute_values_dict=module.params,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        immutable_attrs=immutable_attrs,
        transforms=transforms,
    )

    try:
        if module.params['state'] == 'present':
            log('Applying actions for state present')
            if not servicegroup_exists(client, module):
                if not module.check_mode:
                    log('Adding service group')
                    servicegroup_proxy.add()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not servicegroup_identical(client, module,
                                            servicegroup_proxy):

                # Check if we try to change value of immutable attributes
                diff_dict = diff(client, module, servicegroup_proxy)
                immutables_changed = get_immutables_intersection(
                    servicegroup_proxy, diff_dict.keys())
                if immutables_changed != []:
                    msg = 'Cannot update immutable attributes %s. Must delete and recreate entity.' % (
                        immutables_changed, )
                    module.fail_json(msg=msg, diff=diff_dict, **module_result)

                if not module.check_mode:
                    servicegroup_proxy.update()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Check bindings
            if not monitor_bindings_identical(client, module):
                if not module.check_mode:
                    sync_monitor_bindings(client, module)
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True

            if not servicemembers_identical(client, module):
                if not module.check_mode:
                    sync_service_members(client, module)
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True

            if not module.check_mode:
                res = do_state_change(client, module, servicegroup_proxy)
                if res.errorcode != 0:
                    msg = 'Error when setting disabled state. errorcode: %s message: %s' % (
                        res.errorcode, res.message)
                    module.fail_json(msg=msg, **module_result)

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state present')
                if not servicegroup_exists(client, module):
                    module.fail_json(msg='Service group is not present',
                                     **module_result)
                if not servicegroup_identical(client, module,
                                              servicegroup_proxy):
                    module.fail_json(
                        msg='Service group is not identical to configuration',
                        diff=diff(client, module, servicegroup_proxy),
                        **module_result)
                if not servicemembers_identical(client, module):
                    module.fail_json(
                        msg='Service group members differ from configuration',
                        **module_result)
                if not monitor_bindings_identical(client, module):
                    module.fail_json(msg='Monitor bindings are not identical',
                                     **module_result)

        elif module.params['state'] == 'absent':
            log('Applying actions for state absent')
            if servicegroup_exists(client, module):
                if not module.check_mode:
                    servicegroup_proxy.delete()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state absent')
                if servicegroup_exists(client, module):
                    module.fail_json(msg='Service group is present',
                                     **module_result)

    except nitro_exception as e:
        msg = "nitro exception errorcode=" + str(
            e.errorcode) + ",message=" + e.message
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)
def main():

    module_specific_arguments = dict(
        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)
Exemple #22
0
def main():

    module_specific_arguments = dict(
        certkey=dict(type='str', no_log=False),
        cert=dict(type='str'),
        key=dict(type='str', no_log=False),
        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)
Exemple #23
0
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)
Exemple #24
0
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'),
        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)