-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
215 lines (188 loc) · 5.04 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
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"os"
"sort"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/endpoints"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/ec2"
)
const (
ubuntuImageSearch = "ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64*"
keyName = "aws-sdk-gov2-key"
ec2Type = "t2.micro"
userDataScriptFilename = "user_data.sh"
)
func main() {
// get ec2 connection
ec2Svc, err := getEC2Client(endpoints.UsEast1RegionID)
if err != nil {
exitErrorf("Unable to get EC2 Client, %v", err)
}
fmt.Printf("AWS connection %#v\n", ec2Svc)
// get latest ubuntu image
ubuntuAMI, err := findUbuntuAMI(ec2Svc)
if err != nil {
exitErrorf(
"Unable to find latest ubuntu image using search query [%s], %v",
ubuntuImageSearch, err)
}
fmt.Printf("AMI %s\n", ubuntuAMI)
// create key pair
err = createSSHKeyPair(ec2Svc)
if err != nil {
exitErrorf(
"Unable to create SSH Key Pair, %v", err)
}
// run instance
instanceID, err := runInstance(ec2Svc, ubuntuAMI)
if err != nil {
exitErrorf(
"Unable to run instance, %v", err)
}
// get instance public IP
pubIP, err := getInstancePublicIP(ec2Svc, instanceID)
if err != nil {
exitErrorf(
"Unable to get public IP for instance [%s], %v", instanceID, err)
}
fmt.Printf("\n\n\n ssh -i %s.pem ubuntu@%s\n\n\n", keyName, pubIP)
fmt.Printf("CLEANUP: ./cleanup.sh %s %s\n", instanceID, keyName)
}
func getEC2Client(region string) (*ec2.EC2, error) {
cfg, err := external.LoadDefaultAWSConfig()
if err != nil {
return nil, err
}
cfg.Region = endpoints.UsEast1RegionID
ec2Svc := ec2.New(cfg)
return ec2Svc, nil
}
type amazonImage struct {
ID string
CreationDate time.Time
}
type sortableamazonImage []*amazonImage
func (s sortableamazonImage) Len() int {
return len(s)
}
func (s sortableamazonImage) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortableamazonImage) Less(i, j int) bool {
return s[i].CreationDate.After(s[j].CreationDate)
}
func findUbuntuAMI(client *ec2.EC2) (string, error) {
fmt.Println("running findUbuntuAMI...")
diiFilter := ec2.Filter{
Name: aws.String("name"),
Values: []string{ubuntuImageSearch},
}
diiFilters := []ec2.Filter{diiFilter}
dii := ec2.DescribeImagesInput{
Filters: diiFilters,
}
dir := client.DescribeImagesRequest(&dii)
amis, err := dir.Send()
if err != nil {
return "", err
}
amisToSort := make([]*amazonImage, 0)
for _, ami := range amis.Images {
amiCreationDate, err := time.Parse(time.RFC3339, *ami.CreationDate)
if err != nil {
log.Fatal(err)
}
if len(ami.ProductCodes) > 0 {
fmt.Println("Skipping image:", *ami.ImageId)
continue
}
amiToAdd := &amazonImage{
ID: *ami.ImageId,
CreationDate: amiCreationDate,
}
amisToSort = append(amisToSort, amiToAdd)
}
sort.Sort(sortableamazonImage(amisToSort))
return amisToSort[0].ID, nil
}
func createSSHKeyPair(client *ec2.EC2) error {
fmt.Println("creating createSSHKeyPair...")
dkpi := ec2.DeleteKeyPairInput{
KeyName: aws.String(keyName),
}
rkpr := client.DeleteKeyPairRequest(&dkpi)
rkpr.Send()
ckpi := ec2.CreateKeyPairInput{
KeyName: aws.String(keyName),
}
ckp := client.CreateKeyPairRequest(&ckpi)
createKeyPairOutput, err := ckp.Send()
if err != nil {
return err
}
writeFile(keyName+".pem", []byte(*createKeyPairOutput.KeyMaterial))
return nil
}
func runInstance(client *ec2.EC2, ami string) (string, error) {
fmt.Println("runInstance using AMI:", ami)
userDataScript, err := readUsserDataScriptFileAndEncode()
if err != nil {
return "", err
}
rii := &ec2.RunInstancesInput{
ImageId: aws.String(ami),
InstanceType: ec2.InstanceType(ec2Type),
MinCount: aws.Int64(1),
MaxCount: aws.Int64(1),
KeyName: aws.String(keyName),
UserData: aws.String(userDataScript),
}
rir := client.RunInstancesRequest(rii)
reservation, err := rir.Send()
if err != nil {
return "", err
}
instanceID := reservation.Instances[0].InstanceId
err = waitForInstanceToBeOK(*instanceID)
if err != nil {
return "", err
}
return *reservation.Instances[0].InstanceId, nil
}
func getInstancePublicIP(client *ec2.EC2, instanceID string) (string, error) {
fmt.Println("getInstancePublicIP... instanceID: ", instanceID)
dii := &ec2.DescribeInstancesInput{
InstanceIds: []string{instanceID},
}
dir := client.DescribeInstancesRequest(dii)
describeInstancesOutput, err := dir.Send()
if err != nil {
return "", err
}
return *describeInstancesOutput.Reservations[0].Instances[0].PublicIpAddress, nil
}
func writeFile(filename string, contents []byte) error {
err := ioutil.WriteFile(filename, contents, 0400)
if err != nil {
return err
}
return nil
}
func readUsserDataScriptFileAndEncode() (string, error) {
f, err := ioutil.ReadFile(userDataScriptFilename)
if err != nil {
return "", err
}
userDataScript := base64.URLEncoding.EncodeToString(f)
return userDataScript, nil
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}