-
Notifications
You must be signed in to change notification settings - Fork 21
/
resource_target_group.go
559 lines (461 loc) · 18.3 KB
/
resource_target_group.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
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
package ionoscloud
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
ionoscloud "github.com/ionos-cloud/sdk-go/v6"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/services"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/services/cloudapi"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/utils/constant"
)
func resourceTargetGroup() *schema.Resource {
return &schema.Resource{
CreateContext: resourceTargetGroupCreate,
ReadContext: resourceTargetGroupRead,
UpdateContext: resourceTargetGroupUpdate,
DeleteContext: resourceTargetGroupDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceTargetGroupImport,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the target group.",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace),
},
"algorithm": {
Type: schema.TypeString,
Required: true,
Description: "Balancing algorithm.",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice(constant.ForwardingRuleAlgorithms, true)),
},
"protocol": {
Type: schema.TypeString,
Required: true,
Description: "Balancing protocol.",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"HTTP"}, true)),
},
"targets": {
Type: schema.TypeList,
Description: "Array of items in the collection.",
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeString,
Description: "The IP of the balanced target VM.",
Required: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace),
},
"port": {
Type: schema.TypeInt,
Description: "The port of the balanced target service; valid range is 1 to 65535.",
Required: true,
},
"weight": {
Type: schema.TypeInt,
Description: "Traffic is distributed in proportion to target weight, relative to the combined weight of all targets. A target with higher weight receives a greater share of traffic. Valid range is 0 to 256 and default is 1; targets with weight of 0 do not participate in load balancing but still accept persistent connections. It is best use values in the middle of the range to leave room for later adjustments.",
Required: true,
},
"proxy_protocol": {
Type: schema.TypeString,
Description: "Proxy protocol version",
Optional: true,
Default: "none",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice(constant.LBTargetProxyProtocolVersions, true)),
},
"health_check_enabled": {
Type: schema.TypeBool,
Description: "Makes the target available only if it accepts periodic health check TCP connection attempts; when turned off, the target is considered always available. The health check only consists of a connection attempt to the address and port of the target. Default is True.",
Optional: true,
Computed: true,
},
"maintenance_enabled": {
Type: schema.TypeBool,
Description: "Maintenance mode prevents the target from receiving balanced traffic.",
Optional: true,
},
},
},
},
"health_check": {
Type: schema.TypeList,
MaxItems: 1,
Description: "Health check attributes for Application Load Balancer forwarding rule",
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"check_timeout": {
Type: schema.TypeInt,
Description: "The maximum time in milliseconds to wait for a target to respond to a check. For target VMs with 'Check Interval' set, the lesser of the two values is used once the TCP connection is established.",
Optional: true,
Computed: true,
},
"check_interval": {
Type: schema.TypeInt,
Description: "The interval in milliseconds between consecutive health checks; default is 2000.",
Optional: true,
Computed: true,
},
"retries": {
Type: schema.TypeInt,
Description: "The maximum number of attempts to reconnect to a target after a connection failure. Valid range is 0 to 65535, and default is three reconnection.",
Optional: true,
Computed: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.IntBetween(1, 65535)),
},
},
},
},
"http_health_check": {
Type: schema.TypeList,
MaxItems: 1,
Description: "Http health check attributes for Target Group",
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"path": {
Type: schema.TypeString,
Description: "The path (destination URL) for the HTTP health check request; the default is /.",
Optional: true,
Computed: true,
},
"method": {
Type: schema.TypeString,
Description: "The method for the HTTP health check.",
Optional: true,
Computed: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"HEAD", "PUT", "POST", "GET", "TRACE", "PATCH", "OPTIONS"}, true)),
},
"match_type": {
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"STATUS_CODE", "RESPONSE_BODY"}, true)),
},
"response": {
Type: schema.TypeString,
Description: "The response returned by the request, depending on the match type.",
Required: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace),
},
"regex": {
Type: schema.TypeBool,
Optional: true,
},
"negate": {
Type: schema.TypeBool,
Optional: true,
},
},
},
},
},
Timeouts: &resourceDefaultTimeouts,
}
}
func resourceTargetGroupCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
targetGroup := ionoscloud.TargetGroup{
Properties: &ionoscloud.TargetGroupProperties{},
}
if name, nameOk := d.GetOk("name"); nameOk {
name := name.(string)
targetGroup.Properties.Name = &name
}
if algorithm, algorithmOk := d.GetOk("algorithm"); algorithmOk {
algorithm := algorithm.(string)
targetGroup.Properties.Algorithm = &algorithm
}
if protocol, protocolOk := d.GetOk("protocol"); protocolOk {
protocol := protocol.(string)
targetGroup.Properties.Protocol = &protocol
}
targetGroup.Properties.Targets = getTargetGroupTargetData(d)
if _, healthCheckOk := d.GetOk("health_check.0"); healthCheckOk {
targetGroup.Properties.HealthCheck = getTargetGroupHealthCheckData(d)
}
if _, httpHealthCheckOk := d.GetOk("http_health_check.0"); httpHealthCheckOk {
targetGroup.Properties.HttpHealthCheck = getTargetGroupHttpHealthCheckData(d)
}
rsp, apiResponse, err := client.TargetGroupsApi.TargetgroupsPost(ctx).TargetGroup(targetGroup).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("an error occured while creating a target group: %w ", err))
return diags
}
d.SetId(*rsp.Id)
if errState := cloudapi.WaitForStateChange(ctx, meta, d, apiResponse, schema.TimeoutCreate); errState != nil {
if cloudapi.IsRequestFailed(errState) {
d.SetId("")
}
return diag.FromErr(errState)
}
return resourceTargetGroupRead(ctx, d, meta)
}
func resourceTargetGroupRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
rsp, apiResponse, err := client.TargetGroupsApi.TargetgroupsFindByTargetGroupId(ctx, d.Id()).Execute()
logApiRequestTime(apiResponse)
if err != nil {
if httpNotFound(apiResponse) {
d.SetId("")
return nil
}
diags := diag.FromErr(fmt.Errorf("error occured while fetching a target group %s %w", d.Id(), err))
return diags
}
if err := setTargetGroupData(d, &rsp); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceTargetGroupUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
targetGroup := ionoscloud.TargetGroupPut{
Properties: &ionoscloud.TargetGroupProperties{},
}
if name, nameOk := d.GetOk("name"); nameOk {
name := name.(string)
targetGroup.Properties.Name = &name
}
if algorithm, algorithmOk := d.GetOk("algorithm"); algorithmOk {
algorithm := algorithm.(string)
targetGroup.Properties.Algorithm = &algorithm
}
if protocol, protocolOk := d.GetOk("protocol"); protocolOk {
protocol := protocol.(string)
targetGroup.Properties.Protocol = &protocol
}
targetGroup.Properties.Targets = getTargetGroupTargetData(d)
if _, healthCheckOk := d.GetOk("health_check.0"); healthCheckOk {
targetGroup.Properties.HealthCheck = getTargetGroupHealthCheckData(d)
}
if _, httpHealthCheckOk := d.GetOk("http_health_check.0"); httpHealthCheckOk {
targetGroup.Properties.HttpHealthCheck = getTargetGroupHttpHealthCheckData(d)
}
response, apiResponse, err := client.TargetGroupsApi.TargetgroupsPut(ctx, d.Id()).TargetGroup(targetGroup).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("an error occured while restoring a targetGroup ID %s %w", d.Id(), err))
return diags
}
d.SetId(*response.Id)
if errState := cloudapi.WaitForStateChange(ctx, meta, d, apiResponse, schema.TimeoutUpdate); errState != nil {
return diag.FromErr(errState)
}
return resourceTargetGroupRead(ctx, d, meta)
}
func resourceTargetGroupDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
apiResponse, err := client.TargetGroupsApi.TargetGroupsDelete(ctx, d.Id()).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("an error occured while deleting a target group %s %w", d.Id(), err))
return diags
}
if errState := cloudapi.WaitForStateChange(ctx, meta, d, apiResponse, schema.TimeoutDelete); errState != nil {
return diag.FromErr(errState)
}
d.SetId("")
return nil
}
func resourceTargetGroupImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
client := meta.(services.SdkBundle).CloudApiClient
groupIp := d.Id()
groupTarget, apiResponse, err := client.TargetGroupsApi.TargetgroupsFindByTargetGroupId(ctx, groupIp).Execute()
logApiRequestTime(apiResponse)
if err != nil {
if httpNotFound(apiResponse) {
d.SetId("")
return nil, fmt.Errorf("unable to find target group %q", groupIp)
}
return nil, fmt.Errorf("an error occured while retrieving the target group %q, %w", groupIp, err)
}
if err := setTargetGroupData(d, &groupTarget); err != nil {
return nil, err
}
return []*schema.ResourceData{d}, nil
}
func setTargetGroupData(d *schema.ResourceData, targetGroup *ionoscloud.TargetGroup) error {
if targetGroup.Id != nil {
d.SetId(*targetGroup.Id)
}
if targetGroup.Properties != nil {
if targetGroup.Properties.Name != nil {
err := d.Set("name", *targetGroup.Properties.Name)
if err != nil {
return fmt.Errorf("error while setting name property for target group %s: %w", d.Id(), err)
}
}
if targetGroup.Properties.Algorithm != nil {
err := d.Set("algorithm", *targetGroup.Properties.Algorithm)
if err != nil {
return fmt.Errorf("error while setting algorithm property for target group %s: %w", d.Id(), err)
}
}
if targetGroup.Properties.Protocol != nil {
err := d.Set("protocol", *targetGroup.Properties.Protocol)
if err != nil {
return fmt.Errorf("error while setting protocol property for target group %s: %w", d.Id(), err)
}
}
forwardingRuleTargets := make([]interface{}, 0)
if targetGroup.Properties.Targets != nil && len(*targetGroup.Properties.Targets) > 0 {
forwardingRuleTargets = make([]interface{}, 0)
for _, target := range *targetGroup.Properties.Targets {
targetEntry := make(map[string]interface{})
if target.Ip != nil {
targetEntry["ip"] = *target.Ip
}
if target.Port != nil {
targetEntry["port"] = *target.Port
}
if target.Weight != nil {
targetEntry["weight"] = *target.Weight
}
if target.ProxyProtocol != nil {
targetEntry["proxy_protocol"] = *target.ProxyProtocol
}
if target.HealthCheckEnabled != nil {
targetEntry["health_check_enabled"] = *target.HealthCheckEnabled
}
if target.MaintenanceEnabled != nil {
targetEntry["maintenance_enabled"] = *target.MaintenanceEnabled
}
forwardingRuleTargets = append(forwardingRuleTargets, targetEntry)
}
}
if len(forwardingRuleTargets) > 0 {
if err := d.Set("targets", forwardingRuleTargets); err != nil {
return fmt.Errorf("error while setting targets property for target group %s: %w", d.Id(), err)
}
}
if targetGroup.Properties.HealthCheck != nil {
healthCheck := make([]interface{}, 1)
healthCheckEntry := make(map[string]interface{})
if targetGroup.Properties.HealthCheck.CheckTimeout != nil {
healthCheckEntry["check_timeout"] = *targetGroup.Properties.HealthCheck.CheckTimeout
}
if targetGroup.Properties.HealthCheck.CheckInterval != nil {
healthCheckEntry["check_interval"] = *targetGroup.Properties.HealthCheck.CheckInterval
}
if targetGroup.Properties.HealthCheck.Retries != nil {
healthCheckEntry["retries"] = *targetGroup.Properties.HealthCheck.Retries
}
healthCheck[0] = healthCheckEntry
err := d.Set("health_check", healthCheck)
if err != nil {
return fmt.Errorf("error while setting health_check property for target group %s: %w", d.Id(), err)
}
}
if targetGroup.Properties.HttpHealthCheck != nil {
httpHealthCheck := make([]interface{}, 1)
httpHealthCheckEntry := make(map[string]interface{})
if targetGroup.Properties.HttpHealthCheck.Path != nil {
httpHealthCheckEntry["path"] = *targetGroup.Properties.HttpHealthCheck.Path
}
if targetGroup.Properties.HttpHealthCheck.Method != nil {
httpHealthCheckEntry["method"] = *targetGroup.Properties.HttpHealthCheck.Method
}
if targetGroup.Properties.HttpHealthCheck.MatchType != nil {
httpHealthCheckEntry["match_type"] = *targetGroup.Properties.HttpHealthCheck.MatchType
}
if targetGroup.Properties.HttpHealthCheck.Response != nil {
httpHealthCheckEntry["response"] = *targetGroup.Properties.HttpHealthCheck.Response
}
if targetGroup.Properties.HttpHealthCheck.Regex != nil {
httpHealthCheckEntry["regex"] = *targetGroup.Properties.HttpHealthCheck.Regex
}
if targetGroup.Properties.HttpHealthCheck.Negate != nil {
httpHealthCheckEntry["negate"] = *targetGroup.Properties.HttpHealthCheck.Negate
}
httpHealthCheck[0] = httpHealthCheckEntry
err := d.Set("http_health_check", httpHealthCheck)
if err != nil {
return fmt.Errorf("error while setting http_health_check property for target group %s: %w", d.Id(), err)
}
}
}
return nil
}
func getTargetGroupTargetData(d *schema.ResourceData) *[]ionoscloud.TargetGroupTarget {
targets := make([]ionoscloud.TargetGroupTarget, 0)
if targetsVal, targetsOk := d.GetOk("targets"); targetsOk {
if targetsVal.([]interface{}) != nil {
for targetIndex := range targetsVal.([]interface{}) {
target := ionoscloud.TargetGroupTarget{}
if ip, ipOk := d.GetOk(fmt.Sprintf("targets.%d.ip", targetIndex)); ipOk {
ip := ip.(string)
target.Ip = &ip
}
if port, portOk := d.GetOk(fmt.Sprintf("targets.%d.port", targetIndex)); portOk {
port := int32(port.(int))
target.Port = &port
}
if weight, weightOk := d.GetOk(fmt.Sprintf("targets.%d.weight", targetIndex)); weightOk {
weight := int32(weight.(int))
target.Weight = &weight
}
if proxy, proxyOk := d.GetOk(fmt.Sprintf("targets.%d.proxy_protocol", targetIndex)); proxyOk {
proxy := proxy.(string)
target.ProxyProtocol = &proxy
}
healthCheck := d.Get(fmt.Sprintf("targets.%d.health_check_enabled", targetIndex)).(bool)
target.HealthCheckEnabled = &healthCheck
maintenance := d.Get(fmt.Sprintf("targets.%d.maintenance_enabled", targetIndex)).(bool)
target.MaintenanceEnabled = &maintenance
targets = append(targets, target)
}
}
}
return &targets
}
func getTargetGroupHealthCheckData(d *schema.ResourceData) *ionoscloud.TargetGroupHealthCheck {
healthCheck := ionoscloud.TargetGroupHealthCheck{}
if checkTimeout, checkTimeoutOk := d.GetOk("health_check.0.check_timeout"); checkTimeoutOk {
checkTimeout := int32(checkTimeout.(int))
healthCheck.CheckTimeout = &checkTimeout
}
if checkInterval, checkIntervalOk := d.GetOk("health_check.0.check_interval"); checkIntervalOk {
checkInterval := int32(checkInterval.(int))
healthCheck.CheckInterval = &checkInterval
}
if retries, retriesOk := d.GetOk("health_check.0.retries"); retriesOk {
retries := int32(retries.(int))
healthCheck.Retries = &retries
}
return &healthCheck
}
func getTargetGroupHttpHealthCheckData(d *schema.ResourceData) *ionoscloud.TargetGroupHttpHealthCheck {
httpHealthCheck := ionoscloud.TargetGroupHttpHealthCheck{}
if path, pathOk := d.GetOk("http_health_check.0.path"); pathOk {
path := path.(string)
httpHealthCheck.Path = &path
}
if method, methodOk := d.GetOk("http_health_check.0.method"); methodOk {
method := method.(string)
httpHealthCheck.Method = &method
}
if matchType, matchTypeOk := d.GetOk("http_health_check.0.match_type"); matchTypeOk {
matchType := matchType.(string)
httpHealthCheck.MatchType = &matchType
}
if response, responseOk := d.GetOk("http_health_check.0.response"); responseOk {
response := response.(string)
httpHealthCheck.Response = &response
}
if regex, regexOk := d.GetOk("http_health_check.0.regex"); regexOk {
regex := regex.(bool)
httpHealthCheck.Regex = ®ex
}
if negate, negateOk := d.GetOk("http_health_check.0.negate"); negateOk {
negate := negate.(bool)
httpHealthCheck.Negate = &negate
}
return &httpHealthCheck
}