-
Notifications
You must be signed in to change notification settings - Fork 56
/
resource_spotinst_managed_instance_aws.go
365 lines (303 loc) · 13 KB
/
resource_spotinst_managed_instance_aws.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
365
package spotinst
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/spotinst/spotinst-sdk-go/service/managedinstance/providers/aws"
"github.com/spotinst/spotinst-sdk-go/spotinst"
"github.com/spotinst/spotinst-sdk-go/spotinst/client"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instance_aws"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instance_aws_compute"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instance_aws_compute_instance_type"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instance_aws_compute_launchspecification"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instance_aws_integrations"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instance_healthcheck"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instance_persistence"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instance_scheduling"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instance_strategy"
"github.com/spotinst/terraform-provider-spotinst/spotinst/commons/managed_instances_aws_compute_launchspecification_networkinterfaces"
)
func resourceSpotinstMangedInstanceAWS() *schema.Resource {
setupMangedInstanceResource()
return &schema.Resource{
CreateContext: resourceSpotinstManagedInstanceAWSCreate,
ReadContext: resourceSpotinstManagedInstanceAWSRead,
UpdateContext: resourceSpotinstManagedInstanceAWSUpdate,
DeleteContext: resourceSpotinstManagedInstanceAWSDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: commons.ManagedInstanceResource.GetSchemaMap(),
}
}
func setupMangedInstanceResource() {
fieldsMap := make(map[commons.FieldName]*commons.GenericField)
managed_instance_aws.Setup(fieldsMap)
managed_instance_strategy.Setup(fieldsMap)
managed_instance_persistence.Setup(fieldsMap)
managed_instance_healthcheck.Setup(fieldsMap)
managed_instance_aws_compute.Setup(fieldsMap)
managed_instance_aws_integrations.Setup(fieldsMap)
managed_instance_scheduling.Setup(fieldsMap)
managed_instances_aws_compute_launchspecification_networkinterfaces.Setup(fieldsMap)
managed_instance_aws_compute_launchspecification.Setup(fieldsMap)
managed_instance_aws_compute_instance_type.Setup(fieldsMap)
commons.ManagedInstanceResource = commons.NewManagedInstanceResource(fieldsMap)
}
const ErrCodeManagedInstanceDoesntExist = "MANAGED_INSTANCE_DOESNT_EXIST"
func resourceSpotinstManagedInstanceAWSRead(ctx context.Context, resourceData *schema.ResourceData, meta interface{}) diag.Diagnostics {
id := resourceData.Id()
log.Printf(string(commons.ResourceOnRead),
commons.ManagedInstanceResource.GetName(), id)
input := &aws.ReadManagedInstanceInput{ManagedInstanceID: spotinst.String(id)}
resp, err := meta.(*Client).managedInstance.CloudProviderAWS().Read(context.Background(), input)
if err != nil {
// If the group was not found, return nil so that we can show
// that the group does not exist
if errs, ok := err.(client.Errors); ok && len(errs) > 0 {
for _, err := range errs {
if err.Code == ErrCodeManagedInstanceDoesntExist {
resourceData.SetId("")
return nil
}
}
}
// Some other error, report it.
return diag.Errorf("failed to read ManagedInstance: %s", err)
}
// If nothing was found, then return no state.
managedInstanceResponse := resp.ManagedInstance
if managedInstanceResponse == nil {
resourceData.SetId("")
return nil
}
if err := commons.ManagedInstanceResource.OnRead(managedInstanceResponse, resourceData, meta); err != nil {
return diag.FromErr(err)
}
log.Printf("===> ManagedInstance read successfully: %s <===", id)
return nil
}
func resourceSpotinstManagedInstanceAWSCreate(ctx context.Context, resourceData *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf(string(commons.ResourceOnCreate),
commons.ManagedInstanceResource.GetName())
mangedInstance, err := commons.ManagedInstanceResource.OnCreate(resourceData, meta)
if err != nil {
return diag.FromErr(err)
}
ManagedInstanceId, err := createManagedInstance(resourceData, mangedInstance, meta.(*Client))
if err != nil {
return diag.FromErr(err)
}
resourceData.SetId(spotinst.StringValue(ManagedInstanceId))
log.Printf("===> ManagedInstance created successfully: %s <===", resourceData.Id())
return resourceSpotinstManagedInstanceAWSRead(ctx, resourceData, meta)
}
func createManagedInstance(resourceData *schema.ResourceData, mangedInstance *aws.ManagedInstance, spotinstClient *Client) (*string, error) {
if json, err := commons.ToJson(mangedInstance); err != nil {
return nil, err
} else {
log.Printf("===> ManagedInstance create configuration: %s", json)
}
if v, ok := resourceData.Get(string(managed_instance_aws_compute_launchspecification.IAMInstanceProfile)).(string); ok && v != "" {
time.Sleep(5 * time.Second)
}
var resp *aws.CreateManagedInstanceOutput = nil
err := resource.RetryContext(context.Background(), time.Minute, func() *resource.RetryError {
input := &aws.CreateManagedInstanceInput{ManagedInstance: mangedInstance}
r, err := spotinstClient.managedInstance.CloudProviderAWS().Create(context.Background(), input)
if err != nil {
// Checks whether we should retry the group creation.
if errs, ok := err.(client.Errors); ok && len(errs) > 0 {
for _, err := range errs {
if err.Code == "InvalidParameterValue" &&
strings.Contains(err.Message, "Invalid IAM Instance Profile") {
return resource.RetryableError(err)
}
}
}
// Some other error, report it.
return resource.NonRetryableError(err)
}
resp = r
return nil
})
if err != nil {
return nil, fmt.Errorf("[ERROR] failed to create ManagedInstance: %s", err)
}
return resp.ManagedInstance.ID, nil
}
func resourceSpotinstManagedInstanceAWSUpdate(ctx context.Context, resourceData *schema.ResourceData, meta interface{}) diag.Diagnostics {
id := resourceData.Id()
log.Printf(string(commons.ResourceOnUpdate),
commons.ManagedInstanceResource.GetName(), id)
shouldUpdate, managedInstance, err := commons.ManagedInstanceResource.OnUpdate(resourceData, meta)
if err != nil {
return diag.FromErr(err)
}
if shouldUpdate {
managedInstance.SetId(spotinst.String(id))
if err := updateAWSManagedInstance(managedInstance, resourceData, meta); err != nil {
return diag.FromErr(err)
}
}
log.Printf("===> ManagedInstance updated successfully: %s <===", id)
return resourceSpotinstManagedInstanceAWSRead(ctx, resourceData, meta)
}
func updateAWSManagedInstance(managedInstance *aws.ManagedInstance, resourceData *schema.ResourceData, meta interface{}) error {
var input = &aws.UpdateManagedInstanceInput{
ManagedInstance: managedInstance,
}
if instanceActions, exists := resourceData.GetOk(string(managed_instance_aws.ManagedInstanceAction)); exists {
actionList := instanceActions.([]interface{})
ctx := context.TODO()
svc := meta.(*Client).managedInstance.CloudProviderAWS()
for _, action := range actionList {
var (
actionMap = action.(map[string]interface{})
actionType = actionMap[string(managed_instance_aws.ActionType)].(string)
err error
)
switch strings.ToLower(actionType) {
case "pause":
err = pauseManagedInstance(ctx, svc, resourceData.Id())
case "resume":
err = resumeManagedInstance(ctx, svc, resourceData.Id())
case "recycle":
err = recycleManagedInstance(ctx, svc, resourceData.Id())
default:
err = fmt.Errorf("unsupported action %q on managed instance %q", actionType, resourceData.Id())
}
if err != nil {
log.Printf("[ERROR] managed instance (%s) action failed with error: %v", resourceData.Id(), err)
return err
}
}
}
if json, err := commons.ToJson(managedInstance); err != nil {
return err
} else {
log.Printf("===> ManagedInstance update configuration: %s", json)
}
if _, err := meta.(*Client).managedInstance.CloudProviderAWS().Update(context.Background(), input); err != nil {
return fmt.Errorf("[ERROR] Failed to update managed instance [%v]: %v", resourceData.Id(), err)
}
return nil
}
func pauseManagedInstance(ctx context.Context, svc aws.Service, instanceID string) error {
log.Printf("Pausing managed instance (%s)", instanceID)
input := &aws.PauseManagedInstanceInput{
ManagedInstanceID: spotinst.String(instanceID),
}
_, err := svc.Pause(ctx, input)
if err != nil {
return fmt.Errorf("failed to pause managed instance (%s): %v", instanceID, err)
}
log.Printf("Successfully paused managed instance (%s)", instanceID)
return nil
}
func resumeManagedInstance(ctx context.Context, svc aws.Service, instanceID string) error {
log.Printf("Resuming managed instance (%s)", instanceID)
input := &aws.ResumeManagedInstanceInput{
ManagedInstanceID: spotinst.String(instanceID),
}
_, err := svc.Resume(ctx, input)
if err != nil {
return fmt.Errorf("failed to resume managed instance (%s): %v", instanceID, err)
}
log.Printf("Successfully resumed managed instance (%s)", instanceID)
return nil
}
func recycleManagedInstance(ctx context.Context, svc aws.Service, instanceID string) error {
log.Printf("Recycling managed instance (%s)", instanceID)
input := &aws.RecycleManagedInstanceInput{
ManagedInstanceID: spotinst.String(instanceID),
}
_, err := svc.Recycle(ctx, input)
if err != nil {
return fmt.Errorf("failed to recycle managed instance (%s): %v", instanceID, err)
}
log.Printf("Successfully recycled managed instance (%s)", instanceID)
return nil
}
func resourceSpotinstManagedInstanceAWSDelete(ctx context.Context, resourceData *schema.ResourceData, meta interface{}) diag.Diagnostics {
id := resourceData.Id()
log.Printf(string(commons.ResourceOnDelete),
commons.ManagedInstanceResource.GetName(), id)
if err := deleteManagedInstance(resourceData, meta); err != nil {
return diag.FromErr(err)
}
log.Printf("===> ManagedInstance deleted successfully: %s <===", resourceData.Id())
resourceData.SetId("")
return nil
}
func deleteManagedInstance(resourceData *schema.ResourceData, meta interface{}) error {
managedInstanceId := resourceData.Id()
var deleteManagedInstanceAWSInput *aws.DeleteManagedInstanceInput
if deleteConfig, ok := resourceData.GetOk(string(managed_instance_aws.Delete)); ok {
input, err := expandManagedInstanceAWSDeleteConfig(deleteConfig, managedInstanceId)
if err != nil {
return fmt.Errorf("stateful node/aws: failed expanding delete configuration: %v", err)
}
deleteManagedInstanceAWSInput = input
} else {
input := &aws.DeleteManagedInstanceInput{
ManagedInstanceID: spotinst.String(resourceData.Id()),
AMIBackup: &aws.AMIBackup{
ShouldDeleteImages: spotinst.Bool(true),
},
DeallocationConfig: &aws.DeallocationConfig{
ShouldDeleteImages: spotinst.Bool(true),
ShouldTerminateInstance: spotinst.Bool(true),
ShouldDeleteVolumes: spotinst.Bool(true),
ShouldDeleteNetworkInterfaces: spotinst.Bool(true),
ShouldDeleteSnapshots: spotinst.Bool(true),
},
}
deleteManagedInstanceAWSInput = input
}
if json, err := commons.ToJson(deleteManagedInstanceAWSInput); err != nil {
return err
} else {
log.Printf("===> ManagedInstance delete configuration: %s", json)
}
if _, err := meta.(*Client).managedInstance.CloudProviderAWS().Delete(context.Background(), deleteManagedInstanceAWSInput); err != nil {
return fmt.Errorf("[ERROR] onDelete() -> Failed to delete managed instance: %s", err)
}
return nil
}
func expandManagedInstanceAWSDeleteConfig(data interface{}, managedInstanceID string) (*aws.DeleteManagedInstanceInput, error) {
spec := &aws.DeleteManagedInstanceInput{
ManagedInstanceID: spotinst.String(managedInstanceID),
AMIBackup: &aws.AMIBackup{},
DeallocationConfig: &aws.DeallocationConfig{},
}
list := data.([]interface{})
if list != nil && list[0] != nil {
m := list[0].(map[string]interface{})
if v, ok := m[string(managed_instance_aws.AmiBackupShouldDeleteImages)].(bool); ok {
spec.AMIBackup.ShouldDeleteImages = spotinst.Bool(v)
}
if v, ok := m[string(managed_instance_aws.DeallocationConfigShouldDeleteImages)].(bool); ok {
spec.DeallocationConfig.ShouldDeleteImages = spotinst.Bool(v)
}
if v, ok := m[string(managed_instance_aws.ShouldDeleteNetworkInterfaces)].(bool); ok {
spec.DeallocationConfig.ShouldDeleteNetworkInterfaces = spotinst.Bool(v)
}
if v, ok := m[string(managed_instance_aws.ShouldDeleteSnapshots)].(bool); ok {
spec.DeallocationConfig.ShouldDeleteSnapshots = spotinst.Bool(v)
}
if v, ok := m[string(managed_instance_aws.ShouldDeleteVolumes)].(bool); ok {
spec.DeallocationConfig.ShouldDeleteVolumes = spotinst.Bool(v)
}
if v, ok := m[string(managed_instance_aws.ShouldTerminateInstance)].(bool); ok {
spec.DeallocationConfig.ShouldTerminateInstance = spotinst.Bool(v)
}
}
return spec, nil
}