-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
274 lines (245 loc) · 9.14 KB
/
main.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
package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/elbv2"
"github.com/hashicorp/logutils"
flags "github.com/jessevdk/go-flags"
"github.com/meirf/gopart"
"github.com/pkg/errors"
)
// Options contains the flag options
type Options struct {
LogLevel string `long:"log-level" description:"The minimum log level to output (DEBUG, INFO, WARN, ERROR, FATAL)" default:"INFO"`
ASG string `long:"asg" description:"The ASG to update." required:"true"`
DryRun bool `long:"dry-run" description:"If set updates are not actually performed."`
Version bool `long:"version" description:"print version and exit"`
Force bool `long:"force" description:"by default if no instances are found at latest version tool does nothing"`
PrintLatestInstances bool `long:"output-latest-instances" description:"print up-to-date instances to stdout"`
PrintInvalidInstances bool `long:"output-invalid-instances" description:"print out-of-date instances to stdout"`
Deregister bool `long:"deregister-from-target-groups" description:"remove old instances from target groups as well"`
}
// These variables are filled by goreleaser
var (
version = "dev"
commit = "none"
date = "unknown"
)
func main() {
options := Options{}
parser := flags.NewParser(&options, flags.Default)
_, err := parser.Parse()
if err != nil {
if e, ok := err.(*flags.Error); ok && e.Type != flags.ErrHelp {
fmt.Printf("\n")
parser.WriteHelp(os.Stderr)
fmt.Printf("\n")
}
os.Exit(1)
}
// Init Logger
filter := &logutils.LevelFilter{
Levels: []logutils.LogLevel{"SPAM", "DEBUG", "INFO", "WARN", "ERROR", "DRYRUN"},
MinLevel: logutils.LogLevel(options.LogLevel),
Writer: os.Stderr,
}
log.SetOutput(filter)
if options.Version {
fmt.Printf("%s-%s-%s\n", version, commit, date)
os.Exit(0)
}
err = doUpdate(&options)
if err != nil {
log.Fatalf("[FATAL] error updating: %v", err)
}
}
func doUpdate(options *Options) error {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
asgClient := autoscaling.New(sess)
albClient := elbv2.New(sess)
log.Printf("[DEBUG] describing ASG %s...", options.ASG)
asgResponse, err := asgClient.DescribeAutoScalingGroups(&autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []*string{
aws.String(options.ASG),
},
})
if err != nil {
return errors.Wrap(err, "could not describe Auto Scaling Group")
}
if asgResponse == nil {
return errors.New("invalid describe Auto Scaling Group response")
}
if len(asgResponse.AutoScalingGroups) != 1 {
return errors.Errorf("auto scaling group \"%s\" not found", options.ASG)
}
asg := asgResponse.AutoScalingGroups[0]
var ltName *string
if asg.LaunchTemplate != nil {
ltName = asg.LaunchTemplate.LaunchTemplateName
} else if asg.MixedInstancesPolicy != nil && asg.MixedInstancesPolicy.LaunchTemplate != nil {
ltName = asg.MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateName
}
if ltName == nil {
return errors.Errorf("auto scaling group \"%s\" does not use Launch Templates", options.ASG)
}
log.Printf("[DEBUG] ASG %s uses Launch Template %s, describing LT...", options.ASG, *ltName)
ec2Client := ec2.New(sess)
ltResponse, err := ec2Client.DescribeLaunchTemplates(&ec2.DescribeLaunchTemplatesInput{
LaunchTemplateNames: []*string{
ltName,
},
})
if err != nil {
return errors.Wrap(err, "could not describe Launch Template "+*ltName)
}
if ltResponse == nil || len(ltResponse.LaunchTemplates) != 1 {
return errors.New("invalid describe Launch Template response for " + *ltName)
}
lt := ltResponse.LaunchTemplates[0]
if lt.LatestVersionNumber == nil {
return errors.New("no latest version for Launch Template " + *ltName)
}
latestVersion := *lt.LatestVersionNumber
log.Printf("[INFO] ASG %s has latest version %d, looking for old instances...", options.ASG, latestVersion)
instanceIdsToRemove := make([]*string, 0)
latestInstances := make([]string, 0)
invalidInstances := make([]string, 0)
oldInstances := make([]*string, 0)
instancesToDeregister := make([]*string, 0)
for _, instance := range asg.Instances {
if instance.LaunchTemplate == nil || instance.LaunchTemplate.Version == nil {
return errors.New("missing Launch Template version for instance id " + *instance.InstanceId)
}
if *instance.LaunchTemplate.LaunchTemplateName != *ltName {
log.Printf(
"[WARN] instance %s has different Launch Template than ASG: %s:%s",
*instance.InstanceId,
*instance.LaunchTemplate.LaunchTemplateName,
*instance.LaunchTemplate.Version,
)
if *instance.ProtectedFromScaleIn == false {
log.Printf("[DEBUG] instance %s is already not protected from scale-in, skipping", *instance.InstanceId)
oldInstances = append(oldInstances, instance.InstanceId)
} else {
instanceIdsToRemove = append(instanceIdsToRemove, instance.InstanceId)
}
continue
}
version, err := strconv.ParseInt(*instance.LaunchTemplate.Version, 10, 64)
if err != nil {
return errors.Wrap(err, "invalid instance Launch Template Version")
}
if version != latestVersion {
log.Printf("[DEBUG] instance %s has old version %d", *instance.InstanceId, version)
invalidInstances = append(invalidInstances, *instance.InstanceId)
if *instance.ProtectedFromScaleIn == false {
log.Printf("[DEBUG] old instance %s is already not protected from scale-in, skipping", *instance.InstanceId)
oldInstances = append(oldInstances, instance.InstanceId)
} else {
instanceIdsToRemove = append(instanceIdsToRemove, instance.InstanceId)
}
} else {
latestInstances = append(latestInstances, *instance.InstanceId)
}
}
if options.PrintLatestInstances {
for _, instance := range latestInstances {
fmt.Println(instance)
}
}
if options.PrintInvalidInstances {
for _, instance := range invalidInstances {
fmt.Println(instance)
}
}
instancesToDeregister = append(instancesToDeregister, oldInstances...)
instancesToDeregister = append(instancesToDeregister, instanceIdsToRemove...)
if options.Deregister && len(latestInstances) > 0 && len(instancesToDeregister) > 0 {
// find target groups to remove instances from
for _, tg := range asg.TargetGroupARNs {
healthy, err := albClient.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{
TargetGroupArn: tg,
})
if err != nil {
return errors.Wrapf(err, "could not get target group instances for %s", *tg)
}
targets := make([]*elbv2.TargetDescription, 0)
TARGETS: // label to goto if target is found
for _, h := range healthy.TargetHealthDescriptions {
for _, old := range instancesToDeregister {
if *h.Target.Id == *old {
targets = append(targets, h.Target)
continue TARGETS
}
}
}
for partition := range gopart.Partition(len(targets), 50) {
targets := targets[partition.Low:partition.High]
if options.DryRun {
for _, target := range targets {
log.Printf("[DRYRUN] would remove instance %s from target group %s", strings.ReplaceAll(target.String(), "\n", ""), *tg)
}
} else {
_, err = albClient.DeregisterTargets(&elbv2.DeregisterTargetsInput{
TargetGroupArn: tg,
Targets: targets,
})
if err != nil {
return errors.Wrapf(err, "could not deregister targets from %s", *tg)
}
log.Printf("[INFO] Removed %d instances from %s", len(targets), *tg)
}
}
}
}
if len(instanceIdsToRemove) == 0 {
log.Printf("[INFO] No old instances with scale in protection enabled found")
return nil
}
if len(latestInstances) == 0 {
log.Printf("[WARN] No instances at latest Launch Template version %d found", latestVersion)
if !options.Force {
log.Printf("[WARN] no changes made, use `--force` flag to override this behavior")
return nil
} else {
log.Printf("[WARN] `--force` flag provided, potentially updating all instances")
}
}
if options.DryRun {
log.Printf("[DRYRUN] Removing scale in protection for %d instances", len(instanceIdsToRemove))
} else {
log.Printf("[INFO] Removing scale in protection for %d instances", len(instanceIdsToRemove))
}
// partition into groups of at most 50
for partition := range gopart.Partition(len(instanceIdsToRemove), 50) {
instanceIds := instanceIdsToRemove[partition.Low:partition.High]
if options.DryRun {
for _, instance := range instanceIds {
log.Printf("[DRYRUN] would remove instance protection on instanceId %s", *instance)
}
continue
}
log.Printf("[DEBUG] calling SetInstanceProtection with %d instances", len(instanceIds))
_, err = asgClient.SetInstanceProtection(&autoscaling.SetInstanceProtectionInput{
AutoScalingGroupName: aws.String(options.ASG),
InstanceIds: instanceIds,
ProtectedFromScaleIn: aws.Bool(false),
})
if err != nil {
return errors.Wrap(err, "set instance protection failed")
}
for _, instance := range instanceIds {
log.Printf("[DEBUG] instance protection removed for instance: %s", *instance)
}
}
return nil
}