/
main.go
333 lines (286 loc) · 9.57 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
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
322
323
324
325
326
327
328
329
330
331
332
333
/*
Copyright © 2019 Keitaroh Kobayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"time"
"github.com/keichan34/ecs-fargate-login/utils"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ecs"
)
var version string
var commit string
var date string
func main() {
var taskDefinitionName, clusterName, cliContainerName, securityGroupsStr, subnetsStr string
var assignPublicIP bool
flag.StringVar(&taskDefinitionName, "n", "", "[Required] The name of the task definition this script will run an instance of.")
flag.StringVar(&securityGroupsStr, "sg", "", "[Required] A comma-delimited list of security groups the booted task should be assigned.")
flag.StringVar(&subnetsStr, "sn", "", "[Required] A comma-delimited list of subnets the task should consider when booting.")
flag.BoolVar(&assignPublicIP, "public", true, "Whether the ECS task should be assigned a public IP or not. Default `true`.")
flag.StringVar(&clusterName, "cluster", "default", "The name of the ECS cluster. Default `default`.")
flag.StringVar(&cliContainerName, "cli-container-name", "cli", "The name of the container in the task definition that refers to the SSH server. Default `cli`")
flag.Parse()
if taskDefinitionName == "" || securityGroupsStr == "" || subnetsStr == "" {
printVersionInfo()
flag.Usage()
os.Exit(1)
return
}
keyPair := generateKeyPair()
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
taskArn := runTask(sess, taskDefinitionName, clusterName, keyPair, assignPublicIP, securityGroupsStr, subnetsStr)
fmt.Printf("Started task: %s\n", *taskArn)
taskIP := getTaskIPAddress(sess, clusterName, taskArn, cliContainerName, assignPublicIP)
if taskIP == nil {
panic(fmt.Errorf("Couldn't determine task IP address"))
}
fmt.Printf("Task %s is running at %s!\n", *taskArn, *taskIP)
tmpfile, err := ioutil.TempFile("", "tmpsshkey")
if err != nil {
fmt.Println("We weren't able to save the key.")
panic("Error; exiting.")
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.Write([]byte(keyPair.PrivateKeyPEM)); err != nil {
fmt.Println("We weren't able to save the key.")
panic("Error; exiting.")
}
cmd := exec.Command(
"ssh",
"-p",
"22", // <- TODO: support different SSH port
"-i",
tmpfile.Name(),
"-o",
"UserKnownHostsFile=/dev/null",
"-o",
"StrictHostKeyChecking=no",
"-o",
"IdentitiesOnly=yes",
fmt.Sprintf("root@%s", *taskIP), // <- TODO: support different user
)
// redirect the output to terminal
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
fmt.Println("Disconnected from SSH. Waiting for task to stop...")
waitForTaskToStop(sess, clusterName, taskArn)
}
func printVersionInfo() {
if version != "" {
fmt.Printf(
"ecs-fargate-login %s (%s, built at %s)\n",
version,
commit,
date,
)
} else {
fmt.Println("ecs-fargate-login (development)")
}
}
func generateKeyPair() *utils.SSHKeyPair {
keyPair, err := utils.GenerateSSHKeyPair()
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
return keyPair
}
func waitForTaskToStop(sess *session.Session, clusterName string, taskArn *string) {
ecsSvc := ecs.New(sess)
describeTaskInput := &ecs.DescribeTasksInput{
Cluster: aws.String(clusterName),
Tasks: []*string{
taskArn,
},
}
err := ecsSvc.WaitUntilTasksStoppedWithContext(
aws.BackgroundContext(),
describeTaskInput,
request.WithWaiterDelay(request.ConstantWaiterDelay(5*time.Second)),
request.WithWaiterMaxAttempts(12), // 5 seconds * 12 = 1 minute
)
if err != nil {
aerr, ok := err.(awserr.Error)
if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode {
fmt.Println("Task hasn't stopped within 1 minute; forcibly stopping task...")
forciblyStopTask(sess, clusterName, taskArn)
}
}
ensureNoEcsError(err)
}
func forciblyStopTask(sess *session.Session, clusterName string, taskArn *string) {
ecsSvc := ecs.New(sess)
stopTaskInput := &ecs.StopTaskInput{
Cluster: aws.String(clusterName),
Task: taskArn,
}
_, err := ecsSvc.StopTask(stopTaskInput)
ensureNoEcsError(err)
fmt.Println("Task stopped.")
}
func runTask(sess *session.Session, taskDefinitionName string, clusterName string, keyPair *utils.SSHKeyPair, assignPublicIP bool, securityGroupsStr string, subnetsStr string) *string {
ecsSvc := ecs.New(sess)
var assignPublicIPStr string
if assignPublicIP == true {
assignPublicIPStr = "ENABLED"
} else {
assignPublicIPStr = "DISABLED"
}
resp, err := ecsSvc.RunTask(&ecs.RunTaskInput{
TaskDefinition: aws.String(taskDefinitionName),
Cluster: aws.String(clusterName),
StartedBy: aws.String("ecs-fargate-login"),
Overrides: &ecs.TaskOverride{
ContainerOverrides: []*ecs.ContainerOverride{
&ecs.ContainerOverride{
Name: aws.String("cli"),
Environment: []*ecs.KeyValuePair{
&ecs.KeyValuePair{
Name: aws.String("_AUTHORIZED_PUBLIC_KEY"),
Value: aws.String(keyPair.PublicKeyAuthorizedKey),
},
},
},
},
},
LaunchType: aws.String("FARGATE"),
NetworkConfiguration: &ecs.NetworkConfiguration{
AwsvpcConfiguration: &ecs.AwsVpcConfiguration{
AssignPublicIp: aws.String(assignPublicIPStr),
SecurityGroups: aws.StringSlice(strings.Split(securityGroupsStr, ",")),
Subnets: aws.StringSlice(strings.Split(subnetsStr, ",")),
},
},
})
ensureNoEcsError(err)
task := resp.Tasks[0]
return task.TaskArn
}
func getTaskIPAddress(sess *session.Session, clusterName string, taskArn *string, cliContainerName string, publicIP bool) *string {
ecsSvc := ecs.New(sess)
describeTaskInput := &ecs.DescribeTasksInput{
Cluster: aws.String(clusterName),
Tasks: []*string{
taskArn,
},
}
err := ecsSvc.WaitUntilTasksRunningWithContext(
aws.BackgroundContext(),
describeTaskInput,
request.WithWaiterDelay(request.ConstantWaiterDelay(5*time.Second)),
request.WithWaiterMaxAttempts(60), // 5 minutes = 5 seconds * 60
)
if err != nil {
aerr, ok := err.(awserr.Error)
if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode {
ecsTaskError(ecsSvc, describeTaskInput)
}
}
ensureNoEcsError(err)
resp, err := ecsSvc.DescribeTasks(describeTaskInput)
ensureNoEcsError(err)
var attachmentID *string
for _, container := range resp.Tasks[0].Containers {
if *container.Name == cliContainerName {
attachmentID = container.NetworkInterfaces[0].AttachmentId
}
}
if attachmentID == nil {
fmt.Println("Unable to determine IP address.")
panic("Error; exiting.")
}
var theID *string
for _, attachment := range resp.Tasks[0].Attachments {
if *attachment.Id == *attachmentID {
var keyToFind string
if publicIP {
keyToFind = "networkInterfaceId"
} else {
keyToFind = "privateIPv4Address"
}
for _, kv := range attachment.Details {
if *kv.Name == keyToFind {
theID = kv.Value
}
}
}
}
if !publicIP {
return theID
}
ec2Svc := ec2.New(sess)
netIntResp, err := ec2Svc.DescribeNetworkInterfaces(&ec2.DescribeNetworkInterfacesInput{
NetworkInterfaceIds: []*string{
theID,
},
})
ensureNoEcsError(err)
ipAddress := netIntResp.NetworkInterfaces[0].Association.PublicIp
return ipAddress
}
func ecsTaskError(ecsSvc *ecs.ECS, describeTaskInput *ecs.DescribeTasksInput) {
resp, err := ecsSvc.DescribeTasks(describeTaskInput)
ensureNoEcsError(err)
task := resp.Tasks[0]
out := []string{}
out = append(out, fmt.Sprintf("Task in status %s", *task.LastStatus))
if *task.LastStatus == "STOPPED" {
out = append(out, fmt.Sprintf("Stopped reason: %s", *task.StoppedReason))
}
for _, container := range task.Containers {
out = append(out, fmt.Sprintf("[%s] Status: %s", *container.Name, *container.LastStatus))
out = append(out, fmt.Sprintf("[%s] Status reason: %s", *container.Name, *container.Reason))
}
panic(fmt.Errorf(strings.Join(out, "\n")))
}
func ensureNoEcsError(err error) {
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case ecs.ErrCodeServerException:
fmt.Println(ecs.ErrCodeServerException, aerr.Error())
case ecs.ErrCodeClientException:
fmt.Println(ecs.ErrCodeClientException, aerr.Error())
case ecs.ErrCodeInvalidParameterException:
fmt.Println(ecs.ErrCodeInvalidParameterException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
panic("Error; exiting.")
}
}