-
Notifications
You must be signed in to change notification settings - Fork 0
/
ec2.go
78 lines (63 loc) · 1.61 KB
/
ec2.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
package main
import (
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/codegangsta/cli"
)
func hasEC2Tag(tags []*ec2.Tag, key, value string) bool {
if tags != nil {
for _, tag := range tags {
if *tag.Key == key && *tag.Value == value {
return true
}
}
}
return false
}
func teardownEC2(c *cli.Context) {
opts := Opts(c)
api := ec2.New(&aws.Config{Region: aws.String(opts.Region)})
// 1. find instances that match our app/env tags
output, err := api.DescribeInstances(&ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag:app"),
Values: []*string{aws.String(opts.App)},
},
{
Name: aws.String("tag:env"),
Values: []*string{aws.String(opts.Env)},
},
},
})
if err != nil {
log.Fatalln(err)
}
// 2. construct a list of instanceIds, excluding the version specified
instanceIds := []*string{}
for _, reservation := range output.Reservations {
for _, instance := range reservation.Instances {
if hasEC2Tag(instance.Tags, "version", opts.Exclude) {
continue
}
instanceIds = append(instanceIds, instance.InstanceId)
}
}
// 3. terminate those instances
if len(instanceIds) == 0 {
log.Println("no instances to terminate")
return
}
if opts.Dry {
log.Printf("dry run mode - would otherwise terminate %d instance(s)\n", len(instanceIds))
return
}
terminateOutput, err := api.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: instanceIds,
})
if err != nil {
log.Fatalln(err)
}
log.Println("terminating %d instances", len(terminateOutput.TerminatingInstances))
}