-
Notifications
You must be signed in to change notification settings - Fork 4
/
ec2_run.go
321 lines (255 loc) · 8.39 KB
/
ec2_run.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package ec2
//-----------------------------------------------------------------------------
// Package factored import statement:
//-----------------------------------------------------------------------------
import (
// Stdlib:
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
// Community:
log "github.com/Sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/elb"
)
//-----------------------------------------------------------------------------
// func: Run
//-----------------------------------------------------------------------------
// Run uses EC2 API to launch a new instance.
func (d *Data) Run() {
// Set current command:
d.command = "run"
// Read udata from stdin:
udata, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.WithField("cmd", "ec2:"+d.command).Fatal(err)
}
// Connect and authenticate to the API endpoints:
d.ec2 = ec2.New(session.New(&aws.Config{Region: aws.String(d.Region)}))
d.elb = elb.New(session.New(&aws.Config{Region: aws.String(d.Region)}))
// Run the EC2 instance:
if err := d.runInstance(udata); err != nil {
log.WithField("cmd", "ec2:"+d.command).Fatal(err)
}
// Modify instance attributes:
if err := d.modifyInstanceAttribute(); err != nil {
log.WithField("cmd", "ec2:"+d.command).Fatal(err)
}
// Setup an elastic IP:
if d.PublicIP == "elastic" {
if err := d.setupElasticIP(); err != nil {
log.WithField("cmd", "ec2:"+d.command).Fatal(err)
}
}
// Register with ELB:
if d.ELBName != "" {
if err := d.registerWithELB(); err != nil {
log.WithField("cmd", "ec2:"+d.command).Fatal(err)
}
}
// Output IP addresses to stdout:
if err := d.stdoutIPs(); err != nil {
log.WithField("cmd", "ec2:"+d.command).Warning(err)
}
}
//-----------------------------------------------------------------------------
// func: runInstance
//-----------------------------------------------------------------------------
func (d *Data) runInstance(udata []byte) error {
// Forge the instance request:
params := &ec2.RunInstancesInput{
ImageId: aws.String(d.AmiID),
MinCount: aws.Int64(1),
MaxCount: aws.Int64(1),
KeyName: aws.String(d.KeyPair),
InstanceType: aws.String(d.InstanceType),
NetworkInterfaces: d.forgeNetworkInterfaces(),
Placement: &ec2.Placement{
AvailabilityZone: aws.String(d.Region + d.Zone),
},
UserData: aws.String(base64.StdEncoding.EncodeToString([]byte(udata))),
IamInstanceProfile: &ec2.IamInstanceProfileSpecification{
Name: aws.String(d.IAMRole),
},
}
// Send the instance request:
resp, err := d.ec2.RunInstances(params)
if err != nil {
return err
}
// Store the instance ID:
d.InstanceID = *resp.Instances[0].InstanceId
log.WithFields(log.Fields{"cmd": "ec2:" + d.command, "id": d.InstanceID}).
Info("New " + d.InstanceType + " EC2 instance requested")
// Store the interface ID:
d.InterfaceID = *resp.Instances[0].
NetworkInterfaces[0].NetworkInterfaceId
// Tag the instance:
if err := d.tag(d.InstanceID, "Name", d.TagName); err != nil {
return err
}
// Pretty-print to stderr:
log.WithFields(log.Fields{"cmd": "ec2:" + d.command, "id": d.TagName}).
Info("New EC2 instance tagged")
return nil
}
//-----------------------------------------------------------------------------
// func: forgeNetworkInterfaces
//-----------------------------------------------------------------------------
func (d *Data) forgeNetworkInterfaces() []*ec2.
InstanceNetworkInterfaceSpecification {
var networkInterfaces []*ec2.InstanceNetworkInterfaceSpecification
var securityGroupIds []*string
// Append to security group array:
for _, grp := range strings.Split(d.SecGrpIDs, ",") {
securityGroupIds = append(securityGroupIds, aws.String(grp))
}
// Forge the interface data type:
iface := ec2.InstanceNetworkInterfaceSpecification{
DeleteOnTermination: aws.Bool(true),
DeviceIndex: aws.Int64(int64(0)),
Groups: securityGroupIds,
SubnetId: aws.String(d.SubnetID),
}
// Private IP address:
if d.PrivateIP != "" {
iface.PrivateIpAddress = aws.String(d.PrivateIP)
}
// Public IP address:
if d.PublicIP == "true" {
iface.AssociatePublicIpAddress = aws.Bool(true)
}
// Append to the interfaces array:
networkInterfaces = append(networkInterfaces, &iface)
return networkInterfaces
}
//-----------------------------------------------------------------------------
// func: modifyInstanceAttribute
//-----------------------------------------------------------------------------
func (d *Data) modifyInstanceAttribute() error {
// Variable transformation:
SrcDstCheck, err := strconv.ParseBool(d.SrcDstCheck)
if err != nil {
return err
}
// Forge the attribute modification request:
params := &ec2.ModifyInstanceAttributeInput{
InstanceId: aws.String(d.InstanceID),
SourceDestCheck: &ec2.AttributeBooleanValue{
Value: aws.Bool(SrcDstCheck),
},
}
// Send the attribute modification request:
_, err = d.ec2.ModifyInstanceAttribute(params)
if err != nil {
return err
}
return nil
}
//-----------------------------------------------------------------------------
// func: setupElasticIP
//-----------------------------------------------------------------------------
func (d *Data) setupElasticIP() error {
// Allocate an elastic IP address:
if err := d.allocateElasticIP(); err != nil {
return err
}
// Associate the elastic IP:
if err := d.associateElasticIP(); err != nil {
return err
}
return nil
}
//-----------------------------------------------------------------------------
// func: associateElasticIP
//-----------------------------------------------------------------------------
func (d *Data) associateElasticIP() error {
// Wait until instance is running:
if err := d.ec2.WaitUntilInstanceRunning(&ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(d.InstanceID)}}); err != nil {
return err
}
// Forge the association request:
params := &ec2.AssociateAddressInput{
AllocationId: aws.String(d.AllocationID),
AllowReassociation: aws.Bool(true),
NetworkInterfaceId: aws.String(d.InterfaceID),
}
// Send the association request:
resp, err := d.ec2.AssociateAddress(params)
if err != nil {
return err
}
// Log to stderr:
log.WithFields(log.Fields{
"cmd": "ec2:" + d.command, "id": *resp.AssociationId}).
Info("New elastic IP association")
return nil
}
//-----------------------------------------------------------------------------
// func: registerWithELB
//-----------------------------------------------------------------------------
func (d *Data) registerWithELB() error {
// Forge the register request:
params := &elb.RegisterInstancesWithLoadBalancerInput{
Instances: []*elb.Instance{
{
InstanceId: aws.String(d.InstanceID),
},
},
LoadBalancerName: aws.String(d.ELBName),
}
// Send the register request:
if _, err := d.elb.RegisterInstancesWithLoadBalancer(params); err != nil {
return err
}
// Log this action:
log.WithFields(log.Fields{"cmd": "ec2:" + d.command, "id": d.ELBName}).
Info("Instance registered with ELB")
return nil
}
//-----------------------------------------------------------------------------
// func: stdoutIPs
//-----------------------------------------------------------------------------
func (d *Data) stdoutIPs() error {
// Forge the describe request:
params := &ec2.DescribeNetworkInterfacesInput{
NetworkInterfaceIds: []*string{
aws.String(d.InterfaceID),
},
}
// Send the describe request:
resp, err := d.ec2.DescribeNetworkInterfaces(params)
if err != nil {
return err
}
// Map to store the output:
m := make(map[string]string)
// Extract data from response:
if len(resp.NetworkInterfaces) > 0 && len(resp.NetworkInterfaces[0].PrivateIpAddresses) > 0 {
// Internal IP address:
if resp.NetworkInterfaces[0].PrivateIpAddresses[0].PrivateIpAddress != nil {
m["internal"] = *resp.NetworkInterfaces[0].PrivateIpAddresses[0].PrivateIpAddress
}
// External IP address:
if resp.NetworkInterfaces[0].PrivateIpAddresses[0].Association != nil {
if resp.NetworkInterfaces[0].PrivateIpAddresses[0].Association.PublicIp != nil {
m["external"] = *resp.NetworkInterfaces[0].PrivateIpAddresses[0].Association.PublicIp
}
}
}
// JSON encode:
jsn, err := json.Marshal(m)
if err != nil {
return err
}
// Print and return:
fmt.Println(string(jsn))
return nil
}