-
Notifications
You must be signed in to change notification settings - Fork 0
/
startstopinstances.go
112 lines (97 loc) · 2.23 KB
/
startstopinstances.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
package main
import (
"bufio"
"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"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage:")
fmt.Println(" startstopinstances (start|stop|status)")
return
}
action := os.Args[1]
if action != "start" && action != "stop" && action != "status" {
fmt.Println("Usage:")
fmt.Println(" startstopinstances (start|stop|status)")
return
}
homedir, err := os.UserHomeDir()
if err != nil {
fmt.Println("Unable to retriever user home directory.")
return
}
f, err := os.Open(homedir + "/.aws/instances")
if err != nil {
fmt.Println("Error openning ~/.aws/instances.")
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
instances := []*string{}
for scanner.Scan() {
instances = append(instances, aws.String(scanner.Text()))
}
session := session.Must(session.NewSession(&aws.Config{Region: aws.String("us-east-1")}))
svc := ec2.New(session)
if action == "stop" {
fmt.Println("Stopping instances: ")
for _, i := range instances {
fmt.Println(*i)
}
input := &ec2.StopInstancesInput{
InstanceIds: instances,
}
_, err = svc.StopInstances(input)
if err != nil {
println(err.Error())
}
}
if action == "start" {
fmt.Println("Starting instances: ")
for _, i := range instances {
fmt.Println(*i)
}
input := &ec2.StartInstancesInput{
InstanceIds: instances,
}
_, err = svc.StartInstances(input)
if err != nil {
println(err.Error())
}
}
if action == "status" {
result, err := svc.DescribeInstances(nil)
if err != nil {
panic(err.Error())
}
for _, reservation := range result.Reservations {
for _, instance := range reservation.Instances {
id := *instance.InstanceId
name := ""
for _, i := range instance.Tags {
if *i.Key == "Name" {
name = *i.Value
}
}
state := *instance.State.Name
ip := "none"
if instance.PublicIpAddress != nil {
ip = *instance.PublicIpAddress
}
instanceManaged := false
for _, i := range instances {
if id == *i {
instanceManaged = true
}
}
if instanceManaged {
fmt.Printf("%-20s %-20s %10s %15s\n", id, name, state, ip)
}
}
}
}
}