-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
243 lines (215 loc) · 5.65 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
package main
import (
"errors"
"fmt"
"math/rand"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/aws/aws-sdk-go/aws"
awsSession "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
connect "github.com/aws/aws-sdk-go/service/ec2instanceconnect"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli/v2" // imports as package "cli"
"github.com/nodefortytwo/amz-ssh/pkg/sshutils"
"github.com/nodefortytwo/amz-ssh/pkg/update"
)
var version = "0.0.0"
func main() {
rand.Seed(time.Now().Unix())
setupSignalHandlers()
app := &cli.App{
Name: "amz-ssh",
Usage: "connect to an ec2 instance via ec2 connect",
Version: version,
Action: run,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "region",
Aliases: []string{"r"},
EnvVars: []string{"AWS_REGION"},
Value: "eu-west-1",
},
&cli.StringFlag{
Name: "tag",
Value: "role:bastion",
},
&cli.StringFlag{
Name: "instance-id",
Aliases: []string{"i"},
Usage: "instance id to ssh to or tunnel through",
Value: "",
},
&cli.StringFlag{
Name: "user",
Aliases: []string{"u"},
Usage: "OS user of bastion",
Value: "ec2-user",
},
&cli.StringFlag{
Name: "tunnel",
Aliases: []string{"t"},
Usage: "Host to tunnel to",
},
&cli.StringSliceFlag{
Name: "destination",
Aliases: []string{"d"},
Usage: "destination to ssh to via the bastion. This flag can be provided multiple times to allow for multple hops",
},
&cli.IntFlag{
Name: "port",
Aliases: []string{"p"},
Value: 22,
},
&cli.IntFlag{
Name: "local-port",
Aliases: []string{"lp"},
Usage: "local port to map to, defaults to tunnel port",
},
&cli.BoolFlag{
Name: "debug",
Usage: "Print debug information",
},
},
Commands: []*cli.Command{
{
Name: "update",
Usage: "Update the cli",
Action: update.Handler,
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func setupSignalHandlers() {
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
fmt.Println("\nGoodbye!")
os.Exit(0)
}()
}
func run(c *cli.Context) error {
if c.Bool("debug") {
log.SetLevel(log.DebugLevel)
}
var tagName string
var tagValue string
if parts := strings.Split(c.String("tag"), ":"); len(parts) == 2 {
tagName = parts[0]
tagValue = parts[1]
} else {
return fmt.Errorf("%s is not a valid tag definition, use key:value", c.String("tag"))
}
ec2Client := ec2Client(c.String("region"))
connectClient := connectClient(c.String("region"))
instanceID := c.String("instance-id")
if instanceID == "" {
var err error
instanceID, err = resolveBastionInstanceID(ec2Client, tagName, tagValue)
if err != nil {
return err
}
}
bastionAddr := fmt.Sprintf("%s@%s:%d", c.String("user"), instanceID, c.Int("port"))
bastionEndpoint, err := sshutils.NewEC2Endpoint(bastionAddr, ec2Client, connectClient)
if err != nil {
return err
}
if tunnel := sshutils.NewEndpoint(c.String("tunnel")); tunnel.Host != "" {
p := c.Int("local-port")
if p == 0 {
p = tunnel.Port
}
return sshutils.Tunnel(p, tunnel, bastionEndpoint)
}
chain := []sshutils.EndpointIface{
bastionEndpoint,
}
for _, ep := range c.StringSlice("destination") {
destEndpoint, err := sshutils.NewEC2Endpoint(ep, ec2Client, connectClient)
if err != nil {
return err
}
destEndpoint.UsePrivate = true
chain = append(chain, destEndpoint)
}
return sshutils.Connect(chain...)
}
func getSpotRequestByTag(ec2Client *ec2.EC2, tagName, tagValue string) (*ec2.DescribeSpotInstanceRequestsOutput, error) {
return ec2Client.DescribeSpotInstanceRequests(&ec2.DescribeSpotInstanceRequestsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag:" + tagName),
Values: aws.StringSlice([]string{tagValue}),
},
{
Name: aws.String("state"),
Values: aws.StringSlice([]string{"active"}),
},
{
Name: aws.String("status-code"),
Values: aws.StringSlice([]string{"fulfilled"}),
},
},
})
}
func getInstanceByTag(ec2Client *ec2.EC2, tagName, tagValue string) (*ec2.DescribeInstancesOutput, error) {
return ec2Client.DescribeInstances(&ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag:" + tagName),
Values: aws.StringSlice([]string{tagValue}),
},
{
Name: aws.String("instance-state-name"),
Values: aws.StringSlice([]string{"running"}),
},
},
})
}
func resolveBastionInstanceID(ec2Client *ec2.EC2, tagName, tagValue string) (string, error) {
log.Info("Looking for bastion spot request")
siro, err := getSpotRequestByTag(ec2Client, tagName, tagValue)
if err != nil {
return "", err
}
if len(siro.SpotInstanceRequests) > 0 {
return aws.StringValue(siro.SpotInstanceRequests[rand.Intn(len(siro.SpotInstanceRequests))].InstanceId), nil
}
log.Info("No spot requests found, looking for instance directly")
dio, err := getInstanceByTag(ec2Client, tagName, tagValue)
if err != nil {
return "", err
}
if len(dio.Reservations) > 0 {
res := dio.Reservations[rand.Intn(len(dio.Reservations))]
return aws.StringValue(res.Instances[rand.Intn(len(res.Instances))].InstanceId), nil
}
return "", errors.New("unable to find any valid bastion instances")
}
func ec2Client(region string) *ec2.EC2 {
sess, err := awsSession.NewSession(&aws.Config{
Region: aws.String(region),
})
if err != nil {
log.Fatal(err)
}
return ec2.New(sess)
}
func connectClient(region string) *connect.EC2InstanceConnect {
sess, err := awsSession.NewSession(&aws.Config{
Region: aws.String(region),
})
if err != nil {
log.Fatal(err)
}
return connect.New(sess)
}