-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (67 loc) · 1.74 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
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
var region string
func init() {
region = os.Getenv("AWS_DEFAULT_REGION")
}
func main() {
// Use environment variable
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region)},
)
// Create new EC2 client
svc := ec2.New(sess)
// Delete Instances
deleteInstances(svc, err)
// Delete Security Groups
deleteSecurityGroups(svc, err)
}
func deleteInstances(svc *ec2.EC2, err error) {
result, err := svc.DescribeInstances(nil)
if err != nil {
fmt.Println("Error", err)
}
fmt.Println("Found", len(result.Reservations), "Reservation(s) in", region)
for _, reservation := range result.Reservations {
instances := reservation.Instances[0]
if *instances.State.Name != "terminated" {
input := &ec2.TerminateInstancesInput{
InstanceIds: []*string{
aws.String(*instances.InstanceId),
},
}
result, err := svc.TerminateInstances(input)
if err != nil {
fmt.Println("Error", err)
} else {
fmt.Println("Success terminate", result.TerminatingInstances)
}
}
fmt.Println("")
}
}
func deleteSecurityGroups(svc *ec2.EC2, err error) {
result, err := svc.DescribeSecurityGroups(nil)
if err != nil {
fmt.Println("Error", err)
}
fmt.Println("Found", len(result.SecurityGroups), "SecurityGroup(s) in", region)
for _, securityGroup := range result.SecurityGroups {
groupID := securityGroup.GroupId
_, err := svc.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{
GroupId: aws.String(*groupID),
})
if err != nil {
fmt.Println("Error", err)
} else {
fmt.Println("Success delete source group", *groupID)
}
}
fmt.Println("")
}