Skip to content

Commit

Permalink
🌈
Browse files Browse the repository at this point in the history
  • Loading branch information
aidansteele committed Aug 24, 2017
1 parent 54c83b0 commit 1893031
Show file tree
Hide file tree
Showing 6 changed files with 198 additions and 53 deletions.
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ script: ls

after_success:
- gox -arch="amd64" -os="windows linux darwin"
- ls
- upx-3.93-amd64_linux/upx gossm_{windows_amd64.exe,linux_amd64}

deploy:
Expand All @@ -31,4 +32,4 @@ deploy:
- gossm_windows_amd64.exe
on:
tags: true
repo: aidansteele/gossm
repo: glassechidna/gossm
25 changes: 0 additions & 25 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -175,28 +175,3 @@
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
63 changes: 59 additions & 4 deletions glide.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions glide.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,9 @@ import:
- package: github.com/spf13/viper
- package: github.com/aws/aws-sdk-go
version: ^1.10.14
- package: github.com/mitchellh/go-wordwrap
- package: github.com/fatih/color
version: ^1.5.0
- package: github.com/nsf/termbox-go
- package: github.com/mattn/go-runewidth # needed by termbox-go
version: ^0.0.2
46 changes: 36 additions & 10 deletions root.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,53 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
"strings"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/aws-sdk-go/aws"
)

var cfgFile string

var RootCmd = &cobra.Command{
Use: "gossm",
Short: "Run commands on remote machines using EC2 SSM Run Command",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
region, _ := cmd.PersistentFlags().GetString("region")
profile, _ := cmd.PersistentFlags().GetString("profile")
sess := AwsSession(profile, region)

instance, _ := cmd.PersistentFlags().GetString("instance-id")
bucket, _ := cmd.PersistentFlags().GetString("s3-bucket")
keyPrefix, _ := cmd.PersistentFlags().GetString("s3-key-prefix")
instanceIds, _ := cmd.PersistentFlags().GetStringSlice("instance-id")
tagPairs, _ := cmd.PersistentFlags().GetStringSlice("tag")

targets := []*ssm.Target{}

for _, pair := range tagPairs {
splitted := strings.SplitN(pair, "=", 2)

tag := splitted[0]
val := splitted[1]
key := fmt.Sprintf("tag:%s", tag)

target := &ssm.Target{
Key: &key,
Values: []*string{&val},
}
targets = append(targets, target)
}

if len(instanceIds) > 0 {
target := &ssm.Target{
Key: aws.String("InstanceIds"),
Values: aws.StringSlice(instanceIds),
}
targets = append(targets, target)
}

timeout, _ := cmd.PersistentFlags().GetInt64("timeout")
command := strings.Join(args, " ")

doit(sess, instance, command, timeout)
doit(sess, targets, bucket, keyPrefix, command, timeout)
},
}

Expand All @@ -44,11 +68,13 @@ func init() {
cobra.OnInitialize(initConfig)

RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.gossm.yaml)")
RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

RootCmd.PersistentFlags().String("profile", "", "")
RootCmd.PersistentFlags().String("region", "", "")
RootCmd.PersistentFlags().String("instance-id", "", "")
RootCmd.PersistentFlags().String("s3-bucket", "", "")
RootCmd.PersistentFlags().String("s3-key-prefix", "", "")
RootCmd.PersistentFlags().StringSlice("instance-ids", []string{}, "")
RootCmd.PersistentFlags().StringSliceP("tag", "t", []string{}, "")
RootCmd.PersistentFlags().Int64("timeout", 600, "")
}

Expand Down
108 changes: 95 additions & 13 deletions run.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@ import (
"github.com/aws/aws-sdk-go/service/ssm"
"log"
"time"
"os"
"net/url"
"github.com/aws/aws-sdk-go/service/s3"
"strings"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"fmt"
"github.com/mitchellh/go-wordwrap"
"github.com/fatih/color"
"github.com/nsf/termbox-go"
)

func AwsSession(profile, region string) *session.Session {
Expand All @@ -31,12 +38,69 @@ func AwsSession(profile, region string) *session.Session {
return sess
}

func doit(sess *session.Session, instanceId, command string, timeout int64) {
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}

func getFromS3Url(sess *session.Session, urlString string) (*string, error) {
s3url, err := url.Parse(urlString)
if err != nil { return nil, err }

urlPath := s3url.Path
parts := strings.SplitN(urlPath, "/", 3)
bucket := parts[1]
key := parts[2]

buff := &aws.WriteAtBuffer{}
s3dl := s3manager.NewDownloader(sess)

_, err = s3dl.Download(buff, &s3.GetObjectInput{
Bucket: &bucket,
Key: &key,
})
if err != nil { return nil, err }

str := string(buff.Bytes())
return &str, nil
}

func printFormattedOutput(prefix, output string) {
if err := termbox.Init(); err != nil { panic(err) }
windowWidth, _ := termbox.Size()
termbox.Close()

outputWidth := windowWidth - len(prefix)
wrapped := wordwrap.WrapString(output, uint(outputWidth))
lines := strings.Split(wrapped, "\n")

for _, line := range(lines) {
fmt.Print(prefix)
fmt.Println(line)
}
}

var stdoutColours = []*color.Color{
color.New(color.FgGreen),
color.New(color.FgHiGreen),
}
var stderrColours = []*color.Color{
color.New(color.FgRed),
color.New(color.FgHiRed),
}

func doit(sess *session.Session, targets []*ssm.Target, bucket, keyPrefix, command string, timeout int64) {
client := ssm.New(sess)
resp, err := client.SendCommand(&ssm.SendCommandInput{
DocumentName: aws.String("AWS-RunShellScript"),
InstanceIds: aws.StringSlice([]string{instanceId}),
Targets: targets,
TimeoutSeconds: &timeout,
OutputS3BucketName: &bucket,
OutputS3KeyPrefix: &keyPrefix,
Parameters: map[string][]*string {
"commands": aws.StringSlice([]string{command}),
},
Expand All @@ -47,30 +111,48 @@ func doit(sess *session.Session, instanceId, command string, timeout int64) {
}

commandId := resp.Command.CommandId
status := "InProgress"
printedInstanceIds := []string{}

cmdResp := ssm.GetCommandInvocationOutput{}

for {
time.Sleep(time.Second * 3)

resp2, err := client.GetCommandInvocation(&ssm.GetCommandInvocationInput{
resp3, err := client.ListCommandInvocations(&ssm.ListCommandInvocationsInput{
CommandId: commandId,
InstanceId: &instanceId,
})

if err != nil {
log.Panicf(err.Error())
}

status = *resp2.Status
for _, invocation := range resp3.CommandInvocations {
instanceId := *invocation.InstanceId
if stringInSlice(instanceId, printedInstanceIds) {
continue
}

if *invocation.Status != "InProgress" {
colourIdx := len(printedInstanceIds) % 2
prefix := fmt.Sprintf("[%d/%d %s] ", len(printedInstanceIds) + 1, len(resp3.CommandInvocations), instanceId)

stdout, _ := getFromS3Url(sess, *invocation.StandardOutputUrl)
if stdout != nil {
colour := stdoutColours[colourIdx]
printFormattedOutput(colour.Sprint(prefix), *stdout)
}

stderr, _ := getFromS3Url(sess, *invocation.StandardErrorUrl)
if stderr != nil {
colour := stderrColours[colourIdx]
printFormattedOutput(colour.Sprint(prefix), *stderr)
}

printedInstanceIds = append(printedInstanceIds, instanceId)
}
}

if status != "InProgress" {
cmdResp = *resp2
if len(printedInstanceIds) == len(resp3.CommandInvocations) {
break
}
}

os.Stderr.WriteString(*cmdResp.StandardErrorContent)
os.Stdout.WriteString(*cmdResp.StandardOutputContent)
}

0 comments on commit 1893031

Please sign in to comment.