/
attach.go
98 lines (76 loc) · 2.57 KB
/
attach.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
package cluster
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/mumoshu/terraform-provider-eksctl/pkg/sdk"
"log"
"strings"
)
func doAttachAutoScalingGroupsToTargetGroups(ctx *sdk.Context, set *ClusterSet) error {
if len(set.ListenerStatuses) == 0 {
return nil
}
cfn := cloudformation.New(ctx.Session())
var stackSummaries []*cloudformation.StackSummary
var nextToken *string
for {
res, err := cfn.ListStacks(&cloudformation.ListStacksInput{
NextToken: nextToken,
StackStatusFilter: aws.StringSlice(
[]string{
cloudformation.StackStatusCreateComplete,
cloudformation.StackStatusUpdateComplete,
},
),
})
if err != nil {
return fmt.Errorf("attaching autoscaling groups to target groups: %w", err)
}
stackSummaries = append(stackSummaries, res.StackSummaries...)
nextToken = res.NextToken
if nextToken == nil {
break
}
}
stackNamePrefix := fmt.Sprintf("eksctl-%s-nodegroup-", set.ClusterName)
log.Printf("Finding stacks whose name is prefixd with %q from %d stack summaries", stackNamePrefix, len(stackSummaries))
asSvc := autoscaling.New(ctx.Session())
for _, s := range stackSummaries {
if strings.HasPrefix(*s.StackName, stackNamePrefix) {
log.Printf("processing stack summary for %s", *s.StackName)
var targetGroupARNS []*string
ngName := strings.TrimPrefix(*s.StackName, stackNamePrefix)
for _, l := range set.ListenerStatuses {
for _, a := range l.ALBAttachments {
if a.NodeGroupName == ngName {
targetGroupARNS = append(targetGroupARNS, l.DesiredTG.TargetGroupArn)
}
}
}
if len(targetGroupARNS) == 0 {
continue
}
res, err := cfn.DescribeStackResource(&cloudformation.DescribeStackResourceInput{
LogicalResourceId: aws.String("NodeGroup"),
StackName: s.StackName,
})
if err != nil {
return fmt.Errorf("describing stack resource for %s: %w", *s.StackName, err)
}
asgARN := *res.StackResourceDetail.PhysicalResourceId
_, asErr := asSvc.AttachLoadBalancerTargetGroups(&autoscaling.AttachLoadBalancerTargetGroupsInput{
AutoScalingGroupName: aws.String(asgARN),
TargetGroupARNs: targetGroupARNS,
})
if aerr, ok := asErr.(awserr.Error); ok {
return fmt.Errorf("attaching load balancer target groups: Code %s: %w", aerr.Code(), asErr)
} else if asErr != nil {
return fmt.Errorf("attaching load balancer target groups: unexpected error: %w", asErr)
}
}
}
return nil
}