-
Notifications
You must be signed in to change notification settings - Fork 55
/
resource_spotinst_ocean_aks_np.go
364 lines (285 loc) · 11.1 KB
/
resource_spotinst_ocean_aks_np.go
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
package spotinst
import (
"context"
"fmt"
"log"
"github.com/spotinst/spotinst-sdk-go/service/ocean/providers/azure"
"github.com/spotinst/terraform-provider-spotinst/spotinst/ocean_aks_np_scheduling"
"github.com/spotinst/terraform-provider-spotinst/spotinst/ocean_aks_np_vm_sizes"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/spotinst/spotinst-sdk-go/service/ocean/providers/azure_np"
"github.com/spotinst/terraform-provider-spotinst/spotinst/ocean_aks_np"
"github.com/spotinst/terraform-provider-spotinst/spotinst/ocean_aks_np_auto_scale"
"github.com/spotinst/terraform-provider-spotinst/spotinst/ocean_aks_np_auto_scaler"
"github.com/spotinst/terraform-provider-spotinst/spotinst/ocean_aks_np_health"
"github.com/spotinst/terraform-provider-spotinst/spotinst/ocean_aks_np_node_count_limits"
"github.com/spotinst/terraform-provider-spotinst/spotinst/ocean_aks_np_node_pool_properties"
"github.com/spotinst/terraform-provider-spotinst/spotinst/ocean_aks_np_strategy"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/spotinst/spotinst-sdk-go/spotinst"
"github.com/spotinst/spotinst-sdk-go/spotinst/client"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons"
)
func resourceSpotinstOceanAKSNP() *schema.Resource {
setupClusterAKSNPResource()
return &schema.Resource{
CreateContext: resourceSpotinstClusterAKSNPCreate,
ReadContext: resourceSpotinstClusterAKSNPRead,
UpdateContext: resourceSpotinstClusterAKSNPUpdate,
DeleteContext: resourceSpotinstClusterAKSNPDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: commons.OceanAKSNPResource.GetSchemaMap(),
}
}
func setupClusterAKSNPResource() {
fieldsMap := make(map[commons.FieldName]*commons.GenericField)
ocean_aks_np.Setup(fieldsMap)
ocean_aks_np_auto_scaler.Setup(fieldsMap)
ocean_aks_np_strategy.Setup(fieldsMap)
ocean_aks_np_health.Setup(fieldsMap)
ocean_aks_np_node_pool_properties.Setup(fieldsMap)
ocean_aks_np_node_count_limits.Setup(fieldsMap)
ocean_aks_np_auto_scale.Setup(fieldsMap)
ocean_aks_np_scheduling.Setup(fieldsMap)
ocean_aks_np_vm_sizes.Setup(fieldsMap)
commons.OceanAKSNPResource = commons.NewOceanAKSNPResource(fieldsMap)
}
// region Create
func resourceSpotinstClusterAKSNPCreate(ctx context.Context, resourceData *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf(string(commons.ResourceOnCreate), commons.OceanAKSNPResource.GetName())
cluster, err := commons.OceanAKSNPResource.OnCreate(resourceData, meta)
if err != nil {
return diag.FromErr(err)
}
clusterID, err := createAKSNPCluster(cluster, meta.(*Client))
if err != nil {
return diag.FromErr(err)
}
resourceData.SetId(spotinst.StringValue(clusterID))
log.Printf("ocean/aks: AKS cluster created successfully: %s", resourceData.Id())
return resourceSpotinstClusterAKSNPRead(ctx, resourceData, meta)
}
func createAKSNPCluster(cluster *azure_np.Cluster, spotinstClient *Client) (*string, error) {
if json, err := commons.ToJson(cluster); err != nil {
return nil, err
} else {
log.Printf("ocean/aks: cluster configuration: %s", json)
}
input := &azure_np.CreateClusterInput{
Cluster: cluster,
}
output, err := spotinstClient.ocean.CloudProviderAzureNP().CreateCluster(context.TODO(), input)
if err != nil {
return nil, fmt.Errorf("ocean/aks: failed to create cluster: %v", err)
}
return output.Cluster.ID, nil
}
// endregion
// region Read
func resourceSpotinstClusterAKSNPRead(ctx context.Context, resourceData *schema.ResourceData, meta interface{}) diag.Diagnostics {
clusterID := resourceData.Id()
log.Printf(string(commons.ResourceOnRead), commons.OceanAKSNPResource.GetName(), clusterID)
cluster, err := readAKSNPCluster(context.TODO(), clusterID, meta.(*Client))
if err != nil {
return diag.FromErr(err)
}
// If nothing was found, return no state.
if cluster == nil {
resourceData.SetId("")
return nil
}
// Expose the controller cluster identifier.
if cluster.ControllerClusterID != nil {
_ = resourceData.Set(string(ocean_aks_np.ControllerClusterID),
spotinst.StringValue(cluster.ControllerClusterID))
}
if err := commons.OceanAKSNPResource.OnRead(cluster, resourceData, meta); err != nil {
return diag.FromErr(err)
}
log.Printf("ocean/aks: cluster read successfully: %s", clusterID)
return nil
}
func readAKSNPCluster(ctx context.Context, clusterID string, spotinstClient *Client) (*azure_np.Cluster, error) {
input := &azure_np.ReadClusterInput{
ClusterID: spotinst.String(clusterID),
}
output, err := spotinstClient.ocean.CloudProviderAzureNP().ReadCluster(ctx, input)
if err != nil {
// If the cluster was not found, return nil so that we can show that it
// does not exist.
if errs, ok := err.(client.Errors); ok && len(errs) > 0 {
for _, err := range errs {
if err.Code == ErrCodeClusterNotFound {
return nil, nil
}
}
}
// Some other error, report it.
return nil, fmt.Errorf("ocean/aks: failed to read cluster: %v", err)
}
return output.Cluster, nil
}
// endregion
// region Update
func resourceSpotinstClusterAKSNPUpdate(ctx context.Context, resourceData *schema.ResourceData, meta interface{}) diag.Diagnostics {
clusterID := resourceData.Id()
log.Printf(string(commons.ResourceOnUpdate), commons.OceanAKSNPResource.GetName(), clusterID)
shouldUpdate, changesRequiredRoll, cluster, err := commons.OceanAKSNPResource.OnUpdate(resourceData, meta)
if err != nil {
return diag.FromErr(err)
}
if shouldUpdate {
cluster.SetId(spotinst.String(clusterID))
if err := updateAKSNPCluster(cluster, resourceData, meta.(*Client), changesRequiredRoll); err != nil {
return diag.FromErr(err)
}
}
log.Printf("ocean/aks: cluster updated successfully: %s", clusterID)
return resourceSpotinstClusterAKSNPRead(ctx, resourceData, meta)
}
func updateAKSNPCluster(cluster *azure_np.Cluster, resourceData *schema.ResourceData, spotinstClient *Client, changesRequiredRoll bool) error {
input := &azure_np.UpdateClusterInput{
Cluster: cluster,
}
var shouldRoll = false
var conditionedRoll = false
clusterID := resourceData.Id()
if updatePolicy, exists := resourceData.GetOkExists(string(ocean_aks_np.UpdatePolicy)); exists {
list := updatePolicy.([]interface{})
if len(list) > 0 && list[0] != nil {
m := list[0].(map[string]interface{})
if roll, ok := m[string(ocean_aks_np.ShouldRoll)].(bool); ok && roll {
shouldRoll = roll
}
if condRoll, ok := m[string(ocean_aks_np.ConditionedRoll)].(bool); ok && condRoll {
conditionedRoll = condRoll
}
}
}
if json, err := commons.ToJson(cluster); err != nil {
return err
} else {
log.Printf("ocean/aks: cluster update configuration: %s", json)
}
if _, err := spotinstClient.ocean.CloudProviderAzureNP().UpdateCluster(context.TODO(), input); err != nil {
return fmt.Errorf("ocean/aks: failed to update cluster: %v", err)
} else if shouldRoll {
if !conditionedRoll || changesRequiredRoll {
if err := rollOceanAKSCluster(resourceData, spotinstClient); err != nil {
log.Printf("[ERROR] Cluster [%v] roll failed, error: %v", clusterID, err)
return err
}
}
} else {
log.Printf("onRoll() -> Field [%v] is false, skipping cluster roll", string(ocean_aks_np.ShouldRoll))
}
return nil
}
func rollOceanAKSCluster(resourceData *schema.ResourceData, meta interface{}) error {
clusterID := resourceData.Id()
updatePolicy, exists := resourceData.GetOkExists(string(ocean_aks_np.UpdatePolicy))
if !exists {
return fmt.Errorf("ocean/aksnp: missing update policy for cluster %q", clusterID)
}
list := updatePolicy.([]interface{})
if len(list) > 0 && list[0] != nil {
updateClusterSchema := list[0].(map[string]interface{})
rollConfig, ok := updateClusterSchema[string(ocean_aks_np.RollConfig)]
if !ok || rollConfig == nil {
return fmt.Errorf("ocean/aksnp: missing roll configuration, "+
"skipping roll for cluster %q", clusterID)
}
rollSpec, err := expandOceanAKSClusterRollConfig(rollConfig, clusterID)
if err != nil {
return fmt.Errorf("ocean/aks: failed expanding roll "+
"configuration for cluster %q, error: %v", clusterID, err)
}
rollJSON, err := commons.ToJson(rollConfig)
if err != nil {
return fmt.Errorf("ocean/aks: failed marshaling roll "+
"configuration for cluster %q, error: %v", clusterID, err)
}
log.Printf("onRoll() -> Rolling cluster [%v] with configuration %s", clusterID, rollJSON)
rollInput := &azure.CreateRollInput{Roll: rollSpec}
if _, err = meta.(*Client).ocean.CloudProviderAzure().CreateRoll(context.TODO(), rollInput); err != nil {
return fmt.Errorf("onRoll() -> Roll failed for cluster [%v], error: %v", clusterID, err)
}
log.Printf("onRoll() -> Successfully rolled cluster [%v]", clusterID)
}
return nil
}
func expandOceanAKSClusterRollConfig(data interface{}, clusterID string) (*azure.RollSpec, error) {
list := data.([]interface{})
spec := &azure.RollSpec{
ClusterID: spotinst.String(clusterID),
}
if list != nil && list[0] != nil {
m := list[0].(map[string]interface{})
if v, ok := m[string(ocean_aks_np.BatchSizePercentage)].(int); ok && v >= 0 {
spec.BatchSizePercentage = spotinst.Int(v)
} else {
spec.BatchSizePercentage = nil
}
if v, ok := m[string(ocean_aks_np.VngIDs)]; ok {
spec.VngIds = expandList(v)
}
if v, ok := m[string(ocean_aks_np.BatchMinHealthyPercentage)].(int); ok && v > 0 {
spec.BatchMinHealthyPercentage = spotinst.Int(v)
}
if v, ok := m[string(ocean_aks_np.RespectPDB)].(bool); ok {
spec.RespectPDB = spotinst.Bool(v)
}
if v, ok := m[string(ocean_aks_np.Comment)].(string); ok {
spec.Comment = spotinst.String(v)
}
if v, ok := m[string(ocean_aks_np.NodePoolNames)]; ok {
spec.NodePoolNames = expandList(v)
}
if v, ok := m[string(ocean_aks_np.RespectRestrictScaleDown)].(bool); ok {
spec.RespectRestrictScaleDown = spotinst.Bool(v)
}
if v, ok := m[string(ocean_aks_np.NodeNames)]; ok {
spec.NodeNames = expandList(v)
}
}
return spec, nil
}
func expandList(data interface{}) []string {
list := data.([]interface{})
result := make([]string, 0, len(list))
for _, v := range list {
if ls, ok := v.(string); ok && ls != "" {
result = append(result, ls)
}
}
return result
}
// endregion
// region Delete
func resourceSpotinstClusterAKSNPDelete(ctx context.Context, resourceData *schema.ResourceData, meta interface{}) diag.Diagnostics {
clusterID := resourceData.Id()
log.Printf(string(commons.ResourceOnDelete), commons.OceanAKSNPResource.GetName(), clusterID)
if err := deleteAKSNPCluster(clusterID, meta.(*Client)); err != nil {
return diag.FromErr(err)
}
log.Printf("ocean/aks: cluster deleted successfully: %s", clusterID)
resourceData.SetId("")
return nil
}
func deleteAKSNPCluster(clusterID string, spotinstClient *Client) error {
input := &azure_np.DeleteClusterInput{
ClusterID: spotinst.String(clusterID),
}
if json, err := commons.ToJson(input); err != nil {
return err
} else {
log.Printf("ocean/aks: cluster delete configuration: %s", json)
}
if _, err := spotinstClient.ocean.CloudProviderAzureNP().DeleteCluster(context.TODO(), input); err != nil {
return fmt.Errorf("ocean/aks: failed to delete cluster: %v", err)
}
return nil
}
// endregion