summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/network/netscaler/netscaler_cs_vserver.py
blob: 06d850d85aadca52e8267d9b621506d77a433c8c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
#!/usr/bin/python
# -*- coding: utf-8 -*-

#  Copyright (c) 2017 Citrix Systems
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type


ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}


DOCUMENTATION = '''
---
module: netscaler_cs_vserver
short_description: Manage content switching vserver
description:
    - Manage content switching vserver
    - This module is intended to run either on the ansible  control node or a bastion (jumpserver) with access to the actual netscaler instance

version_added: "2.4"

author: George Nikolopoulos (@giorgos-nikolopoulos)

options:

    name:
        description:
            - >-
                Name for the content switching virtual server. Must begin with an ASCII alphanumeric or underscore
                C(_) character, and must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.), space,
                colon C(:), at sign C(@), equal sign C(=), and hyphen C(-) characters.
            - "Cannot be changed after the CS virtual server is created."
            - "Minimum length = 1"

    td:
        description:
            - >-
                Integer value that uniquely identifies the traffic domain in which you want to configure the entity.
                If you do not specify an ID, the entity becomes part of the default traffic domain, which has an ID
                of 0.
            - "Minimum value = 0"
            - "Maximum value = 4094"

    servicetype:
        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'
        description:
            - "Protocol used by the virtual server."

    ipv46:
        description:
            - "IP address of the content switching virtual server."
            - "Minimum length = 1"

    targettype:
        choices:
            - 'GSLB'
        description:
            - "Virtual server target type."

    ippattern:
        description:
            - >-
                IP address pattern, in dotted decimal notation, for identifying packets to be accepted by the virtual
                server. The IP Mask parameter specifies which part of the destination IP address is matched against
                the pattern. Mutually exclusive with the IP Address parameter.
            - >-
                For example, if the IP pattern assigned to the virtual server is C(198.51.100.0) and the IP mask is
                C(255.255.240.0) (a forward mask), the first 20 bits in the destination IP addresses are matched with
                the first 20 bits in the pattern. The virtual server accepts requests with IP addresses that range
                from 198.51.96.1 to 198.51.111.254. You can also use a pattern such as C(0.0.2.2) and a mask such as
                C(0.0.255.255) (a reverse mask).
            - >-
                If a destination IP address matches more than one IP pattern, the pattern with the longest match is
                selected, and the associated virtual server processes the request. For example, if the virtual
                servers, C(vs1) and C(vs2), have the same IP pattern, C(0.0.100.128), but different IP masks of C(0.0.255.255)
                and C(0.0.224.255), a destination IP address of 198.51.100.128 has the longest match with the IP pattern
                of C(vs1). If a destination IP address matches two or more virtual servers to the same extent, the
                request is processed by the virtual server whose port number matches the port number in the request.

    ipmask:
        description:
            - >-
                IP mask, in dotted decimal notation, for the IP Pattern parameter. Can have leading or trailing
                non-zero octets (for example, C(255.255.240.0) or C(0.0.255.255)). Accordingly, the mask specifies whether
                the first n bits or the last n bits of the destination IP address in a client request are to be
                matched with the corresponding bits in the IP pattern. The former is called a forward mask. The
                latter is called a reverse mask.

    range:
        description:
            - >-
                Number of consecutive IP addresses, starting with the address specified by the IP Address parameter,
                to include in a range of addresses assigned to this virtual server.
            - "Minimum value = C(1)"
            - "Maximum value = C(254)"

    port:
        description:
            - "Port number for content switching virtual server."
            - "Minimum value = 1"
            - "Range C(1) - C(65535)"
            - "* in CLI is represented as 65535 in NITRO API"

    stateupdate:
        choices:
            - 'enabled'
            - 'disabled'
        description:
            - >-
                Enable state updates for a specific content switching virtual server. By default, the Content
                Switching virtual server is always UP, regardless of the state of the Load Balancing virtual servers
                bound to it. This parameter interacts with the global setting as follows:
            - "Global Level | Vserver Level | Result"
            - "enabled enabled enabled"
            - "enabled disabled enabled"
            - "disabled enabled enabled"
            - "disabled disabled disabled"
            - >-
                If you want to enable state updates for only some content switching virtual servers, be sure to
                disable the state update parameter.

    cacheable:
        description:
            - >-
                Use this option to specify whether a virtual server, used for load balancing or content switching,
                routes requests to the cache redirection virtual server before sending it to the configured servers.
        type: bool

    redirecturl:
        description:
            - >-
                URL to which traffic is redirected if the virtual server becomes unavailable. The service type of the
                virtual server should be either C(HTTP) or C(SSL).
            - >-
                Caution: Make sure that the domain in the URL does not match the domain specified for a content
                switching policy. If it does, requests are continuously redirected to the unavailable virtual server.
            - "Minimum length = 1"

    clttimeout:
        description:
            - "Idle time, in seconds, after which the client connection is terminated. The default values are:"
            - "Minimum value = C(0)"
            - "Maximum value = C(31536000)"

    precedence:
        choices:
            - 'RULE'
            - 'URL'
        description:
            - >-
                Type of precedence to use for both RULE-based and URL-based policies on the content switching virtual
                server. With the default C(RULE) setting, incoming requests are evaluated against the rule-based
                content switching policies. If none of the rules match, the URL in the request is evaluated against
                the URL-based content switching policies.

    casesensitive:
        description:
            - >-
                Consider case in URLs (for policies that use URLs instead of RULES). For example, with the C(on)
                setting, the URLs /a/1.html and /A/1.HTML are treated differently and can have different targets (set
                by content switching policies). With the C(off) setting, /a/1.html and /A/1.HTML are switched to the
                same target.
        type: bool

    somethod:
        choices:
            - 'CONNECTION'
            - 'DYNAMICCONNECTION'
            - 'BANDWIDTH'
            - 'HEALTH'
            - 'NONE'
        description:
            - >-
                Type of spillover used to divert traffic to the backup virtual server when the primary virtual server
                reaches the spillover threshold. Connection spillover is based on the number of connections.
                Bandwidth spillover is based on the total Kbps of incoming and outgoing traffic.

    sopersistence:
        choices:
            - 'enabled'
            - 'disabled'
        description:
            - "Maintain source-IP based persistence on primary and backup virtual servers."

    sopersistencetimeout:
        description:
            - "Time-out value, in minutes, for spillover persistence."
            - "Minimum value = C(2)"
            - "Maximum value = C(1440)"

    sothreshold:
        description:
            - >-
                Depending on the spillover method, the maximum number of connections or the maximum total bandwidth
                (Kbps) that a virtual server can handle before spillover occurs.
            - "Minimum value = C(1)"
            - "Maximum value = C(4294967287)"

    sobackupaction:
        choices:
            - 'DROP'
            - 'ACCEPT'
            - 'REDIRECT'
        description:
            - >-
                Action to be performed if spillover is to take effect, but no backup chain to spillover is usable or
                exists.

    redirectportrewrite:
        choices:
            - 'enabled'
            - 'disabled'
        description:
            - "State of port rewrite while performing HTTP redirect."

    downstateflush:
        choices:
            - 'enabled'
            - 'disabled'
        description:
            - >-
                Flush all active transactions associated with a virtual server whose state transitions from UP to
                DOWN. Do not enable this option for applications that must complete their transactions.

    backupvserver:
        description:
            - >-
                Name of the backup virtual server that you are configuring. Must begin with an ASCII alphanumeric or
                underscore C(_) character, and must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.),
                space C( ), colon C(:), at sign C(@), equal sign C(=), and hyphen C(-) characters. Can be changed after the
                backup virtual server is created. You can assign a different backup virtual server or rename the
                existing virtual server.
            - "Minimum length = 1"

    disableprimaryondown:
        choices:
            - 'enabled'
            - 'disabled'
        description:
            - >-
                Continue forwarding the traffic to backup virtual server even after the primary server comes UP from
                the DOWN state.

    insertvserveripport:
        choices:
            - 'OFF'
            - 'VIPADDR'
            - 'V6TOV4MAPPING'
        description:
            - >-
                Insert the virtual server's VIP address and port number in the request header. Available values
                function as follows:
            - "C(VIPADDR) - Header contains the vserver's IP address and port number without any translation."
            - "C(OFF) - The virtual IP and port header insertion option is disabled."
            - >-
                C(V6TOV4MAPPING) - Header contains the mapped IPv4 address corresponding to the IPv6 address of the
                vserver and the port number. An IPv6 address can be mapped to a user-specified IPv4 address using the
                set ns ip6 command.

    vipheader:
        description:
            - "Name of virtual server IP and port header, for use with the VServer IP Port Insertion parameter."
            - "Minimum length = 1"

    rtspnat:
        description:
            - "Enable network address translation (NAT) for real-time streaming protocol (RTSP) connections."
        type: bool

    authenticationhost:
        description:
            - >-
                FQDN of the authentication virtual server. The service type of the virtual server should be either
                C(HTTP) or C(SSL).
            - "Minimum length = 3"
            - "Maximum length = 252"

    authentication:
        description:
            - "Authenticate users who request a connection to the content switching virtual server."
        type: bool

    listenpolicy:
        description:
            - >-
                String specifying the listen policy for the content switching virtual server. Can be either the name
                of an existing expression or an in-line expression.

    authn401:
        description:
            - "Enable HTTP 401-response based authentication."
        type: bool

    authnvsname:
        description:
            - >-
                Name of authentication virtual server that authenticates the incoming user requests to this content
                switching virtual server. .
            - "Minimum length = 1"
            - "Maximum length = 252"

    push:
        choices:
            - 'enabled'
            - 'disabled'
        description:
            - >-
                Process traffic with the push virtual server that is bound to this content switching virtual server
                (specified by the Push VServer parameter). The service type of the push virtual server should be
                either C(HTTP) or C(SSL).

    pushvserver:
        description:
            - >-
                Name of the load balancing virtual server, of type C(PUSH) or C(SSL_PUSH), to which the server pushes
                updates received on the client-facing load balancing virtual server.
            - "Minimum length = 1"

    pushlabel:
        description:
            - >-
                Expression for extracting the label from the response received from server. This string can be either
                an existing rule name or an inline expression. The service type of the virtual server should be
                either C(HTTP) or C(SSL).

    pushmulticlients:
        description:
            - >-
                Allow multiple Web 2.0 connections from the same client to connect to the virtual server and expect
                updates.
        type: bool

    tcpprofilename:
        description:
            - "Name of the TCP profile containing TCP configuration settings for the virtual server."
            - "Minimum length = 1"
            - "Maximum length = 127"

    httpprofilename:
        description:
            - >-
                Name of the HTTP profile containing HTTP configuration settings for the virtual server. The service
                type of the virtual server should be either C(HTTP) or C(SSL).
            - "Minimum length = 1"
            - "Maximum length = 127"

    dbprofilename:
        description:
            - "Name of the DB profile."
            - "Minimum length = 1"
            - "Maximum length = 127"

    oracleserverversion:
        choices:
            - '10G'
            - '11G'
        description:
            - "Oracle server version."

    comment:
        description:
            - "Information about this virtual server."

    mssqlserverversion:
        choices:
            - '70'
            - '2000'
            - '2000SP1'
            - '2005'
            - '2008'
            - '2008R2'
            - '2012'
            - '2014'
        description:
            - "The version of the MSSQL server."

    l2conn:
        description:
            - "Use L2 Parameters to identify a connection."
        type: bool

    mysqlprotocolversion:
        description:
            - "The protocol version returned by the mysql vserver."

    mysqlserverversion:
        description:
            - "The server version string returned by the mysql vserver."
            - "Minimum length = 1"
            - "Maximum length = 31"

    mysqlcharacterset:
        description:
            - "The character set returned by the mysql vserver."

    mysqlservercapabilities:
        description:
            - "The server capabilities returned by the mysql vserver."

    appflowlog:
        choices:
            - 'enabled'
            - 'disabled'
        description:
            - "Enable logging appflow flow information."

    netprofile:
        description:
            - "The name of the network profile."
            - "Minimum length = 1"
            - "Maximum length = 127"

    icmpvsrresponse:
        choices:
            - 'PASSIVE'
            - 'ACTIVE'
        description:
            - "Can be active or passive."

    rhistate:
        choices:
            - 'PASSIVE'
            - 'ACTIVE'
        description:
            - "A host route is injected according to the setting on the virtual servers"
            - >-
                * If set to C(PASSIVE) on all the virtual servers that share the IP address, the appliance always
                injects the hostroute.
            - >-
                * If set to C(ACTIVE) on all the virtual servers that share the IP address, the appliance injects even
                if one virtual server is UP.
            - >-
                * If set to C(ACTIVE) on some virtual servers and C(PASSIVE) on the others, the appliance, injects even if
                one virtual server set to C(ACTIVE) is UP.

    authnprofile:
        description:
            - "Name of the authentication profile to be used when authentication is turned on."

    dnsprofilename:
        description:
            - >-
                Name of the DNS profile to be associated with the VServer. DNS profile properties will applied to the
                transactions processed by a VServer. This parameter is valid only for DNS and DNS-TCP VServers.
            - "Minimum length = 1"
            - "Maximum length = 127"

    domainname:
        description:
            - "Domain name for which to change the time to live (TTL) and/or backup service IP address."
            - "Minimum length = 1"

    ttl:
        description:
            - "."
            - "Minimum value = C(1)"

    backupip:
        description:
            - "."
            - "Minimum length = 1"

    cookiedomain:
        description:
            - "."
            - "Minimum length = 1"

    cookietimeout:
        description:
            - "."
            - "Minimum value = C(0)"
            - "Maximum value = C(1440)"

    sitedomainttl:
        description:
            - "."
            - "Minimum value = C(1)"

    lbvserver:
        description:
            - The default Load Balancing virtual server.
        version_added: "2.5"

    ssl_certkey:
        description:
            - The name of the ssl certificate that is bound to this service.
            - The ssl certificate must already exist.
            - Creating the certificate can be done with the M(netscaler_ssl_certkey) module.
            - This option is only applicable only when C(servicetype) is C(SSL).
        version_added: "2.5"

    disabled:
        description:
            - When set to C(yes) the cs vserver will be disabled.
            - When set to C(no) the cs vserver will be enabled.
            - >-
                Note that due to limitations of the underlying NITRO API a C(disabled) state change alone
                does not cause the module result to report a changed status.
        type: bool
        default: 'no'

extends_documentation_fragment: netscaler
requirements:
    - nitro python sdk
'''

EXAMPLES = '''
# policy_1 must have been already created with the netscaler_cs_policy module
# lbvserver_1 must have been already created with the netscaler_lb_vserver module

- name: Setup content switching vserver
  delegate_to: localhost
  netscaler_cs_vserver:
    nsip: 172.18.0.2
    nitro_user: nsroot
    nitro_pass: nsroot

    state: present

    name: cs_vserver_1
    ipv46: 192.168.1.1
    port: 80
    servicetype: HTTP

    policybindings:
      - policyname: policy_1
        targetlbvserver: lbvserver_1
'''

RETURN = '''
loglines:
    description: list of logged messages by the module
    returned: always
    type: list
    sample: ['message 1', 'message 2']

msg:
    description: Message detailing the failure reason
    returned: failure
    type: str
    sample: "Action does not exist"

diff:
    description: List of differences between the actual configured object and the configuration specified in the module
    returned: failure
    type: dict
    sample: { 'clttimeout': 'difference. ours: (float) 100.0 other: (float) 60.0' }
'''

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.netscaler.netscaler import (
    ConfigProxy,
    get_nitro_client,
    netscaler_common_arguments,
    log,
    loglines,
    ensure_feature_is_enabled,
    get_immutables_intersection
)
try:
    from nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver import csvserver
    from nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver_lbvserver_binding import csvserver_lbvserver_binding
    from nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver_cspolicy_binding import csvserver_cspolicy_binding
    from nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding import sslvserver_sslcertkey_binding
    from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
    PYTHON_SDK_IMPORTED = True
except ImportError as e:
    PYTHON_SDK_IMPORTED = False


def cs_vserver_exists(client, module):
    if csvserver.count_filtered(client, 'name:%s' % module.params['name']) > 0:
        return True
    else:
        return False


def cs_vserver_identical(client, module, csvserver_proxy):
    csvserver_list = csvserver.get_filtered(client, 'name:%s' % module.params['name'])
    diff_dict = csvserver_proxy.diff_object(csvserver_list[0])
    if len(diff_dict) == 0:
        return True
    else:
        return False


def get_configured_policybindings(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_default_lb_vserver(client, module):
    try:
        default_lb_vserver = csvserver_lbvserver_binding.get(client, module.params['name'])
        return default_lb_vserver[0]
    except nitro_exception as e:
        if e.errorcode == 258:
            return csvserver_lbvserver_binding()
        else:
            raise


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 sync_default_lb_vserver(client, module):
    d = get_default_lb_vserver(client, module)

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

        if not configured.has_equal_attributes(d):
            if d.name is not None:
                log('Deleting default lb vserver %s' % d.lbvserver)
                csvserver_lbvserver_binding.delete(client, d)
            log('Adding default lb vserver %s' % configured.lbvserver)
            configured.add()
    else:
        if d.name is not None:
            log('Deleting default lb vserver %s' % d.lbvserver)
            csvserver_lbvserver_binding.delete(client, d)


def get_actual_policybindings(client, module):
    log('Getting actual policy bindigs')
    bindings = {}
    try:
        count = csvserver_cspolicy_binding.count(client, name=module.params['name'])
        if count == 0:
            return bindings
    except nitro_exception as e:
        if e.errorcode == 258:
            return bindings
        else:
            raise

    for binding in csvserver_cspolicy_binding.get(client, name=module.params['name']):
        key = binding.policyname
        bindings[key] = binding

    return bindings


def cs_policybindings_identical(client, module):
    log('Checking policy bindings identical')
    actual_bindings = get_actual_policybindings(client, module)
    configured_bindings = get_configured_policybindings(client, module)

    actual_keyset = set(actual_bindings.keys())
    configured_keyset = set(configured_bindings.keys())
    if len(actual_keyset ^ configured_keyset) > 0:
        return False

    # Compare item to item
    for key in actual_bindings.keys():
        configured_binding_proxy = configured_bindings[key]
        actual_binding_object = actual_bindings[key]
        if not configured_binding_proxy.has_equal_attributes(actual_binding_object):
            return False

    # Fallthrough to success
    return True


def sync_cs_policybindings(client, module):
    log('Syncing cs policybindings')
    actual_bindings = get_actual_policybindings(client, module)
    configured_bindings = get_configured_policybindings(client, module)

    # Delete actual bindings not in configured
    delete_keys = list(set(actual_bindings.keys()) - set(configured_bindings.keys()))
    for key in delete_keys:
        log('Deleting binding for policy %s' % key)
        csvserver_cspolicy_binding.delete(client, actual_bindings[key])

    # Add configured bindings not in actual
    add_keys = list(set(configured_bindings.keys()) - set(actual_bindings.keys()))
    for key in add_keys:
        log('Adding binding for policy %s' % key)
        configured_bindings[key].add()

    # Update existing if changed
    modify_keys = list(set(configured_bindings.keys()) & set(actual_bindings.keys()))
    for key in modify_keys:
        if not configured_bindings[key].has_equal_attributes(actual_bindings[key]):
            log('Updating binding for policy %s' % key)
            csvserver_cspolicy_binding.delete(client, actual_bindings[key])
            configured_bindings[key].add()


def ssl_certkey_bindings_identical(client, module):
    log('Checking if ssl cert key bindings are identical')
    vservername = module.params['name']
    if sslvserver_sslcertkey_binding.count(client, vservername) == 0:
        bindings = []
    else:
        bindings = sslvserver_sslcertkey_binding.get(client, vservername)

    if module.params['ssl_certkey'] is None:
        if len(bindings) == 0:
            return True
        else:
            return False
    else:
        certificate_list = [item.certkeyname for item in bindings]
        if certificate_list == [module.params['ssl_certkey']]:
            return True
        else:
            return False


def ssl_certkey_bindings_sync(client, module):
    log('Syncing certkey bindings')
    vservername = module.params['name']
    if sslvserver_sslcertkey_binding.count(client, vservername) == 0:
        bindings = []
    else:
        bindings = sslvserver_sslcertkey_binding.get(client, vservername)

    # Delete existing bindings
    for binding in bindings:
        log('Deleting existing binding for certkey %s' % binding.certkeyname)
        sslvserver_sslcertkey_binding.delete(client, binding)

    # Add binding if appropriate
    if module.params['ssl_certkey'] is not None:
        log('Adding binding for certkey %s' % module.params['ssl_certkey'])
        binding = sslvserver_sslcertkey_binding()
        binding.vservername = module.params['name']
        binding.certkeyname = module.params['ssl_certkey']
        sslvserver_sslcertkey_binding.add(client, binding)


def diff_list(client, module, csvserver_proxy):
    csvserver_list = csvserver.get_filtered(client, 'name:%s' % module.params['name'])
    return csvserver_proxy.diff_object(csvserver_list[0])


def do_state_change(client, module, csvserver_proxy):
    if module.params['disabled']:
        log('Disabling cs vserver')
        result = csvserver.disable(client, csvserver_proxy.actual)
    else:
        log('Enabling cs vserver')
        result = csvserver.enable(client, csvserver_proxy.actual)
    return result


def main():

    module_specific_arguments = dict(

        name=dict(type='str'),
        td=dict(type='float'),
        servicetype=dict(
            type='str',
            choices=[
                'HTTP',
                'SSL',
                'TCP',
                'FTP',
                'RTSP',
                'SSL_TCP',
                'UDP',
                'DNS',
                'SIP_UDP',
                'SIP_TCP',
                'SIP_SSL',
                'ANY',
                'RADIUS',
                'RDP',
                'MYSQL',
                'MSSQL',
                'DIAMETER',
                'SSL_DIAMETER',
                'DNS_TCP',
                'ORACLE',
                'SMPP'
            ]
        ),

        ipv46=dict(type='str'),
        dnsrecordtype=dict(
            type='str',
            choices=[
                'A',
                'AAAA',
                'CNAME',
                'NAPTR',
            ]
        ),
        ippattern=dict(type='str'),
        ipmask=dict(type='str'),
        range=dict(type='float'),
        port=dict(type='int'),
        stateupdate=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        cacheable=dict(type='bool'),
        redirecturl=dict(type='str'),
        clttimeout=dict(type='float'),
        precedence=dict(
            type='str',
            choices=[
                'RULE',
                'URL',
            ]
        ),
        casesensitive=dict(type='bool'),
        somethod=dict(
            type='str',
            choices=[
                'CONNECTION',
                'DYNAMICCONNECTION',
                'BANDWIDTH',
                'HEALTH',
                'NONE',
            ]
        ),
        sopersistence=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        sopersistencetimeout=dict(type='float'),
        sothreshold=dict(type='float'),
        sobackupaction=dict(
            type='str',
            choices=[
                'DROP',
                'ACCEPT',
                'REDIRECT',
            ]
        ),
        redirectportrewrite=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        downstateflush=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        disableprimaryondown=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        insertvserveripport=dict(
            type='str',
            choices=[
                'OFF',
                'VIPADDR',
                'V6TOV4MAPPING',
            ]
        ),
        vipheader=dict(type='str'),
        rtspnat=dict(type='bool'),
        authenticationhost=dict(type='str'),
        authentication=dict(type='bool'),
        listenpolicy=dict(type='str'),
        authn401=dict(type='bool'),
        authnvsname=dict(type='str'),
        push=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        pushvserver=dict(type='str'),
        pushlabel=dict(type='str'),
        pushmulticlients=dict(type='bool'),
        tcpprofilename=dict(type='str'),
        httpprofilename=dict(type='str'),
        dbprofilename=dict(type='str'),
        oracleserverversion=dict(
            type='str',
            choices=[
                '10G',
                '11G',
            ]
        ),
        comment=dict(type='str'),
        mssqlserverversion=dict(
            type='str',
            choices=[
                '70',
                '2000',
                '2000SP1',
                '2005',
                '2008',
                '2008R2',
                '2012',
                '2014',
            ]
        ),
        l2conn=dict(type='bool'),
        mysqlprotocolversion=dict(type='float'),
        mysqlserverversion=dict(type='str'),
        mysqlcharacterset=dict(type='float'),
        mysqlservercapabilities=dict(type='float'),
        appflowlog=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        netprofile=dict(type='str'),
        icmpvsrresponse=dict(
            type='str',
            choices=[
                'PASSIVE',
                'ACTIVE',
            ]
        ),
        rhistate=dict(
            type='str',
            choices=[
                'PASSIVE',
                'ACTIVE',
            ]
        ),
        authnprofile=dict(type='str'),
        dnsprofilename=dict(type='str'),
    )

    hand_inserted_arguments = dict(
        policybindings=dict(type='list'),
        ssl_certkey=dict(type='str'),
        disabled=dict(
            type='bool',
            default=False
        ),
        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)


if __name__ == "__main__":
    main()