forked from GoogleCloudPlatform/magic-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_container_node_pool.go.erb
1383 lines (1185 loc) · 45 KB
/
resource_container_node_pool.go.erb
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
<% autogen_exception -%>
package google
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
<% if version == "ga" -%>
"google.golang.org/api/container/v1"
<% else -%>
container "google.golang.org/api/container/v1beta1"
<% end -%>
)
var clusterIdRegex = regexp.MustCompile("projects/(?P<project>[^/]+)/locations/(?P<location>[^/]+)/clusters/(?P<name>[^/]+)")
func resourceContainerNodePool() *schema.Resource {
return &schema.Resource{
Create: resourceContainerNodePoolCreate,
Read: resourceContainerNodePoolRead,
Update: resourceContainerNodePoolUpdate,
Delete: resourceContainerNodePoolDelete,
Exists: resourceContainerNodePoolExists,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
SchemaVersion: 1,
MigrateState: resourceContainerNodePoolMigrateState,
Importer: &schema.ResourceImporter{
State: resourceContainerNodePoolStateImporter,
},
CustomizeDiff: customdiff.All(
resourceNodeConfigEmptyGuestAccelerator,
),
UseJSONNumber: true,
Schema: mergeSchemas(
schemaNodePool,
map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The ID of the project in which to create the node pool. If blank, the provider-configured project will be used.`,
},
"cluster": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The cluster to create the node pool for. Cluster must be present in location provided for zonal clusters.`,
},
"location": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The location (region or zone) of the cluster.`,
},
"operation": {
Type: schema.TypeString,
Computed: true,
},
}),
}
}
var schemaNodePool = map[string]*schema.Schema{
"autoscaling": &schema.Schema{
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `Configuration required by cluster autoscaler to adjust the size of the node pool to the current cluster usage.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"min_node_count": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(0),
Description: `Minimum number of nodes per zone in the node pool. Must be >=0 and <= max_node_count. Cannot be used with total limits.`,
},
"max_node_count": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(0),
Description: `Maximum number of nodes per zone in the node pool. Must be >= min_node_count. Cannot be used with total limits.`,
},
"total_min_node_count": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(0),
Description: `Minimum number of all nodes in the node pool. Must be >=0 and <= total_max_node_count. Cannot be used with per zone limits.`,
},
"total_max_node_count": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(0),
Description: `Maximum number of all nodes in the node pool. Must be >= total_min_node_count. Cannot be used with per zone limits.`,
},
"location_policy": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"BALANCED", "ANY"}, false),
Description: `Location policy specifies the algorithm used when scaling-up the node pool. "BALANCED" - Is a best effort policy that aims to balance the sizes of available zones. "ANY" - Instructs the cluster autoscaler to prioritize utilization of unused reservations, and reduces preemption risk for Spot VMs.`,
},
},
},
},
<% unless version == 'ga' -%>
"placement_policy": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: `Specifies the node placement policy`,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
Description: `Type defines the type of placement policy`,
},
},
},
},
<% end -%>
"max_pods_per_node": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The maximum number of pods per node in this node pool. Note that this does not work on node pools which are "route-based" - that is, node pools belonging to clusters that do not have IP Aliasing enabled.`,
},
"node_locations": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: `The list of zones in which the node pool's nodes should be located. Nodes must be in the region of their regional cluster or in the same region as their cluster's zone for zonal clusters. If unspecified, the cluster-level node_locations will be used.`,
},
"upgrade_settings": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Description: `Specify node upgrade settings to change how many nodes GKE attempts to upgrade at once. The number of nodes upgraded simultaneously is the sum of max_surge and max_unavailable. The maximum number of nodes upgraded simultaneously is limited to 20.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"max_surge": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntAtLeast(0),
Description: `The number of additional nodes that can be added to the node pool during an upgrade. Increasing max_surge raises the number of nodes that can be upgraded simultaneously. Can be set to 0 or greater.`,
},
"max_unavailable": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntAtLeast(0),
Description: `The number of nodes that can be simultaneously unavailable during an upgrade. Increasing max_unavailable raises the number of nodes that can be upgraded in parallel. Can be set to 0 or greater.`,
},
},
},
},
"initial_node_count": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The initial number of nodes for the pool. In regional or multi-zonal clusters, this is the number of nodes per zone. Changing this will force recreation of the resource.`,
},
"instance_group_urls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: `The resource URLs of the managed instance groups associated with this node pool.`,
},
"managed_instance_group_urls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: `List of instance group URLs which have been assigned to this node pool.`,
},
"management": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Description: `Node management configuration, wherein auto-repair and auto-upgrade is configured.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_repair": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: `Whether the nodes will be automatically repaired.`,
},
"auto_upgrade": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: `Whether the nodes will be automatically upgraded.`,
},
},
},
},
"name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The name of the node pool. If left blank, Terraform will auto-generate a unique name.`,
},
"name_prefix": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `Creates a unique name for the node pool beginning with the specified prefix. Conflicts with name.`,
},
"node_config": schemaNodeConfig(),
"node_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntAtLeast(0),
Description: `The number of nodes per instance group. This field can be used to update the number of nodes per instance group but should not be used alongside autoscaling.`,
},
"version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `The Kubernetes version for the nodes in this pool. Note that if this field and auto_upgrade are both specified, they will fight each other for what the node version should be, so setting both is highly discouraged. While a fuzzy version can be specified, it's recommended that you specify explicit versions as Terraform will see spurious diffs when fuzzy versions are used. See the google_container_engine_versions data source's version_prefix field to approximate fuzzy versions in a Terraform-compatible way.`,
},
<% unless version == 'ga' -%>
"network_config": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Description: `Networking configuration for this NodePool. If specified, it overrides the cluster-level defaults.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_pod_range": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Description: `Whether to create a new range for pod IPs in this node pool. Defaults are provided for pod_range and pod_ipv4_cidr_block if they are not specified.`,
},
"pod_range": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The ID of the secondary range for pod IPs. If create_pod_range is true, this ID is used for the new range. If create_pod_range is false, uses an existing secondary range with this ID.`,
},
"pod_ipv4_cidr_block": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validateIpCidrRange,
Description: `The IP address range for pod IPs in this node pool. Only applicable if create_pod_range is true. Set to blank to have a range chosen with the default size. Set to /netmask (e.g. /14) to have a range chosen with a specific netmask. Set to a CIDR notation (e.g. 10.96.0.0/14) to pick a specific range to use.`,
},
},
},
},
<% end -%>
}
type NodePoolInformation struct {
project string
location string
cluster string
}
func (nodePoolInformation *NodePoolInformation) fullyQualifiedName(nodeName string) string {
return fmt.Sprintf(
"projects/%s/locations/%s/clusters/%s/nodePools/%s",
nodePoolInformation.project,
nodePoolInformation.location,
nodePoolInformation.cluster,
nodeName,
)
}
func (nodePoolInformation *NodePoolInformation) parent() string {
return fmt.Sprintf(
"projects/%s/locations/%s/clusters/%s",
nodePoolInformation.project,
nodePoolInformation.location,
nodePoolInformation.cluster,
)
}
func (nodePoolInformation *NodePoolInformation) lockKey() string {
return containerClusterMutexKey(nodePoolInformation.project,
nodePoolInformation.location, nodePoolInformation.cluster)
}
func extractNodePoolInformation(d *schema.ResourceData, config *Config) (*NodePoolInformation, error) {
cluster := d.Get("cluster").(string)
if fieldValues := clusterIdRegex.FindStringSubmatch(cluster); fieldValues != nil {
log.Printf("[DEBUG] matching parent cluster %s to regex %s", cluster, clusterIdRegex.String())
return &NodePoolInformation{
project: fieldValues[1],
location: fieldValues[2],
cluster: fieldValues[3],
}, nil
}
log.Printf("[DEBUG] parent cluster %s does not match regex %s", cluster, clusterIdRegex.String())
project, err := getProject(d, config)
if err != nil {
return nil, err
}
location, err := getLocation(d, config)
if err != nil {
return nil, err
}
return &NodePoolInformation{
project: project,
location: location,
cluster: cluster,
}, nil
}
func resourceContainerNodePoolCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
nodePoolInfo, err := extractNodePoolInformation(d, config)
if err != nil {
return err
}
nodePool, err := expandNodePool(d, "")
if err != nil {
return err
}
mutexKV.Lock(nodePoolInfo.lockKey())
defer mutexKV.Unlock(nodePoolInfo.lockKey())
req := &container.CreateNodePoolRequest{
NodePool: nodePool,
}
timeout := d.Timeout(schema.TimeoutCreate)
startTime := time.Now()
// we attempt to prefetch the node pool to make sure it doesn't exist before creation
var id = fmt.Sprintf("projects/%s/locations/%s/clusters/%s/nodePools/%s", nodePoolInfo.project, nodePoolInfo.location, nodePoolInfo.cluster, nodePool.Name)
name := getNodePoolName(id)
clusterNodePoolsGetCall := config.NewContainerClient(userAgent).Projects.Locations.Clusters.NodePools.Get(nodePoolInfo.fullyQualifiedName(name))
if config.UserProjectOverride {
clusterNodePoolsGetCall.Header().Add("X-Goog-User-Project", nodePoolInfo.project)
}
_, err = clusterNodePoolsGetCall.Do()
if err != nil && isGoogleApiErrorWithCode(err, 404) {
// Set the ID before we attempt to create if the resource doesn't exist. That
// way, if we receive an error but the resource is created anyway, it will be
// refreshed on the next call to apply.
d.SetId(id)
} else if err == nil {
return fmt.Errorf("resource - %s - already exists", id)
}
var operation *container.Operation
err = resource.Retry(timeout, func() *resource.RetryError {
clusterNodePoolsCreateCall := config.NewContainerClient(userAgent).Projects.Locations.Clusters.NodePools.Create(nodePoolInfo.parent(), req)
if config.UserProjectOverride {
clusterNodePoolsCreateCall.Header().Add("X-Goog-User-Project", nodePoolInfo.project)
}
operation, err = clusterNodePoolsCreateCall.Do()
if err != nil {
if isFailedPreconditionError(err) {
// We get failed precondition errors if the cluster is updating
// while we try to add the node pool.
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("error creating NodePool: %s", err)
}
timeout -= time.Since(startTime)
waitErr := containerOperationWait(config,
operation, nodePoolInfo.project,
nodePoolInfo.location, "creating GKE NodePool", userAgent, timeout)
if waitErr != nil {
// Check if the create operation failed because Terraform was prematurely terminated. If it was we can persist the
// operation id to state so that a subsequent refresh of this resource will wait until the operation has terminated
// before attempting to Read the state of the cluster. This allows a graceful resumption of a Create that was killed
// by the upstream Terraform process exiting early such as a sigterm.
select {
case <-config.context.Done():
log.Printf("[DEBUG] Persisting %s so this operation can be resumed \n", operation.Name)
if err := d.Set("operation", operation.Name); err != nil {
return fmt.Errorf("Error setting operation: %s", err)
}
return nil
default:
// leaving default case to ensure this is non blocking
}
// Check if resource was created but apply timed out.
// Common cause for that is GCE_STOCKOUT which will wait for resources and return error after timeout,
// but in fact nodepool will be created so we have to capture that in state.
_, err = clusterNodePoolsGetCall.Do()
if err != nil {
d.SetId("")
return waitErr
}
}
log.Printf("[INFO] GKE NodePool %s has been created", nodePool.Name)
if err = resourceContainerNodePoolRead(d, meta); err != nil {
return err
}
//Check cluster is in running state
_, err = containerClusterAwaitRestingState(config, nodePoolInfo.project, nodePoolInfo.location, nodePoolInfo.cluster, userAgent, d.Timeout(schema.TimeoutCreate))
if err != nil {
return err
}
state, err := containerNodePoolAwaitRestingState(config, d.Id(), nodePoolInfo.project, userAgent, d.Timeout(schema.TimeoutCreate))
if err != nil {
return err
}
if containerNodePoolRestingStates[state] == ErrorState {
return fmt.Errorf("NodePool %s was created in the error state %q", nodePool.Name, state)
}
return nil
}
func resourceContainerNodePoolRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
nodePoolInfo, err := extractNodePoolInformation(d, config)
if err != nil {
return err
}
operation := d.Get("operation").(string)
if operation != "" {
log.Printf("[DEBUG] in progress operation detected at %v, attempting to resume", operation)
op := &container.Operation{
Name: operation,
}
if err := d.Set("operation", ""); err != nil {
return fmt.Errorf("Error setting operation: %s", err)
}
waitErr := containerOperationWait(config, op, nodePoolInfo.project, nodePoolInfo.location, "resuming GKE node pool", userAgent, d.Timeout(schema.TimeoutRead))
if waitErr != nil {
return waitErr
}
}
name := getNodePoolName(d.Id())
clusterNodePoolsGetCall := config.NewContainerClient(userAgent).Projects.Locations.Clusters.NodePools.Get(nodePoolInfo.fullyQualifiedName(name))
if config.UserProjectOverride {
clusterNodePoolsGetCall.Header().Add("X-Goog-User-Project", nodePoolInfo.project)
}
nodePool, err := clusterNodePoolsGetCall.Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("NodePool %q from cluster %q", name, nodePoolInfo.cluster))
}
npMap, err := flattenNodePool(d, config, nodePool, "")
if err != nil {
return err
}
for k, v := range npMap {
if err := d.Set(k, v); err != nil {
return fmt.Errorf("Error setting %s: %s", k, err)
}
}
if err := d.Set("location", nodePoolInfo.location); err != nil {
return fmt.Errorf("Error setting location: %s", err)
}
if err := d.Set("project", nodePoolInfo.project); err != nil {
return fmt.Errorf("Error setting project: %s", err)
}
return nil
}
func resourceContainerNodePoolUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
nodePoolInfo, err := extractNodePoolInformation(d, config)
if err != nil {
return err
}
name := getNodePoolName(d.Id())
//Check cluster is in running state
_, err = containerClusterAwaitRestingState(config, nodePoolInfo.project, nodePoolInfo.location, nodePoolInfo.cluster, userAgent, d.Timeout(schema.TimeoutCreate))
if err != nil {
return err
}
_, err = containerNodePoolAwaitRestingState(config, nodePoolInfo.fullyQualifiedName(name), nodePoolInfo.project, userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
d.Partial(true)
if err := nodePoolUpdate(d, meta, nodePoolInfo, "", d.Timeout(schema.TimeoutUpdate)); err != nil {
return err
}
d.Partial(false)
//Check cluster is in running state
_, err = containerClusterAwaitRestingState(config, nodePoolInfo.project, nodePoolInfo.location, nodePoolInfo.cluster, userAgent, d.Timeout(schema.TimeoutCreate))
if err != nil {
return err
}
_, err = containerNodePoolAwaitRestingState(config, nodePoolInfo.fullyQualifiedName(name), nodePoolInfo.project, userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
return resourceContainerNodePoolRead(d, meta)
}
func resourceContainerNodePoolDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
nodePoolInfo, err := extractNodePoolInformation(d, config)
if err != nil {
return err
}
name := getNodePoolName(d.Id())
//Check cluster is in running state
_, err = containerClusterAwaitRestingState(config, nodePoolInfo.project, nodePoolInfo.location, nodePoolInfo.cluster, userAgent, d.Timeout(schema.TimeoutCreate))
if err != nil {
if isGoogleApiErrorWithCode(err, 404) {
log.Printf("[INFO] GKE cluster %s doesn't exist, skipping node pool %s deletion", nodePoolInfo.cluster, d.Id())
return nil
}
return err
}
_, err = containerNodePoolAwaitRestingState(config, nodePoolInfo.fullyQualifiedName(name), nodePoolInfo.project, userAgent, d.Timeout(schema.TimeoutDelete))
if err != nil {
// If the node pool doesn't get created and then we try to delete it, we get an error,
// but I don't think we need an error during delete if it doesn't exist
if isGoogleApiErrorWithCode(err, 404) {
log.Printf("node pool %q not found, doesn't need to be cleaned up", name)
return nil
} else {
return err
}
}
mutexKV.Lock(nodePoolInfo.lockKey())
defer mutexKV.Unlock(nodePoolInfo.lockKey())
timeout := d.Timeout(schema.TimeoutDelete)
startTime := time.Now()
var operation *container.Operation
err = resource.Retry(timeout, func() *resource.RetryError {
clusterNodePoolsDeleteCall := config.NewContainerClient(userAgent).Projects.Locations.Clusters.NodePools.Delete(nodePoolInfo.fullyQualifiedName(name))
if config.UserProjectOverride {
clusterNodePoolsDeleteCall.Header().Add("X-Goog-User-Project", nodePoolInfo.project)
}
operation, err = clusterNodePoolsDeleteCall.Do()
if err != nil {
if isFailedPreconditionError(err) {
// We get failed precondition errors if the cluster is updating
// while we try to delete the node pool.
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("Error deleting NodePool: %s", err)
}
timeout -= time.Since(startTime)
// Wait until it's deleted
waitErr := containerOperationWait(config, operation, nodePoolInfo.project, nodePoolInfo.location, "deleting GKE NodePool", userAgent, timeout)
if waitErr != nil {
return waitErr
}
log.Printf("[INFO] GKE NodePool %s has been deleted", d.Id())
d.SetId("")
return nil
}
func resourceContainerNodePoolExists(d *schema.ResourceData, meta interface{}) (bool, error) {
config := meta.(*Config)
nodePoolInfo, err := extractNodePoolInformation(d, config)
if err != nil {
return false, err
}
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return false, err
}
name := getNodePoolName(d.Id())
clusterNodePoolsGetCall := config.NewContainerClient(userAgent).Projects.Locations.Clusters.NodePools.Get(nodePoolInfo.fullyQualifiedName(name))
if config.UserProjectOverride {
clusterNodePoolsGetCall.Header().Add("X-Goog-User-Project", nodePoolInfo.project)
}
_, err = clusterNodePoolsGetCall.Do()
if err != nil {
if err = handleNotFoundError(err, d, fmt.Sprintf("Container NodePool %s", name)); err == nil {
return false, nil
}
// There was some other error in reading the resource
return true, err
}
return true, nil
}
func resourceContainerNodePoolStateImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return nil, err
}
if err := parseImportId([]string{"projects/(?P<project>[^/]+)/locations/(?P<location>[^/]+)/clusters/(?P<cluster>[^/]+)/nodePools/(?P<name>[^/]+)", "(?P<project>[^/]+)/(?P<location>[^/]+)/(?P<cluster>[^/]+)/(?P<name>[^/]+)", "(?P<location>[^/]+)/(?P<cluster>[^/]+)/(?P<name>[^/]+)"}, d, config); err != nil {
return nil, err
}
id, err := replaceVars(d, config, "projects/{{project}}/locations/{{location}}/clusters/{{cluster}}/nodePools/{{name}}")
if err != nil {
return nil, err
}
d.SetId(id)
project, err := getProject(d, config)
if err != nil {
return nil, err
}
nodePoolInfo, err := extractNodePoolInformation(d, config)
if err != nil {
return nil, err
}
//Check cluster is in running state
_, err = containerClusterAwaitRestingState(config, nodePoolInfo.project, nodePoolInfo.location, nodePoolInfo.cluster, userAgent, d.Timeout(schema.TimeoutCreate))
if err != nil {
return nil, err
}
if _, err := containerNodePoolAwaitRestingState(config, d.Id(), project, userAgent, d.Timeout(schema.TimeoutCreate)); err != nil {
return nil, err
}
return []*schema.ResourceData{d}, nil
}
func expandNodePool(d *schema.ResourceData, prefix string) (*container.NodePool, error) {
var name string
if v, ok := d.GetOk(prefix + "name"); ok {
if _, ok := d.GetOk(prefix + "name_prefix"); ok {
return nil, fmt.Errorf("Cannot specify both name and name_prefix for a node_pool")
}
name = v.(string)
} else if v, ok := d.GetOk(prefix + "name_prefix"); ok {
name = resource.PrefixedUniqueId(v.(string))
} else {
name = resource.UniqueId()
}
nodeCount := 0
if initialNodeCount, ok := d.GetOk(prefix + "initial_node_count"); ok {
nodeCount = initialNodeCount.(int)
}
if nc, ok := d.GetOk(prefix + "node_count"); ok {
if nodeCount != 0 {
return nil, fmt.Errorf("Cannot set both initial_node_count and node_count on node pool %s", name)
}
nodeCount = nc.(int)
}
var locations []string
if v, ok := d.GetOk("node_locations"); ok && v.(*schema.Set).Len() > 0 {
locations = convertStringSet(v.(*schema.Set))
}
np := &container.NodePool{
Name: name,
InitialNodeCount: int64(nodeCount),
Config: expandNodeConfig(d.Get(prefix + "node_config")),
Locations: locations,
Version: d.Get(prefix + "version").(string),
<% unless version == 'ga' -%>
NetworkConfig: expandNodeNetworkConfig(d.Get(prefix + "network_config")),
<% end -%>
}
if v, ok := d.GetOk(prefix + "autoscaling"); ok {
autoscaling := v.([]interface{})[0].(map[string]interface{})
np.Autoscaling = &container.NodePoolAutoscaling{
Enabled: true,
MinNodeCount: int64(autoscaling["min_node_count"].(int)),
MaxNodeCount: int64(autoscaling["max_node_count"].(int)),
TotalMinNodeCount: int64(autoscaling["total_min_node_count"].(int)),
TotalMaxNodeCount: int64(autoscaling["total_max_node_count"].(int)),
LocationPolicy: autoscaling["location_policy"].(string),
ForceSendFields: []string{"MinNodeCount", "MaxNodeCount", "TotalMinNodeCount", "TotalMaxNodeCount"},
}
}
<% unless version == 'ga' -%>
if v, ok := d.GetOk(prefix + "placement_policy"); ok {
placement_policy := v.([]interface{})[0].(map[string]interface{})
np.PlacementPolicy = &container.PlacementPolicy{
Type: placement_policy["type"].(string),
}
}
<% end -%>
if v, ok := d.GetOk(prefix + "max_pods_per_node"); ok {
np.MaxPodsConstraint = &container.MaxPodsConstraint{
MaxPodsPerNode: int64(v.(int)),
}
}
if v, ok := d.GetOk(prefix + "management"); ok {
managementConfig := v.([]interface{})[0].(map[string]interface{})
np.Management = &container.NodeManagement{}
if v, ok := managementConfig["auto_repair"]; ok {
np.Management.AutoRepair = v.(bool)
}
if v, ok := managementConfig["auto_upgrade"]; ok {
np.Management.AutoUpgrade = v.(bool)
}
}
if v, ok := d.GetOk(prefix + "upgrade_settings"); ok {
upgradeSettingsConfig := v.([]interface{})[0].(map[string]interface{})
np.UpgradeSettings = &container.UpgradeSettings{}
if v, ok := upgradeSettingsConfig["max_surge"]; ok {
np.UpgradeSettings.MaxSurge = int64(v.(int))
}
if v, ok := upgradeSettingsConfig["max_unavailable"]; ok {
np.UpgradeSettings.MaxUnavailable = int64(v.(int))
}
}
return np, nil
}
func flattenNodePool(d *schema.ResourceData, config *Config, np *container.NodePool, prefix string) (map[string]interface{}, error) {
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return nil, err
}
// Node pools don't expose the current node count in their API, so read the
// instance groups instead. They should all have the same size, but in case a resize
// failed or something else strange happened, we'll just use the average size.
size := 0
igmUrls := []string{}
managedIgmUrls := []string{}
for _, url := range np.InstanceGroupUrls {
// retrieve instance group manager (InstanceGroupUrls are actually URLs for InstanceGroupManagers)
matches := instanceGroupManagerURL.FindStringSubmatch(url)
if len(matches) < 4 {
return nil, fmt.Errorf("Error reading instance group manage URL '%q'", url)
}
igm, err := config.NewComputeClient(userAgent).InstanceGroupManagers.Get(matches[1], matches[2], matches[3]).Do()
if isGoogleApiErrorWithCode(err, 404) {
// The IGM URL in is stale; don't include it
continue
}
if err != nil {
return nil, fmt.Errorf("Error reading instance group manager returned as an instance group URL: %q", err)
}
size += int(igm.TargetSize)
igmUrls = append(igmUrls, url)
managedIgmUrls = append(managedIgmUrls, igm.InstanceGroup)
}
nodeCount := 0
if len(igmUrls) > 0 {
nodeCount = size / len(igmUrls)
}
nodePool := map[string]interface{}{
"name": np.Name,
"name_prefix": d.Get(prefix + "name_prefix"),
"initial_node_count": np.InitialNodeCount,
"node_locations": schema.NewSet(schema.HashString, convertStringArrToInterface(np.Locations)),
"node_count": nodeCount,
"node_config": flattenNodeConfig(np.Config),
"instance_group_urls": igmUrls,
"managed_instance_group_urls": managedIgmUrls,
"version": np.Version,
<% unless version == 'ga' -%>
"network_config": flattenNodeNetworkConfig(np.NetworkConfig, d, prefix),
<% end -%>
}
if np.Autoscaling != nil {
if np.Autoscaling.Enabled {
nodePool["autoscaling"] = []map[string]interface{}{
{
"min_node_count": np.Autoscaling.MinNodeCount,
"max_node_count": np.Autoscaling.MaxNodeCount,
"total_min_node_count": np.Autoscaling.TotalMinNodeCount,
"total_max_node_count": np.Autoscaling.TotalMaxNodeCount,
"location_policy": np.Autoscaling.LocationPolicy,
},
}
} else {
nodePool["autoscaling"] = []map[string]interface{}{}
}
}
<% unless version == 'ga' -%>
if np.PlacementPolicy != nil {
nodePool["placement_policy"] = []map[string]interface{}{
{
"type": np.PlacementPolicy.Type,
},
}
}
<% end -%>
if np.MaxPodsConstraint != nil {
nodePool["max_pods_per_node"] = np.MaxPodsConstraint.MaxPodsPerNode
}
nodePool["management"] = []map[string]interface{}{
{
"auto_repair": np.Management.AutoRepair,
"auto_upgrade": np.Management.AutoUpgrade,
},
}
if np.UpgradeSettings != nil {
nodePool["upgrade_settings"] = []map[string]interface{}{
{
"max_surge": np.UpgradeSettings.MaxSurge,
"max_unavailable": np.UpgradeSettings.MaxUnavailable,
},
}
} else {
delete(nodePool, "upgrade_settings")
}
return nodePool, nil
}
<% unless version == 'ga' -%>
func flattenNodeNetworkConfig(c *container.NodeNetworkConfig, d *schema.ResourceData, prefix string) []map[string]interface{} {
result := []map[string]interface{}{}
if c != nil {
result = append(result, map[string]interface{}{
"create_pod_range": d.Get(prefix + "network_config.0.create_pod_range"), // API doesn't return this value so we set the old one. Field is ForceNew + Required
"pod_ipv4_cidr_block": c.PodIpv4CidrBlock,
"pod_range": c.PodRange,
})
}
return result
}
func expandNodeNetworkConfig(v interface{}) *container.NodeNetworkConfig {
networkNodeConfigs := v.([]interface{})
nnc := &container.NodeNetworkConfig{}
if len(networkNodeConfigs) == 0 {
return nnc
}
networkNodeConfig := networkNodeConfigs[0].(map[string]interface{})
if v, ok := networkNodeConfig["create_pod_range"]; ok {
nnc.CreatePodRange = v.(bool)
}
if v, ok := networkNodeConfig["pod_range"]; ok {
nnc.PodRange = v.(string)
}
if v, ok := networkNodeConfig["pod_ipv4_cidr_block"]; ok {
nnc.PodIpv4CidrBlock = v.(string)
}
return nnc
}
<% end -%>
func nodePoolUpdate(d *schema.ResourceData, meta interface{}, nodePoolInfo *NodePoolInformation, prefix string, timeout time.Duration) error {
config := meta.(*Config)
name := d.Get(prefix + "name").(string)
lockKey := nodePoolInfo.lockKey()
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
if d.HasChange(prefix + "autoscaling") {
update := &container.ClusterUpdate{
DesiredNodePoolId: name,
}
if v, ok := d.GetOk(prefix + "autoscaling"); ok {
autoscaling := v.([]interface{})[0].(map[string]interface{})
update.DesiredNodePoolAutoscaling = &container.NodePoolAutoscaling{
Enabled: true,
MinNodeCount: int64(autoscaling["min_node_count"].(int)),
MaxNodeCount: int64(autoscaling["max_node_count"].(int)),
TotalMinNodeCount: int64(autoscaling["total_min_node_count"].(int)),