summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/google/gcp_container_cluster.py
blob: 030094fee8fc1375abb98e5183b3997952b37368 (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
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
#     ***     AUTO GENERATED CODE    ***    AUTO GENERATED CODE     ***
#
# ----------------------------------------------------------------------------
#
#     This file is automatically generated by Magic Modules and manual
#     changes will be clobbered when the file is regenerated.
#
#     Please read more about how to change this file at
#     https://www.github.com/GoogleCloudPlatform/magic-modules
#
# ----------------------------------------------------------------------------

from __future__ import absolute_import, division, print_function

__metaclass__ = type

################################################################################
# Documentation
################################################################################

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

DOCUMENTATION = '''
---
module: gcp_container_cluster
description:
- A Google Container Engine cluster.
short_description: Creates a GCP Cluster
version_added: 2.6
author: Google Inc. (@googlecloudplatform)
requirements:
- python >= 2.6
- requests >= 2.18.4
- google-auth >= 1.3.0
options:
  state:
    description:
    - Whether the given object should exist in GCP
    choices:
    - present
    - absent
    default: present
  name:
    description:
    - The name of this cluster. The name must be unique within this project and location,
      and can be up to 40 characters. Must be Lowercase letters, numbers, and hyphens
      only. Must start with a letter. Must end with a number or a letter.
    required: false
    type: str
  description:
    description:
    - An optional description of this cluster.
    required: false
    type: str
  initial_node_count:
    description:
    - The number of nodes to create in this cluster. You must ensure that your Compute
      Engine resource quota is sufficient for this number of instances. You must also
      have available firewall and routes quota. For requests, this field should only
      be used in lieu of a "nodePool" object, since this configuration (along with
      the "nodeConfig") will be used to create a "NodePool" object with an auto-generated
      name. Do not use this and a nodePool at the same time.
    - This field has been deprecated. Please use nodePool.initial_node_count instead.
    required: false
    type: int
  node_config:
    description:
    - Parameters used in creating the cluster's nodes.
    - For requests, this field should only be used in lieu of a "nodePool" object,
      since this configuration (along with the "initialNodeCount") will be used to
      create a "NodePool" object with an auto-generated name. Do not use this and
      a nodePool at the same time. For responses, this field will be populated with
      the node configuration of the first node pool. If unspecified, the defaults
      are used.
    required: false
    type: dict
    suboptions:
      machine_type:
        description:
        - The name of a Google Compute Engine machine type (e.g.
        - n1-standard-1). If unspecified, the default machine type is n1-standard-1.
        required: false
        type: str
      disk_size_gb:
        description:
        - Size of the disk attached to each node, specified in GB. The smallest allowed
          disk size is 10GB. If unspecified, the default disk size is 100GB.
        required: false
        type: int
      oauth_scopes:
        description:
        - The set of Google API scopes to be made available on all of the node VMs
          under the "default" service account.
        - 'The following scopes are recommended, but not required, and by default
          are not included: U(https://www.googleapis.com/auth/compute) is required
          for mounting persistent storage on your nodes.'
        - U(https://www.googleapis.com/auth/devstorage.read_only) is required for
          communicating with gcr.io (the Google Container Registry).
        - If unspecified, no scopes are added, unless Cloud Logging or Cloud Monitoring
          are enabled, in which case their required scopes will be added.
        required: false
        type: list
      service_account:
        description:
        - The Google Cloud Platform Service Account to be used by the node VMs. If
          no Service Account is specified, the "default" service account is used.
        required: false
        type: str
      metadata:
        description:
        - The metadata key/value pairs assigned to instances in the cluster.
        - 'Keys must conform to the regexp [a-zA-Z0-9-_]+ and be less than 128 bytes
          in length. These are reflected as part of a URL in the metadata server.
          Additionally, to avoid ambiguity, keys must not conflict with any other
          metadata keys for the project or be one of the four reserved keys: "instance-template",
          "kube-env", "startup-script", and "user-data" Values are free-form strings,
          and only have meaning as interpreted by the image running in the instance.
          The only restriction placed on them is that each value''s size must be less
          than or equal to 32 KB.'
        - The total size of all keys and values must be less than 512 KB.
        - 'An object containing a list of "key": value pairs.'
        - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.'
        required: false
        type: dict
      image_type:
        description:
        - The image type to use for this node. Note that for a given image type, the
          latest version of it will be used.
        required: false
        type: str
      labels:
        description:
        - 'The map of Kubernetes labels (key/value pairs) to be applied to each node.
          These will added in addition to any default label(s) that Kubernetes may
          apply to the node. In case of conflict in label keys, the applied set may
          differ depending on the Kubernetes version -- it''s best to assume the behavior
          is undefined and conflicts should be avoided. For more information, including
          usage and the valid values, see: U(http://kubernetes.io/v1.1/docs/user-guide/labels.html)
          An object containing a list of "key": value pairs.'
        - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.'
        required: false
        type: dict
      local_ssd_count:
        description:
        - The number of local SSD disks to be attached to the node.
        - 'The limit for this value is dependant upon the maximum number of disks
          available on a machine per zone. See: U(https://cloud.google.com/compute/docs/disks/local-ssd#local_ssd_limits)
          for more information.'
        required: false
        type: int
      tags:
        description:
        - The list of instance tags applied to all nodes. Tags are used to identify
          valid sources or targets for network firewalls and are specified by the
          client during cluster or node pool creation. Each tag within the list must
          comply with RFC1035.
        required: false
        type: list
      preemptible:
        description:
        - 'Whether the nodes are created as preemptible VM instances. See: U(https://cloud.google.com/compute/docs/instances/preemptible)
          for more information about preemptible VM instances.'
        required: false
        type: bool
      accelerators:
        description:
        - A list of hardware accelerators to be attached to each node. See U(https://cloud.google.com/compute/docs/gpus)
          for more information about support for GPUs.
        required: false
        type: list
        version_added: 2.9
        suboptions:
          accelerator_count:
            description:
            - The number of accelerator cards exposed to an instance.
            required: false
            type: str
          accelerator_type:
            description:
            - The accelerator type resource name.
            required: false
            type: str
      disk_type:
        description:
        - Type of the disk attached to each node (e.g. 'pd-standard' or 'pd-ssd')
          If unspecified, the default disk type is 'pd-standard' .
        required: false
        type: str
        version_added: 2.9
      min_cpu_platform:
        description:
        - Minimum CPU platform to be used by this instance. The instance may be scheduled
          on the specified or newer CPU platform.
        required: false
        type: str
        version_added: 2.9
      taints:
        description:
        - List of kubernetes taints to be applied to each node.
        - 'For more information, including usage and the valid values, see: U(https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/)
          .'
        required: false
        type: list
        version_added: 2.9
        suboptions:
          key:
            description:
            - Key for taint.
            required: false
            type: str
          value:
            description:
            - Value for taint.
            required: false
            type: str
          effect:
            description:
            - Effect for taint.
            - 'Some valid choices include: "EFFECT_UNSPECIFIED", "NO_SCHEDULE", "PREFER_NO_SCHEDULE",
              "NO_EXECUTE"'
            required: false
            type: str
  master_auth:
    description:
    - The authentication information for accessing the master endpoint.
    required: false
    type: dict
    suboptions:
      username:
        description:
        - The username to use for HTTP basic authentication to the master endpoint.
        required: false
        type: str
      password:
        description:
        - The password to use for HTTP basic authentication to the master endpoint.
          Because the master endpoint is open to the Internet, you should create a
          strong password with a minimum of 16 characters.
        required: false
        type: str
      client_certificate_config:
        description:
        - Configuration for client certificate authentication on the cluster. For
          clusters before v1.12, if no configuration is specified, a client certificate
          is issued.
        required: false
        type: dict
        version_added: 2.9
        suboptions:
          issue_client_certificate:
            description:
            - Issue a client certificate.
            required: false
            type: bool
  logging_service:
    description:
    - 'The logging service the cluster should use to write logs. Currently available
      options: logging.googleapis.com - the Google Cloud Logging service.'
    - none - no logs will be exported from the cluster.
    - if left as an empty string,logging.googleapis.com will be used.
    - 'Some valid choices include: "logging.googleapis.com", "none"'
    required: false
    type: str
  monitoring_service:
    description:
    - The monitoring service the cluster should use to write metrics.
    - 'Currently available options: monitoring.googleapis.com - the Google Cloud Monitoring
      service.'
    - none - no metrics will be exported from the cluster.
    - if left as an empty string, monitoring.googleapis.com will be used.
    - 'Some valid choices include: "monitoring.googleapis.com", "none"'
    required: false
    type: str
  network:
    description:
    - The name of the Google Compute Engine network to which the cluster is connected.
      If left unspecified, the default network will be used.
    required: false
    type: str
  private_cluster_config:
    description:
    - Configuration for a private cluster.
    required: false
    type: dict
    version_added: 2.8
    suboptions:
      enable_private_nodes:
        description:
        - Whether nodes have internal IP addresses only. If enabled, all nodes are
          given only RFC 1918 private addresses and communicate with the master via
          private networking.
        required: false
        type: bool
      enable_private_endpoint:
        description:
        - Whether the master's internal IP address is used as the cluster endpoint.
        required: false
        type: bool
      master_ipv4_cidr_block:
        description:
        - The IP range in CIDR notation to use for the hosted master network. This
          range will be used for assigning internal IP addresses to the master or
          set of masters, as well as the ILB VIP. This range must not overlap with
          any other ranges in use within the cluster's network.
        required: false
        type: str
  cluster_ipv4_cidr:
    description:
    - The IP address range of the container pods in this cluster, in CIDR notation
      (e.g. 10.96.0.0/14). Leave blank to have one automatically chosen or specify
      a /14 block in 10.0.0.0/8.
    required: false
    type: str
  addons_config:
    description:
    - Configurations for the various addons available to run in the cluster.
    required: false
    type: dict
    suboptions:
      http_load_balancing:
        description:
        - Configuration for the HTTP (L7) load balancing controller addon, which makes
          it easy to set up HTTP load balancers for services in a cluster.
        required: false
        type: dict
        suboptions:
          disabled:
            description:
            - Whether the HTTP Load Balancing controller is enabled in the cluster.
              When enabled, it runs a small pod in the cluster that manages the load
              balancers.
            required: false
            type: bool
      horizontal_pod_autoscaling:
        description:
        - Configuration for the horizontal pod autoscaling feature, which increases
          or decreases the number of replica pods a replication controller has based
          on the resource usage of the existing pods.
        required: false
        type: dict
        suboptions:
          disabled:
            description:
            - Whether the Horizontal Pod Autoscaling feature is enabled in the cluster.
              When enabled, it ensures that a Heapster pod is running in the cluster,
              which is also used by the Cloud Monitoring service.
            required: false
            type: bool
      network_policy_config:
        description:
        - Configuration for NetworkPolicy. This only tracks whether the addon is enabled
          or not on the Master, it does not track whether network policy is enabled
          for the nodes.
        required: false
        type: dict
        version_added: 2.9
        suboptions:
          disabled:
            description:
            - Whether NetworkPolicy is enabled for this cluster.
            required: false
            type: bool
  subnetwork:
    description:
    - The name of the Google Compute Engine subnetwork to which the cluster is connected.
    required: false
    type: str
  locations:
    description:
    - The list of Google Compute Engine zones in which the cluster's nodes should
      be located.
    required: false
    type: list
    aliases:
    - nodeLocations
    version_added: 2.9
  resource_labels:
    description:
    - The resource labels for the cluster to use to annotate any related Google Compute
      Engine resources.
    required: false
    type: dict
    version_added: 2.9
  legacy_abac:
    description:
    - Configuration for the legacy ABAC authorization mode.
    required: false
    type: dict
    version_added: 2.9
    suboptions:
      enabled:
        description:
        - Whether the ABAC authorizer is enabled for this cluster. When enabled, identities
          in the system, including service accounts, nodes, and controllers, will
          have statically granted permissions beyond those provided by the RBAC configuration
          or IAM.
        required: false
        type: bool
  network_policy:
    description:
    - Configuration options for the NetworkPolicy feature.
    required: false
    type: dict
    version_added: 2.9
    suboptions:
      provider:
        description:
        - The selected network policy provider.
        - 'Some valid choices include: "PROVIDER_UNSPECIFIED", "CALICO"'
        required: false
        type: str
      enabled:
        description:
        - Whether network policy is enabled on the cluster.
        required: false
        type: bool
  default_max_pods_constraint:
    description:
    - The default constraint on the maximum number of pods that can be run simultaneously
      on a node in the node pool of this cluster.
    - Only honored if cluster created with IP Alias support.
    required: false
    type: dict
    version_added: 2.9
    suboptions:
      max_pods_per_node:
        description:
        - Constraint enforced on the max num of pods per node.
        required: false
        type: str
  enable_tpu:
    description:
    - Enable the ability to use Cloud TPUs in this cluster.
    required: false
    type: bool
    version_added: 2.9
  tpu_ipv4_cidr_block:
    description:
    - The IP address range of the Cloud TPUs in this cluster, in CIDR notation.
    required: false
    type: str
    version_added: 2.9
  location:
    description:
    - The location where the cluster is deployed.
    required: true
    type: str
    aliases:
    - zone
    version_added: 2.8
  kubectl_path:
    description:
    - The path that the kubectl config file will be written to.
    - The file will not be created if this path is unset.
    - Any existing file at this path will be completely overwritten.
    - This requires the PyYaml library.
    required: false
    type: str
    version_added: 2.9
  kubectl_context:
    description:
    - The name of the context for the kubectl config file. Will default to the cluster
      name.
    required: false
    type: str
    version_added: 2.9
extends_documentation_fragment: gcp
'''

EXAMPLES = '''
- name: create a cluster
  gcp_container_cluster:
    name: my-cluster
    initial_node_count: 2
    master_auth:
      username: cluster_admin
      password: my-secret-password
    node_config:
      machine_type: n1-standard-4
      disk_size_gb: 500
    location: us-central1-a
    project: test_project
    auth_kind: serviceaccount
    service_account_file: "/tmp/auth.pem"
    state: present
'''

RETURN = '''
name:
  description:
  - The name of this cluster. The name must be unique within this project and location,
    and can be up to 40 characters. Must be Lowercase letters, numbers, and hyphens
    only. Must start with a letter. Must end with a number or a letter.
  returned: success
  type: str
description:
  description:
  - An optional description of this cluster.
  returned: success
  type: str
initialNodeCount:
  description:
  - The number of nodes to create in this cluster. You must ensure that your Compute
    Engine resource quota is sufficient for this number of instances. You must also
    have available firewall and routes quota. For requests, this field should only
    be used in lieu of a "nodePool" object, since this configuration (along with the
    "nodeConfig") will be used to create a "NodePool" object with an auto-generated
    name. Do not use this and a nodePool at the same time.
  - This field has been deprecated. Please use nodePool.initial_node_count instead.
  returned: success
  type: int
nodeConfig:
  description:
  - Parameters used in creating the cluster's nodes.
  - For requests, this field should only be used in lieu of a "nodePool" object, since
    this configuration (along with the "initialNodeCount") will be used to create
    a "NodePool" object with an auto-generated name. Do not use this and a nodePool
    at the same time. For responses, this field will be populated with the node configuration
    of the first node pool. If unspecified, the defaults are used.
  returned: success
  type: complex
  contains:
    machineType:
      description:
      - The name of a Google Compute Engine machine type (e.g.
      - n1-standard-1). If unspecified, the default machine type is n1-standard-1.
      returned: success
      type: str
    diskSizeGb:
      description:
      - Size of the disk attached to each node, specified in GB. The smallest allowed
        disk size is 10GB. If unspecified, the default disk size is 100GB.
      returned: success
      type: int
    oauthScopes:
      description:
      - The set of Google API scopes to be made available on all of the node VMs under
        the "default" service account.
      - 'The following scopes are recommended, but not required, and by default are
        not included: U(https://www.googleapis.com/auth/compute) is required for mounting
        persistent storage on your nodes.'
      - U(https://www.googleapis.com/auth/devstorage.read_only) is required for communicating
        with gcr.io (the Google Container Registry).
      - If unspecified, no scopes are added, unless Cloud Logging or Cloud Monitoring
        are enabled, in which case their required scopes will be added.
      returned: success
      type: list
    serviceAccount:
      description:
      - The Google Cloud Platform Service Account to be used by the node VMs. If no
        Service Account is specified, the "default" service account is used.
      returned: success
      type: str
    metadata:
      description:
      - The metadata key/value pairs assigned to instances in the cluster.
      - 'Keys must conform to the regexp [a-zA-Z0-9-_]+ and be less than 128 bytes
        in length. These are reflected as part of a URL in the metadata server. Additionally,
        to avoid ambiguity, keys must not conflict with any other metadata keys for
        the project or be one of the four reserved keys: "instance-template", "kube-env",
        "startup-script", and "user-data" Values are free-form strings, and only have
        meaning as interpreted by the image running in the instance. The only restriction
        placed on them is that each value''s size must be less than or equal to 32
        KB.'
      - The total size of all keys and values must be less than 512 KB.
      - 'An object containing a list of "key": value pairs.'
      - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.'
      returned: success
      type: dict
    imageType:
      description:
      - The image type to use for this node. Note that for a given image type, the
        latest version of it will be used.
      returned: success
      type: str
    labels:
      description:
      - 'The map of Kubernetes labels (key/value pairs) to be applied to each node.
        These will added in addition to any default label(s) that Kubernetes may apply
        to the node. In case of conflict in label keys, the applied set may differ
        depending on the Kubernetes version -- it''s best to assume the behavior is
        undefined and conflicts should be avoided. For more information, including
        usage and the valid values, see: U(http://kubernetes.io/v1.1/docs/user-guide/labels.html)
        An object containing a list of "key": value pairs.'
      - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.'
      returned: success
      type: dict
    localSsdCount:
      description:
      - The number of local SSD disks to be attached to the node.
      - 'The limit for this value is dependant upon the maximum number of disks available
        on a machine per zone. See: U(https://cloud.google.com/compute/docs/disks/local-ssd#local_ssd_limits)
        for more information.'
      returned: success
      type: int
    tags:
      description:
      - The list of instance tags applied to all nodes. Tags are used to identify
        valid sources or targets for network firewalls and are specified by the client
        during cluster or node pool creation. Each tag within the list must comply
        with RFC1035.
      returned: success
      type: list
    preemptible:
      description:
      - 'Whether the nodes are created as preemptible VM instances. See: U(https://cloud.google.com/compute/docs/instances/preemptible)
        for more information about preemptible VM instances.'
      returned: success
      type: bool
    accelerators:
      description:
      - A list of hardware accelerators to be attached to each node. See U(https://cloud.google.com/compute/docs/gpus)
        for more information about support for GPUs.
      returned: success
      type: complex
      contains:
        acceleratorCount:
          description:
          - The number of accelerator cards exposed to an instance.
          returned: success
          type: str
        acceleratorType:
          description:
          - The accelerator type resource name.
          returned: success
          type: str
    diskType:
      description:
      - Type of the disk attached to each node (e.g. 'pd-standard' or 'pd-ssd') If
        unspecified, the default disk type is 'pd-standard' .
      returned: success
      type: str
    minCpuPlatform:
      description:
      - Minimum CPU platform to be used by this instance. The instance may be scheduled
        on the specified or newer CPU platform.
      returned: success
      type: str
    taints:
      description:
      - List of kubernetes taints to be applied to each node.
      - 'For more information, including usage and the valid values, see: U(https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/)
        .'
      returned: success
      type: complex
      contains:
        key:
          description:
          - Key for taint.
          returned: success
          type: str
        value:
          description:
          - Value for taint.
          returned: success
          type: str
        effect:
          description:
          - Effect for taint.
          returned: success
          type: str
masterAuth:
  description:
  - The authentication information for accessing the master endpoint.
  returned: success
  type: complex
  contains:
    username:
      description:
      - The username to use for HTTP basic authentication to the master endpoint.
      returned: success
      type: str
    password:
      description:
      - The password to use for HTTP basic authentication to the master endpoint.
        Because the master endpoint is open to the Internet, you should create a strong
        password with a minimum of 16 characters.
      returned: success
      type: str
    clientCertificateConfig:
      description:
      - Configuration for client certificate authentication on the cluster. For clusters
        before v1.12, if no configuration is specified, a client certificate is issued.
      returned: success
      type: complex
      contains:
        issueClientCertificate:
          description:
          - Issue a client certificate.
          returned: success
          type: bool
    clusterCaCertificate:
      description:
      - Base64-encoded public certificate that is the root of trust for the cluster.
      returned: success
      type: str
    clientCertificate:
      description:
      - Base64-encoded public certificate used by clients to authenticate to the cluster
        endpoint.
      returned: success
      type: str
    clientKey:
      description:
      - Base64-encoded private key used by clients to authenticate to the cluster
        endpoint.
      returned: success
      type: str
loggingService:
  description:
  - 'The logging service the cluster should use to write logs. Currently available
    options: logging.googleapis.com - the Google Cloud Logging service.'
  - none - no logs will be exported from the cluster.
  - if left as an empty string,logging.googleapis.com will be used.
  returned: success
  type: str
monitoringService:
  description:
  - The monitoring service the cluster should use to write metrics.
  - 'Currently available options: monitoring.googleapis.com - the Google Cloud Monitoring
    service.'
  - none - no metrics will be exported from the cluster.
  - if left as an empty string, monitoring.googleapis.com will be used.
  returned: success
  type: str
network:
  description:
  - The name of the Google Compute Engine network to which the cluster is connected.
    If left unspecified, the default network will be used.
  returned: success
  type: str
privateClusterConfig:
  description:
  - Configuration for a private cluster.
  returned: success
  type: complex
  contains:
    enablePrivateNodes:
      description:
      - Whether nodes have internal IP addresses only. If enabled, all nodes are given
        only RFC 1918 private addresses and communicate with the master via private
        networking.
      returned: success
      type: bool
    enablePrivateEndpoint:
      description:
      - Whether the master's internal IP address is used as the cluster endpoint.
      returned: success
      type: bool
    masterIpv4CidrBlock:
      description:
      - The IP range in CIDR notation to use for the hosted master network. This range
        will be used for assigning internal IP addresses to the master or set of masters,
        as well as the ILB VIP. This range must not overlap with any other ranges
        in use within the cluster's network.
      returned: success
      type: str
    privateEndpoint:
      description:
      - The internal IP address of this cluster's master endpoint.
      returned: success
      type: str
    publicEndpoint:
      description:
      - The external IP address of this cluster's master endpoint.
      returned: success
      type: str
clusterIpv4Cidr:
  description:
  - The IP address range of the container pods in this cluster, in CIDR notation (e.g.
    10.96.0.0/14). Leave blank to have one automatically chosen or specify a /14 block
    in 10.0.0.0/8.
  returned: success
  type: str
addonsConfig:
  description:
  - Configurations for the various addons available to run in the cluster.
  returned: success
  type: complex
  contains:
    httpLoadBalancing:
      description:
      - Configuration for the HTTP (L7) load balancing controller addon, which makes
        it easy to set up HTTP load balancers for services in a cluster.
      returned: success
      type: complex
      contains:
        disabled:
          description:
          - Whether the HTTP Load Balancing controller is enabled in the cluster.
            When enabled, it runs a small pod in the cluster that manages the load
            balancers.
          returned: success
          type: bool
    horizontalPodAutoscaling:
      description:
      - Configuration for the horizontal pod autoscaling feature, which increases
        or decreases the number of replica pods a replication controller has based
        on the resource usage of the existing pods.
      returned: success
      type: complex
      contains:
        disabled:
          description:
          - Whether the Horizontal Pod Autoscaling feature is enabled in the cluster.
            When enabled, it ensures that a Heapster pod is running in the cluster,
            which is also used by the Cloud Monitoring service.
          returned: success
          type: bool
    networkPolicyConfig:
      description:
      - Configuration for NetworkPolicy. This only tracks whether the addon is enabled
        or not on the Master, it does not track whether network policy is enabled
        for the nodes.
      returned: success
      type: complex
      contains:
        disabled:
          description:
          - Whether NetworkPolicy is enabled for this cluster.
          returned: success
          type: bool
subnetwork:
  description:
  - The name of the Google Compute Engine subnetwork to which the cluster is connected.
  returned: success
  type: str
locations:
  description:
  - The list of Google Compute Engine zones in which the cluster's nodes should be
    located.
  returned: success
  type: list
resourceLabels:
  description:
  - The resource labels for the cluster to use to annotate any related Google Compute
    Engine resources.
  returned: success
  type: dict
labelFingerprint:
  description:
  - The fingerprint of the set of labels for this cluster.
  returned: success
  type: str
legacyAbac:
  description:
  - Configuration for the legacy ABAC authorization mode.
  returned: success
  type: complex
  contains:
    enabled:
      description:
      - Whether the ABAC authorizer is enabled for this cluster. When enabled, identities
        in the system, including service accounts, nodes, and controllers, will have
        statically granted permissions beyond those provided by the RBAC configuration
        or IAM.
      returned: success
      type: bool
networkPolicy:
  description:
  - Configuration options for the NetworkPolicy feature.
  returned: success
  type: complex
  contains:
    provider:
      description:
      - The selected network policy provider.
      returned: success
      type: str
    enabled:
      description:
      - Whether network policy is enabled on the cluster.
      returned: success
      type: bool
defaultMaxPodsConstraint:
  description:
  - The default constraint on the maximum number of pods that can be run simultaneously
    on a node in the node pool of this cluster.
  - Only honored if cluster created with IP Alias support.
  returned: success
  type: complex
  contains:
    maxPodsPerNode:
      description:
      - Constraint enforced on the max num of pods per node.
      returned: success
      type: str
endpoint:
  description:
  - The IP address of this cluster's master endpoint.
  - The endpoint can be accessed from the internet at https://username:password@endpoint/
    See the masterAuth property of this resource for username and password information.
  returned: success
  type: str
initialClusterVersion:
  description:
  - The software version of the master endpoint and kubelets used in the cluster when
    it was first created. The version can be upgraded over time.
  returned: success
  type: str
currentMasterVersion:
  description:
  - The current software version of the master endpoint.
  returned: success
  type: str
currentNodeVersion:
  description:
  - The current version of the node software components. If they are currently at
    multiple versions because they're in the process of being upgraded, this reflects
    the minimum version of all nodes.
  returned: success
  type: str
createTime:
  description:
  - The time the cluster was created, in RFC3339 text format.
  returned: success
  type: str
status:
  description:
  - The current status of this cluster.
  returned: success
  type: str
statusMessage:
  description:
  - Additional information about the current status of this cluster, if available.
  returned: success
  type: str
nodeIpv4CidrSize:
  description:
  - The size of the address space on each node for hosting containers.
  - This is provisioned from within the container_ipv4_cidr range.
  returned: success
  type: int
servicesIpv4Cidr:
  description:
  - The IP address range of the Kubernetes services in this cluster, in CIDR notation
    (e.g. 1.2.3.4/29). Service addresses are typically put in the last /16 from the
    container CIDR.
  returned: success
  type: str
currentNodeCount:
  description:
  - The number of nodes currently in the cluster.
  returned: success
  type: int
expireTime:
  description:
  - The time the cluster will be automatically deleted in RFC3339 text format.
  returned: success
  type: str
enableTpu:
  description:
  - Enable the ability to use Cloud TPUs in this cluster.
  returned: success
  type: bool
tpuIpv4CidrBlock:
  description:
  - The IP address range of the Cloud TPUs in this cluster, in CIDR notation.
  returned: success
  type: str
conditions:
  description:
  - Which conditions caused the current cluster state.
  returned: success
  type: complex
  contains:
    code:
      description:
      - Machine-friendly representation of the condition.
      returned: success
      type: str
    message:
      description:
      - Human-friendly representation of the condition.
      returned: success
      type: str
location:
  description:
  - The location where the cluster is deployed.
  returned: success
  type: str
kubectlPath:
  description:
  - The path that the kubectl config file will be written to.
  - The file will not be created if this path is unset.
  - Any existing file at this path will be completely overwritten.
  - This requires the PyYaml library.
  returned: success
  type: str
kubectlContext:
  description:
  - The name of the context for the kubectl config file. Will default to the cluster
    name.
  returned: success
  type: str
'''

################################################################################
# Imports
################################################################################

from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, remove_nones_from_dict, replace_resource_dict
import json
import time

################################################################################
# Main
################################################################################


def main():
    """Main function"""

    module = GcpModule(
        argument_spec=dict(
            state=dict(default='present', choices=['present', 'absent'], type='str'),
            name=dict(type='str'),
            description=dict(type='str'),
            initial_node_count=dict(type='int'),
            node_config=dict(
                type='dict',
                options=dict(
                    machine_type=dict(type='str'),
                    disk_size_gb=dict(type='int'),
                    oauth_scopes=dict(type='list', elements='str'),
                    service_account=dict(type='str'),
                    metadata=dict(type='dict'),
                    image_type=dict(type='str'),
                    labels=dict(type='dict'),
                    local_ssd_count=dict(type='int'),
                    tags=dict(type='list', elements='str'),
                    preemptible=dict(type='bool'),
                    accelerators=dict(type='list', elements='dict', options=dict(accelerator_count=dict(type='str'), accelerator_type=dict(type='str'))),
                    disk_type=dict(type='str'),
                    min_cpu_platform=dict(type='str'),
                    taints=dict(type='list', elements='dict', options=dict(key=dict(type='str'), value=dict(type='str'), effect=dict(type='str'))),
                ),
            ),
            master_auth=dict(
                type='dict',
                options=dict(
                    username=dict(type='str'),
                    password=dict(type='str'),
                    client_certificate_config=dict(type='dict', options=dict(issue_client_certificate=dict(type='bool'))),
                ),
            ),
            logging_service=dict(type='str'),
            monitoring_service=dict(type='str'),
            network=dict(type='str'),
            private_cluster_config=dict(
                type='dict',
                options=dict(enable_private_nodes=dict(type='bool'), enable_private_endpoint=dict(type='bool'), master_ipv4_cidr_block=dict(type='str')),
            ),
            cluster_ipv4_cidr=dict(type='str'),
            addons_config=dict(
                type='dict',
                options=dict(
                    http_load_balancing=dict(type='dict', options=dict(disabled=dict(type='bool'))),
                    horizontal_pod_autoscaling=dict(type='dict', options=dict(disabled=dict(type='bool'))),
                    network_policy_config=dict(type='dict', options=dict(disabled=dict(type='bool'))),
                ),
            ),
            subnetwork=dict(type='str'),
            locations=dict(type='list', elements='str', aliases=['nodeLocations']),
            resource_labels=dict(type='dict'),
            legacy_abac=dict(type='dict', options=dict(enabled=dict(type='bool'))),
            network_policy=dict(type='dict', options=dict(provider=dict(type='str'), enabled=dict(type='bool'))),
            default_max_pods_constraint=dict(type='dict', options=dict(max_pods_per_node=dict(type='str'))),
            enable_tpu=dict(type='bool'),
            tpu_ipv4_cidr_block=dict(type='str'),
            location=dict(required=True, type='str', aliases=['zone']),
            kubectl_path=dict(type='str'),
            kubectl_context=dict(type='str'),
        )
    )

    if not module.params['scopes']:
        module.params['scopes'] = ['https://www.googleapis.com/auth/cloud-platform']

    state = module.params['state']

    fetch = fetch_resource(module, self_link(module))
    changed = False

    if fetch:
        if state == 'present':
            if is_different(module, fetch):
                update(module, self_link(module))
                fetch = fetch_resource(module, self_link(module))
                changed = True
        else:
            delete(module, self_link(module))
            fetch = {}
            changed = True
    else:
        if state == 'present':
            fetch = create(module, collection(module))
            delete_default_node_pool(module)
            changed = True
        else:
            fetch = {}

    if module.params.get('kubectl_path'):
        Kubectl(module).write_file()
    fetch.update({'changed': changed})

    module.exit_json(**fetch)


def create(module, link):
    auth = GcpSession(module, 'container')
    return wait_for_operation(module, auth.post(link, resource_to_request(module)))


def update(module, link):
    auth = GcpSession(module, 'container')
    return wait_for_operation(module, auth.put(link, resource_to_request(module)))


def delete(module, link):
    auth = GcpSession(module, 'container')
    return wait_for_operation(module, auth.delete(link))


def resource_to_request(module):
    request = {
        u'name': module.params.get('name'),
        u'description': module.params.get('description'),
        u'initialNodeCount': module.params.get('initial_node_count'),
        u'nodeConfig': ClusterNodeconfig(module.params.get('node_config', {}), module).to_request(),
        u'masterAuth': ClusterMasterauth(module.params.get('master_auth', {}), module).to_request(),
        u'loggingService': module.params.get('logging_service'),
        u'monitoringService': module.params.get('monitoring_service'),
        u'network': module.params.get('network'),
        u'privateClusterConfig': ClusterPrivateclusterconfig(module.params.get('private_cluster_config', {}), module).to_request(),
        u'clusterIpv4Cidr': module.params.get('cluster_ipv4_cidr'),
        u'addonsConfig': ClusterAddonsconfig(module.params.get('addons_config', {}), module).to_request(),
        u'subnetwork': module.params.get('subnetwork'),
        u'locations': module.params.get('locations'),
        u'resourceLabels': module.params.get('resource_labels'),
        u'legacyAbac': ClusterLegacyabac(module.params.get('legacy_abac', {}), module).to_request(),
        u'networkPolicy': ClusterNetworkpolicy(module.params.get('network_policy', {}), module).to_request(),
        u'defaultMaxPodsConstraint': ClusterDefaultmaxpodsconstraint(module.params.get('default_max_pods_constraint', {}), module).to_request(),
        u'enableTpu': module.params.get('enable_tpu'),
        u'tpuIpv4CidrBlock': module.params.get('tpu_ipv4_cidr_block'),
    }
    request = encode_request(request, module)
    return_vals = {}
    for k, v in request.items():
        if v or v is False:
            return_vals[k] = v

    return return_vals


def fetch_resource(module, link, allow_not_found=True):
    auth = GcpSession(module, 'container')
    return return_if_object(module, auth.get(link), allow_not_found)


def self_link(module):
    return "https://container.googleapis.com/v1/projects/{project}/locations/{location}/clusters/{name}".format(**module.params)


def collection(module):
    return "https://container.googleapis.com/v1/projects/{project}/locations/{location}/clusters".format(**module.params)


def return_if_object(module, response, allow_not_found=False):
    # If not found, return nothing.
    if allow_not_found and response.status_code == 404:
        return None

    # If no content, return nothing.
    if response.status_code == 204:
        return None

    try:
        module.raise_for_status(response)
        result = response.json()
    except getattr(json.decoder, 'JSONDecodeError', ValueError):
        module.fail_json(msg="Invalid JSON response with error: %s" % response.text)

    if navigate_hash(result, ['error', 'errors']):
        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))

    return result


def is_different(module, response):
    request = resource_to_request(module)
    response = response_to_hash(module, response)

    # Remove all output-only from response.
    response_vals = {}
    for k, v in response.items():
        if k in request:
            response_vals[k] = v

    request_vals = {}
    for k, v in request.items():
        if k in response:
            request_vals[k] = v

    return GcpRequest(request_vals) != GcpRequest(response_vals)


# Remove unnecessary properties from the response.
# This is for doing comparisons with Ansible's current parameters.
def response_to_hash(module, response):
    return {
        u'name': response.get(u'name'),
        u'description': response.get(u'description'),
        u'initialNodeCount': module.params.get('initial_node_count'),
        u'nodeConfig': ClusterNodeconfig(module.params.get('node_config', {}), module).to_request(),
        u'masterAuth': ClusterMasterauth(response.get(u'masterAuth', {}), module).from_response(),
        u'loggingService': response.get(u'loggingService'),
        u'monitoringService': response.get(u'monitoringService'),
        u'network': response.get(u'network'),
        u'privateClusterConfig': ClusterPrivateclusterconfig(response.get(u'privateClusterConfig', {}), module).from_response(),
        u'clusterIpv4Cidr': response.get(u'clusterIpv4Cidr'),
        u'addonsConfig': ClusterAddonsconfig(response.get(u'addonsConfig', {}), module).from_response(),
        u'subnetwork': response.get(u'subnetwork'),
        u'locations': response.get(u'locations'),
        u'resourceLabels': response.get(u'resourceLabels'),
        u'labelFingerprint': response.get(u'labelFingerprint'),
        u'legacyAbac': ClusterLegacyabac(response.get(u'legacyAbac', {}), module).from_response(),
        u'networkPolicy': ClusterNetworkpolicy(response.get(u'networkPolicy', {}), module).from_response(),
        u'defaultMaxPodsConstraint': ClusterDefaultmaxpodsconstraint(response.get(u'defaultMaxPodsConstraint', {}), module).from_response(),
        u'endpoint': response.get(u'endpoint'),
        u'initialClusterVersion': response.get(u'initialClusterVersion'),
        u'currentMasterVersion': response.get(u'currentMasterVersion'),
        u'currentNodeVersion': response.get(u'currentNodeVersion'),
        u'createTime': response.get(u'createTime'),
        u'status': response.get(u'status'),
        u'statusMessage': response.get(u'statusMessage'),
        u'nodeIpv4CidrSize': response.get(u'nodeIpv4CidrSize'),
        u'servicesIpv4Cidr': response.get(u'servicesIpv4Cidr'),
        u'currentNodeCount': response.get(u'currentNodeCount'),
        u'expireTime': response.get(u'expireTime'),
        u'enableTpu': response.get(u'enableTpu'),
        u'tpuIpv4CidrBlock': response.get(u'tpuIpv4CidrBlock'),
        u'conditions': ClusterConditionsArray(response.get(u'conditions', []), module).from_response(),
    }


def async_op_url(module, extra_data=None):
    if extra_data is None:
        extra_data = {}
    url = "https://container.googleapis.com/v1/projects/{project}/locations/{location}/operations/{op_id}"
    combined = extra_data.copy()
    combined.update(module.params)
    return url.format(**combined)


def wait_for_operation(module, response):
    op_result = return_if_object(module, response)
    if op_result is None:
        return {}
    status = navigate_hash(op_result, ['status'])
    wait_done = wait_for_completion(status, op_result, module)
    return fetch_resource(module, navigate_hash(wait_done, ['targetLink']))


def wait_for_completion(status, op_result, module):
    op_id = navigate_hash(op_result, ['name'])
    op_uri = async_op_url(module, {'op_id': op_id})
    while status != 'DONE':
        raise_if_errors(op_result, ['error', 'errors'], module)
        time.sleep(1.0)
        op_result = fetch_resource(module, op_uri, False)
        status = navigate_hash(op_result, ['status'])
    return op_result


def raise_if_errors(response, err_path, module):
    errors = navigate_hash(response, err_path)
    if errors is not None:
        module.fail_json(msg=errors)


# Google Container Engine API has its own layout for the create method,
# defined like this:
#
# {
#   'cluster': {
#     ... cluster data
#   }
# }
#
# Format the request to match the expected input by the API
def encode_request(resource_request, module):
    return {'cluster': resource_request}


# Deletes the default node pool on default creation.
def delete_default_node_pool(module):
    auth = GcpSession(module, 'container')
    link = "https://container.googleapis.com/v1/projects/%s/locations/%s/clusters/%s/nodePools/default-pool" % (
        module.params['project'],
        module.params['location'],
        module.params['name'],
    )
    return wait_for_operation(module, auth.delete(link))


class Kubectl(object):
    def __init__(self, module):
        self.module = module

    """
    Writes a kubectl config file
    kubectl_path must be set or this will fail.
    """

    def write_file(self):
        try:
            import yaml
        except ImportError:
            self.module.fail_json(msg="Please install the pyyaml module")

        with open(self.module.params['kubectl_path'], 'w') as f:
            f.write(yaml.dump(self._contents()))

    """
    Returns the contents of a kubectl file
    """

    def _contents(self):
        token = self._auth_token()
        endpoint = "https://%s" % self.fetch["endpoint"]
        context = self.module.params.get('kubectl_context')
        if not context:
            context = self.module.params['name']

        return {
            'apiVersion': 'v1',
            'clusters': [
                {'name': context, 'cluster': {'certificate-authority-data': str(self.fetch['masterAuth']['clusterCaCertificate']), 'server': endpoint}}
            ],
            'contexts': [{'name': context, 'context': {'cluster': context, 'user': context}}],
            'current-context': context,
            'kind': 'Config',
            'preferences': {},
            'users': [
                {
                    'name': context,
                    'user': {
                        'auth-provider': {
                            'config': {
                                'access-token': token,
                                'cmd-args': 'config config-helper --format=json',
                                'cmd-path': '/usr/lib64/google-cloud-sdk/bin/gcloud',
                                'expiry-key': '{.credential.token_expiry}',
                                'token-key': '{.credential.access_token}',
                            },
                            'name': 'gcp',
                        },
                        'username': str(self.fetch['masterAuth']['username']),
                        'password': str(self.fetch['masterAuth']['password']),
                    },
                }
            ],
        }

    """
    Returns the auth token used in kubectl
    This also sets the 'fetch' variable used in creating the kubectl
    """

    def _auth_token(self):
        auth = GcpSession(self.module, 'auth')
        response = auth.get(self_link(self.module))
        self.fetch = response.json()
        return response.request.headers['authorization'].split(' ')[1]


class ClusterNodeconfig(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {
                u'machineType': self.request.get('machine_type'),
                u'diskSizeGb': self.request.get('disk_size_gb'),
                u'oauthScopes': self.request.get('oauth_scopes'),
                u'serviceAccount': self.request.get('service_account'),
                u'metadata': self.request.get('metadata'),
                u'imageType': self.request.get('image_type'),
                u'labels': self.request.get('labels'),
                u'localSsdCount': self.request.get('local_ssd_count'),
                u'tags': self.request.get('tags'),
                u'preemptible': self.request.get('preemptible'),
                u'accelerators': ClusterAcceleratorsArray(self.request.get('accelerators', []), self.module).to_request(),
                u'diskType': self.request.get('disk_type'),
                u'minCpuPlatform': self.request.get('min_cpu_platform'),
                u'taints': ClusterTaintsArray(self.request.get('taints', []), self.module).to_request(),
            }
        )

    def from_response(self):
        return remove_nones_from_dict(
            {
                u'machineType': self.request.get(u'machineType'),
                u'diskSizeGb': self.request.get(u'diskSizeGb'),
                u'oauthScopes': self.request.get(u'oauthScopes'),
                u'serviceAccount': self.request.get(u'serviceAccount'),
                u'metadata': self.request.get(u'metadata'),
                u'imageType': self.request.get(u'imageType'),
                u'labels': self.request.get(u'labels'),
                u'localSsdCount': self.request.get(u'localSsdCount'),
                u'tags': self.request.get(u'tags'),
                u'preemptible': self.request.get(u'preemptible'),
                u'accelerators': ClusterAcceleratorsArray(self.request.get(u'accelerators', []), self.module).from_response(),
                u'diskType': self.request.get(u'diskType'),
                u'minCpuPlatform': self.request.get(u'minCpuPlatform'),
                u'taints': ClusterTaintsArray(self.request.get(u'taints', []), self.module).from_response(),
            }
        )


class ClusterAcceleratorsArray(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = []

    def to_request(self):
        items = []
        for item in self.request:
            items.append(self._request_for_item(item))
        return items

    def from_response(self):
        items = []
        for item in self.request:
            items.append(self._response_from_item(item))
        return items

    def _request_for_item(self, item):
        return remove_nones_from_dict({u'acceleratorCount': item.get('accelerator_count'), u'acceleratorType': item.get('accelerator_type')})

    def _response_from_item(self, item):
        return remove_nones_from_dict({u'acceleratorCount': item.get(u'acceleratorCount'), u'acceleratorType': item.get(u'acceleratorType')})


class ClusterTaintsArray(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = []

    def to_request(self):
        items = []
        for item in self.request:
            items.append(self._request_for_item(item))
        return items

    def from_response(self):
        items = []
        for item in self.request:
            items.append(self._response_from_item(item))
        return items

    def _request_for_item(self, item):
        return remove_nones_from_dict({u'key': item.get('key'), u'value': item.get('value'), u'effect': item.get('effect')})

    def _response_from_item(self, item):
        return remove_nones_from_dict({u'key': item.get(u'key'), u'value': item.get(u'value'), u'effect': item.get(u'effect')})


class ClusterMasterauth(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {
                u'username': self.request.get('username'),
                u'password': self.request.get('password'),
                u'clientCertificateConfig': ClusterClientcertificateconfig(self.request.get('client_certificate_config', {}), self.module).to_request(),
            }
        )

    def from_response(self):
        return remove_nones_from_dict(
            {
                u'username': self.request.get(u'username'),
                u'password': self.request.get(u'password'),
                u'clientCertificateConfig': ClusterClientcertificateconfig(self.request.get(u'clientCertificateConfig', {}), self.module).from_response(),
            }
        )


class ClusterClientcertificateconfig(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'issueClientCertificate': self.request.get('issue_client_certificate')})

    def from_response(self):
        return remove_nones_from_dict({u'issueClientCertificate': self.request.get(u'issueClientCertificate')})


class ClusterPrivateclusterconfig(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {
                u'enablePrivateNodes': self.request.get('enable_private_nodes'),
                u'enablePrivateEndpoint': self.request.get('enable_private_endpoint'),
                u'masterIpv4CidrBlock': self.request.get('master_ipv4_cidr_block'),
            }
        )

    def from_response(self):
        return remove_nones_from_dict(
            {
                u'enablePrivateNodes': self.request.get(u'enablePrivateNodes'),
                u'enablePrivateEndpoint': self.request.get(u'enablePrivateEndpoint'),
                u'masterIpv4CidrBlock': self.request.get(u'masterIpv4CidrBlock'),
            }
        )


class ClusterAddonsconfig(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {
                u'httpLoadBalancing': ClusterHttploadbalancing(self.request.get('http_load_balancing', {}), self.module).to_request(),
                u'horizontalPodAutoscaling': ClusterHorizontalpodautoscaling(self.request.get('horizontal_pod_autoscaling', {}), self.module).to_request(),
                u'networkPolicyConfig': ClusterNetworkpolicyconfig(self.request.get('network_policy_config', {}), self.module).to_request(),
            }
        )

    def from_response(self):
        return remove_nones_from_dict(
            {
                u'httpLoadBalancing': ClusterHttploadbalancing(self.request.get(u'httpLoadBalancing', {}), self.module).from_response(),
                u'horizontalPodAutoscaling': ClusterHorizontalpodautoscaling(self.request.get(u'horizontalPodAutoscaling', {}), self.module).from_response(),
                u'networkPolicyConfig': ClusterNetworkpolicyconfig(self.request.get(u'networkPolicyConfig', {}), self.module).from_response(),
            }
        )


class ClusterHttploadbalancing(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'disabled': self.request.get('disabled')})

    def from_response(self):
        return remove_nones_from_dict({u'disabled': self.request.get(u'disabled')})


class ClusterHorizontalpodautoscaling(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'disabled': self.request.get('disabled')})

    def from_response(self):
        return remove_nones_from_dict({u'disabled': self.request.get(u'disabled')})


class ClusterNetworkpolicyconfig(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'disabled': self.request.get('disabled')})

    def from_response(self):
        return remove_nones_from_dict({u'disabled': self.request.get(u'disabled')})


class ClusterLegacyabac(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'enabled': self.request.get('enabled')})

    def from_response(self):
        return remove_nones_from_dict({u'enabled': self.request.get(u'enabled')})


class ClusterNetworkpolicy(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'provider': self.request.get('provider'), u'enabled': self.request.get('enabled')})

    def from_response(self):
        return remove_nones_from_dict({u'provider': self.request.get(u'provider'), u'enabled': self.request.get(u'enabled')})


class ClusterDefaultmaxpodsconstraint(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'maxPodsPerNode': self.request.get('max_pods_per_node')})

    def from_response(self):
        return remove_nones_from_dict({u'maxPodsPerNode': self.request.get(u'maxPodsPerNode')})


class ClusterConditionsArray(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = []

    def to_request(self):
        items = []
        for item in self.request:
            items.append(self._request_for_item(item))
        return items

    def from_response(self):
        items = []
        for item in self.request:
            items.append(self._response_from_item(item))
        return items

    def _request_for_item(self, item):
        return remove_nones_from_dict({u'code': item.get('code'), u'message': item.get('message')})

    def _response_from_item(self, item):
        return remove_nones_from_dict({u'code': item.get(u'code'), u'message': item.get(u'message')})


if __name__ == '__main__':
    main()