Skip to content

Commit

Permalink
Merge pull request #1 from adhocteam/v2
Browse files Browse the repository at this point in the history
Update to aws-go-sdk-v2, use go modules, improve AWS config
  • Loading branch information
cgansen authored Feb 7, 2019
2 parents 12bb663 + 19c6582 commit 93cdc6c
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 62 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ $ ec2ssh 1.2.3.4
Specify an AWS profile other than "default":

```
$ ec2ssh --profile profilenamehere
$ AWS_PROFILE=altprofile ec2ssh
```

Specify an AWS region other than "us-east-1":

```
$ ec2ssh --region us-west-2
$ AWS_REGION=us-west-2 ec2ssh
```

See a list of running/pending instance names and ids:
Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/adhocteam/ec2ssh

require github.com/aws/aws-sdk-go-v2 v0.7.0
16 changes: 16 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
github.com/aws/aws-sdk-go-v2 v0.7.0 h1:a5xRI/tBmUFKuAA0SOyEY2P1YhQb+jVOEI9P/7KfrP0=
github.com/aws/aws-sdk-go-v2 v0.7.0/go.mod h1:17MaCZ9g0q5BIMxwzRQeiv8M3c8+W7iuBnlWAEprcxE=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/gucumber/gucumber v0.0.0-20180127021336-7d5c79e832a2/go.mod h1:YbdHRK9ViqwGMS0rtRY+1I6faHvVyyurKPIPwifihxI=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
91 changes: 31 additions & 60 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ import (
"strings"
"text/tabwriter"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/awserr"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/ec2"
)

func usage() {
Expand All @@ -31,8 +31,6 @@ func usage() {
Options:
-v be verbose (passes -v to underlying SSH invocation)
-p path to SSH key files
-P, --profile AWS profile to be used for the session (optional)
-r, --region AWS region to target when creating an AWS session (optional)
-l, --list list running and pending AWS instances
-c, --command run a command on the remote server
`, filepath.Base(os.Args[0]))
Expand All @@ -43,8 +41,6 @@ var verboseFlag bool
var remoteCommand string
var listInstances bool
var kp string
var profile string
var region string

var instIdRe = regexp.MustCompile(`i-[0-9a-fA-F]{8,17}$`)

Expand Down Expand Up @@ -89,7 +85,7 @@ func printError(err error) {
os.Exit(1)
}

func reservationsToInstances(reservations []*ec2.Reservation) []*Instance {
func reservationsToInstances(reservations []ec2.RunInstancesOutput) []*Instance {
var instances []*Instance
for _, reservation := range reservations {
for _, instance := range reservation.Instances {
Expand Down Expand Up @@ -143,23 +139,6 @@ func init() {
flag.StringVar(&kp, "p", p, "path to directory with SSH keys, default is $HOME/.ssh")
flag.BoolVar(&verboseFlag, "v", false, "be verbose")

const (
defaultProfile = "default"
profileDesc = "the named profile to use when creating a new AWS session"
)
flag.StringVar(&profile, "P", defaultProfile, profileDesc)
flag.StringVar(&profile, "profile", defaultProfile, profileDesc)

const regionDesc = "the region to target when creating an AWS session"

defaultRegion := os.Getenv("AWS_DEFAULT_REGION")
if defaultRegion == "" {
defaultRegion = "us-east-1"
}

flag.StringVar(&region, "r", defaultRegion, regionDesc)
flag.StringVar(&region, "region", defaultRegion, regionDesc)

flag.BoolVar(&listInstances, "l", false, "show list of running instances and exit")
flag.BoolVar(&listInstances, "list", false, "show list of running instances and exit")

Expand All @@ -169,11 +148,11 @@ func init() {

// Given an instance name and Id, and a reservation list, return the ec2.Instance
// that matches
func findInstance(instance *Instance, reservations []*ec2.Reservation) (*ec2.Instance, error) {
func findInstance(instance *Instance, reservations []ec2.RunInstancesOutput) (*ec2.Instance, error) {
for _, reservation := range reservations {
for _, ec2Instance := range reservation.Instances {
if *ec2Instance.InstanceId == instance.Id {
return ec2Instance, nil
return &ec2Instance, nil
}
}
}
Expand All @@ -183,7 +162,7 @@ func findInstance(instance *Instance, reservations []*ec2.Reservation) (*ec2.Ins
// Accepts the user's query and a slice of reservations that match the query.
// Shows the user the instance IDs and allows them to choose one on the command
// line, and returns a pointer to the instance that was chosen
func chooseInstance(lookup string, reservations []*ec2.Reservation) *ec2.Instance {
func chooseInstance(lookup string, reservations []ec2.RunInstancesOutput) *ec2.Instance {
var instanceList = reservationsToInstances(reservations)

fmt.Printf(`Found more than one instance for '%s'.
Expand Down Expand Up @@ -230,26 +209,18 @@ func main() {
flag.Usage = usage
flag.Parse()

debugf("using AWS profile: %s", profile)
sess, err := session.NewSessionWithOptions(session.Options{
Config: aws.Config{
Region: aws.String(region),
CredentialsChainVerboseErrors: &verboseFlag,
},
Profile: profile,
SharedConfigState: session.SharedConfigEnable,
})
cfg, err := external.LoadDefaultAWSConfig()
if err != nil {
printError(err)
}

svc := ec2.New(sess)
svc := ec2.New(cfg)

var instanceStateFilter = ec2.Filter{
Name: aws.String("instance-state-name"),
Values: []*string{
aws.String("running"),
aws.String("pending"),
Values: []string{
"running",
"pending",
},
}

Expand All @@ -259,12 +230,13 @@ func main() {
var params *ec2.DescribeInstancesInput

params = &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
&instanceStateFilter,
Filters: []ec2.Filter{
instanceStateFilter,
},
}

resp, err := svc.DescribeInstances(params)
req := svc.DescribeInstancesRequest(params)
resp, err := req.Send()
if err != nil {
printError(err)
}
Expand All @@ -280,41 +252,40 @@ func main() {
var params *ec2.DescribeInstancesInput
if ip := net.ParseIP(lookup); ip != nil {
params = &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
Filters: []ec2.Filter{
{
Name: aws.String("private-ip-address"),
Values: []*string{
aws.String(lookup),
Values: []string{
lookup,
},
},
&instanceStateFilter,
instanceStateFilter,
},
}
} else if instIdRe.MatchString(lookup) {
debugf("describing instance(s) by ID")
params = &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(lookup)},
Filters: []*ec2.Filter{
&instanceStateFilter,
InstanceIds: []string{lookup},
Filters: []ec2.Filter{
instanceStateFilter,
},
}
} else {
debugf("describing instance(s) by name")
params = &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
Filters: []ec2.Filter{
{
Name: aws.String("tag:Name"),
Values: []*string{
aws.String(lookup),
},
Name: aws.String("tag:Name"),
Values: []string{lookup},
},
&instanceStateFilter,
instanceStateFilter,
},
}
}

debugf("aws api: describing instances")
resp, err := svc.DescribeInstances(params)
req := svc.DescribeInstancesRequest(params)
resp, err := req.Send()
if err != nil {
printError(err)
}
Expand All @@ -325,7 +296,7 @@ func main() {
if len(resp.Reservations) == 0 {
printError(fmt.Errorf("Found no instance '%s'", lookup))
} else if len(resp.Reservations) == 1 {
instance = resp.Reservations[0].Instances[0]
instance = &resp.Reservations[0].Instances[0]
} else if len(resp.Reservations) > 1 {
instance = chooseInstance(lookup, resp.Reservations)
}
Expand Down

0 comments on commit 93cdc6c

Please sign in to comment.