-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
1121 lines (941 loc) · 25.7 KB
/
main.go
File metadata and controls
1121 lines (941 loc) · 25.7 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/gob"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/codegangsta/cli"
"github.com/inconshreveable/go-update"
"github.com/kardianos/osext"
"github.com/olekukonko/tablewriter"
"github.com/toumorokoshi/go-fuzzy/fuzzy"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"os/user"
"path"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
var releasesAPI string = "https://api.github.com/repos/markwallsgrove/ssh_alias_ec2/releases"
var version string = "0.5.2"
var baseDir string
var homeDir string
var currentUsername string
func init() {
currentUser, err := user.Current()
if err != nil {
panic(err)
}
currentUsername = currentUser.Username
homeDir = currentUser.HomeDir
baseDir = fmt.Sprintf("%s/.ec2.cli", currentUser.HomeDir)
}
var bashrcCall = []byte(`
if [ -f ~/.ec2.cli/completion.bash ]; then
export PATH="$PATH:$HOME/.ec2.cli"
. ~/.ec2.cli/completion.bash
fi
`)
var bashAutoComplete = []byte(`#! /bin/bash
_cli_bash_autocomplete() {
local cur opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _cli_bash_autocomplete ec2.cli
`)
var zshAutoComplete = []byte(`
autoload -U compinit && compinit
autoload -U bashcompinit && bashcompinit
export PATH="$PATH:$HOME/.ec2.cli"
if [ -f ~/.ec2.cli/completion.bash ]; then
source ~/.ec2.cli/completion.bash
fi
`)
var publicKey = []byte(`
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvbKUOY+q3YFsJXCbPeT5VsVj69+K
lc/qbJVx/ZsbbPOTiMoWdQ7vENoMcqPgB7O6ouHoLo1FlOazHEnQVcFXoA==
-----END PUBLIC KEY-----
`)
var regexWhiteChars = regexp.MustCompile("[^a-zA-Z0-9]")
var forwardAssetFilePattern = regexp.MustCompile(fmt.Sprintf(
"/f-%s-%s\\.(hash|sig|diff)$", runtime.GOOS, runtime.GOARCH,
))
var backwardsAssetFilePattern = regexp.MustCompile(fmt.Sprintf(
"/b-%s-%s\\.(hash|sig|diff)$", runtime.GOOS, runtime.GOARCH,
))
func downloadFile(uri string, loc string, errChannel chan error) {
output, err := os.Create(loc)
if err != nil {
errChannel <- err
return
}
defer output.Close()
response, err := http.Get(uri)
if err != nil {
errChannel <- err
return
}
defer response.Body.Close()
_, err = io.Copy(output, response.Body)
if err != nil {
errChannel <- err
return
}
errChannel <- errors.New("")
}
type Release struct {
Version string `json:"tag_name"`
Body string `json:"body"`
Assets []Asset `json:"assets"`
}
func (release *Release) DownloadAssets(pattern regexp.Regexp, location string) error {
if len(release.Assets) == 0 {
return errors.New("Release contains zero assets")
}
downloading := 0
errChannel := make(chan error)
for _, asset := range release.Assets {
if pattern.MatchString(asset.DownloadUrl) == false {
continue
}
fmt.Println("Downloading", asset.DownloadUrl, "to", path.Join(location, asset.Name))
go downloadFile(asset.DownloadUrl, path.Join(location, asset.Name), errChannel)
downloading += 1
}
var err error
for i := 0; i < downloading; i++ {
err = <-errChannel
if err.Error() != "" {
break
}
}
close(errChannel)
if err.Error() != "" {
return err
}
return nil
}
type Asset struct {
Name string `json:"name"`
DownloadUrl string `json:"browser_download_url"`
}
type Instance struct {
Name string
Addr string
Id string
PublicDnsName string
InstanceType string
CertName string
Tags []string
}
type Profile struct {
Name string `json:"-"`
Region string `json:"region,omitempty"`
User string `json:"user,omitempty"`
CertLocation string `json:"certLocation,omitempty"`
MaxCacheAge int `json:"maxCacheAge,omitempty"`
AliasPrefix string `json:"aliasPrefix,omitempty"`
AWSProfile string `json:"awsProfile,omitempty"`
AWSAccessKey string `json:"awsAccessKey,omitempty"`
AWSSecretKey string `json:"awsSecretKey,omitempty"`
}
func loadProfileFromFile(location string) (error, Profile) {
if _, err := os.Stat(location); os.IsNotExist(err) {
return nil, Profile{}
}
profileBytes, err := ioutil.ReadFile(location)
if err != nil {
return err, Profile{}
}
var profile Profile
err = json.Unmarshal(profileBytes, &profile)
if err != nil {
return err, Profile{}
}
return nil, profile
}
func trimSurroundingQuotes(str string) string {
if str == "" {
return str
}
lastChar := len(str) - 1
if str[0] == '\'' && str[lastChar] == '\'' || str[0] == '"' && str[lastChar] == '"' {
str = str[1:lastChar]
}
return str
}
func loadProfile(context *cli.Context, useEnvValues bool) (error, Profile) {
location := fmt.Sprintf("%s/config/%s.json", baseDir, context.GlobalString("profile"))
err, profile := loadProfileFromFile(location)
if err != nil {
return err, profile
}
profile.Name = trimSurroundingQuotes(context.GlobalString("profile"))
if useEnvValues == false {
return nil, profile
}
if region := trimSurroundingQuotes(context.GlobalString("region")); region != "" {
profile.Region = region
} else if profile.Region == "" {
profile.Region = "eu-west-1"
}
if user := trimSurroundingQuotes(context.GlobalString("user")); user != "" {
profile.User = user
} else if profile.User == "" {
profile.User = currentUsername
}
if cert := trimSurroundingQuotes(context.GlobalString("cert")); cert != "" {
profile.CertLocation = cert
}
if maxCacheAge := context.GlobalInt("maxCacheAge"); maxCacheAge != -1 {
profile.MaxCacheAge = maxCacheAge
} else if profile.MaxCacheAge == 0 {
profile.MaxCacheAge = 300
}
if prefix := trimSurroundingQuotes(context.String("prefix")); prefix != "" {
profile.AliasPrefix = prefix
}
if awsProfile := trimSurroundingQuotes(context.GlobalString("awsProfile")); awsProfile != "" {
profile.AWSProfile = awsProfile
}
if awsAccessKey := trimSurroundingQuotes(context.GlobalString("awsAccessKey")); awsAccessKey != "" {
profile.AWSAccessKey = awsAccessKey
}
if awsSecretKey := trimSurroundingQuotes(context.GlobalString("awsSecretKey")); awsSecretKey != "" {
profile.AWSSecretKey = awsSecretKey
}
return nil, profile
}
func (profile *Profile) save() error {
if profile.Name == "" {
return errors.New("Profile name is not set")
}
if err := os.MkdirAll(fmt.Sprintf("%s/config", baseDir), 0770); err != nil {
return err
}
configLoc := fmt.Sprintf("%s/config/%s.json", baseDir, profile.Name)
configBytes, err := json.MarshalIndent(profile, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(configLoc, configBytes, 0775)
}
func (i *Instance) getNormalisedName() string {
return fmt.Sprintf("%s_%s", regexWhiteChars.ReplaceAllString(i.Name, "_"), i.Id)
}
func exit(msg string) {
fmt.Fprint(os.Stderr, msg)
os.Exit(1)
}
func getInstanceCache(region string, profile string, maxAge int) map[string]*Instance {
cacheLocation := fmt.Sprintf("%s/cache/%s_%s.cache", baseDir, profile, region)
if info, err := os.Stat(cacheLocation); err != nil {
return nil
} else if maxAge == 0 {
os.Remove(cacheLocation)
return nil
} else if int(time.Since(info.ModTime()).Seconds()) > maxAge {
return nil
}
contents, err := ioutil.ReadFile(cacheLocation)
if err != nil {
return nil
}
buffer := bytes.Buffer{}
buffer.Write(contents)
cache := map[string]*Instance{}
d := gob.NewDecoder(&buffer)
err = d.Decode(&cache)
if err != nil {
return nil
}
return cache
}
func storeInstanceCache(region string, profile string, cache map[string]*Instance) error {
if err := os.MkdirAll(fmt.Sprintf("%s/cache", baseDir), 0770); err != nil {
return err
}
cacheLocation := fmt.Sprintf("%s/cache/%s_%s.cache", baseDir, profile, region)
buffer := bytes.Buffer{}
encoder := gob.NewEncoder(&buffer)
err := encoder.Encode(cache)
if err != nil {
return err
}
err = ioutil.WriteFile(cacheLocation, buffer.Bytes(), 0770)
if err != nil {
return err
}
return nil
}
func getInstances(region string, maxCacheAge int, profile Profile) (error, map[string]*Instance) {
instances := getInstanceCache(region, profile.Name, maxCacheAge)
if instances != nil {
return nil, instances
}
var creds *credentials.Credentials
if profile.AWSAccessKey != "" && profile.AWSSecretKey != "" {
creds = credentials.NewStaticCredentials(
profile.AWSAccessKey,
profile.AWSSecretKey,
"",
)
} else if profile.AWSProfile != "" {
creds = credentials.NewSharedCredentials(
fmt.Sprintf("%s/.aws/credentials", homeDir),
profile.AWSProfile,
)
} else {
creds = credentials.NewEnvCredentials()
}
config := aws.Config{Credentials: creds}
if region != "" {
config.Region = aws.String(region)
}
svc := ec2.New(session.New(), &config)
resp, err := svc.DescribeInstances(nil)
if err != nil {
return err, nil
}
instances = make(map[string]*Instance)
for _, res := range resp.Reservations {
for _, inst := range res.Instances {
instance := new(Instance)
instance.Tags = make([]string, len(inst.Tags))
for index, keys := range inst.Tags {
instance.Tags[index] = *keys.Value
if *keys.Key == "Name" {
instance.Name = *keys.Value
instance.Id = *inst.InstanceId
}
}
instance.PublicDnsName = *inst.PublicDnsName
instance.InstanceType = *inst.InstanceType
instance.CertName = *inst.KeyName
if inst.PublicIpAddress != nil {
instance.Addr = *inst.PublicIpAddress
} else if inst.PrivateIpAddress != nil {
instance.Addr = *inst.PrivateIpAddress
}
if instance.Name != "" && instance.Addr != "" {
instances[instance.getNormalisedName()] = instance
}
}
}
if err = storeInstanceCache(region, profile.Name, instances); err != nil {
return err, nil
}
return nil, instances
}
func main() {
app := cli.NewApp()
app.Name = "ec2.cli"
app.Usage = "quickly gain access to EC2 machines"
app.EnableBashCompletion = true
app.Version = version
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "region",
EnvVar: "AE_AWS_DEFAULT_REGION",
Usage: "AWS region",
},
cli.StringFlag{
Name: "user",
Usage: "SSH username",
EnvVar: "AE_SSH_USER",
},
cli.StringFlag{
Name: "cert",
Usage: "Certificate that will be used with ssh",
EnvVar: "AE_SSH_CERTIFICATE",
},
cli.IntFlag{
Name: "maxCacheAge",
Value: -1,
Usage: "Maximum cache age in seconds",
EnvVar: "AE_MAX_CACHE_AGE",
},
cli.BoolFlag{
Name: "flushCache",
Usage: "Flush the cache",
},
cli.StringFlag{
Name: "profile",
Value: "default",
Usage: "Profile to use",
EnvVar: "AE_DEFAULT_PROFILE",
},
cli.StringFlag{
Name: "awsProfile",
Usage: "Use a certain AWS Profile when communicating with AWS. " +
"This will be used if awsAccessKey and/or awsSecretKey are not defined",
},
cli.StringFlag{
Name: "awsAccessKey",
Usage: "AWS Access Key to use when communicating with AWS. If awsAccessKey " +
"and awsSecretKey are defined, they override awsProfile",
},
cli.StringFlag{
Name: "awsSecretKey",
Usage: "AWS Secret Key to use when communicating with AWS. If awsAccessKey" +
"and awsSecretKey are defined, they ovveride awsProfile",
},
}
app.Commands = []cli.Command{
{
Name: "set",
Usage: "Set a property or view all values of a profile (provide no key/value)",
Action: actionViewConfig,
Subcommands: []cli.Command{
{
Name: "awsSecretKey",
Usage: "Set the AWS Secret Key to use within this profile",
Action: func(context *cli.Context) {
err, profile := loadProfile(context, false)
if err != nil {
panic(err)
}
if len(context.Args()) != 1 {
exit("Invalid amount of arguments. Expected awsProfile.")
}
profile.AWSSecretKey = trimSurroundingQuotes(context.Args().First())
if err = profile.save(); err != nil {
panic(err)
}
},
},
{
Name: "awsAccessKey",
Usage: "Set the AWS Access Key to use within this profile",
Action: func(context *cli.Context) {
err, profile := loadProfile(context, false)
if err != nil {
panic(err)
}
if len(context.Args()) != 1 {
exit("Invalid amount of arguments. Expected awsProfile.")
}
profile.AWSAccessKey = trimSurroundingQuotes(context.Args().First())
if err = profile.save(); err != nil {
panic(err)
}
},
},
{
Name: "awsProfile",
Usage: "AWS profile to use",
Action: func(context *cli.Context) {
err, profile := loadProfile(context, false)
if err != nil {
panic(err)
}
if len(context.Args()) != 1 {
exit("Invalid amount of arguments. Expected awsProfile.")
}
profile.AWSProfile = trimSurroundingQuotes(context.Args().First())
if err = profile.save(); err != nil {
panic(err)
}
},
},
{
Name: "envvars",
Usage: "Special command to save the environment variables into the configuration file",
Action: func(context *cli.Context) {
err, profile := loadProfile(context, true)
if err != nil {
panic(err)
}
if err = profile.save(); err != nil {
panic(err)
}
},
},
{
Name: "region",
Usage: "Set AWS region to connect to",
Action: func(context *cli.Context) {
err, profile := loadProfile(context, false)
if err != nil {
panic(err)
}
if len(context.Args()) != 1 {
exit("Invalid amount of arguments. Expected region.")
}
profile.Region = trimSurroundingQuotes(context.Args().First())
if err = profile.save(); err != nil {
panic(err)
}
},
},
{
Name: "user",
Usage: "Set the SSH username to connect to the machine with",
Action: func(context *cli.Context) {
err, profile := loadProfile(context, false)
if err != nil {
panic(err)
}
if len(context.Args()) != 1 {
exit("Invalid amount of arguments. Expected user.")
}
profile.User = trimSurroundingQuotes(context.Args().First())
if err = profile.save(); err != nil {
panic(err)
}
},
},
{
Name: "cert",
Usage: "Location of the certificate to use when connecting to a machine",
Action: func(context *cli.Context) {
err, profile := loadProfile(context, false)
if err != nil {
panic(err)
}
if len(context.Args()) != 1 {
exit("Invalid amount of arguments. Expected certicate location.")
}
profile.CertLocation = trimSurroundingQuotes(context.Args().First())
if _, err := os.Stat(profile.CertLocation); os.IsNotExist(err) {
exit("Cannot find file")
}
if err = profile.save(); err != nil {
panic(err)
}
},
},
{
Name: "maxCacheAge",
Usage: "Maximum age in seconds to cache a AWS API call",
Action: func(context *cli.Context) {
err, profile := loadProfile(context, false)
if err != nil {
panic(err)
}
if len(context.Args()) != 1 {
exit("Invalid amount of arguments. Expected maximum cache age.")
}
maxCacheAge, err := strconv.Atoi(trimSurroundingQuotes(context.Args().First()))
if err != nil {
exit("First argument must be a integer")
}
profile.MaxCacheAge = maxCacheAge
if err = profile.save(); err != nil {
panic(err)
}
},
},
{
Name: "prefix",
Usage: "Prefix to append to the alias name when generating aliases",
Action: func(context *cli.Context) {
err, profile := loadProfile(context, false)
if err != nil {
panic(err)
}
if len(context.Args()) != 1 {
exit("Invalid amount of arguments. Expected SSH alias prefix.")
}
profile.AliasPrefix = trimSurroundingQuotes(context.Args().First())
if err = profile.save(); err != nil {
panic(err)
}
},
},
},
},
{
Name: "update",
Usage: "Update to a later version",
Action: actionUpdate,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "downgrade",
Usage: "Downgrade to a earlier version",
},
},
},
{
Name: "setup",
Usage: "Setup auto complete",
Action: actionSetup,
},
{
Name: "alias",
Usage: "generate aliases for all ec2 instances",
Flags: []cli.Flag{
cli.StringFlag{
Name: "prefix",
Usage: "Prefix for the alias name",
EnvVar: "AE_SSH_ALIAS_PREFIX",
},
},
Action: actionAlias,
},
{
Name: "status",
Usage: "display the status of all ec2 instances",
Action: actionStatus,
},
{
Name: "ssh",
Usage: "ssh to a given machine",
Action: actionSSH,
Flags: []cli.Flag{
cli.StringFlag{
Name: "tag",
Usage: "fuzzy find against a machine's tags",
},
},
BashComplete: func(c *cli.Context) {
if len(c.Args()) > 0 {
return
}
err, profile := loadProfile(c, true)
if err != nil {
panic(err)
}
maxCacheAge := profile.MaxCacheAge
if c.GlobalBool("flushCache") == true {
maxCacheAge = 0
}
err, instances := getInstances(profile.Region, maxCacheAge, profile)
if err != nil {
panic(err)
}
fuzzyTag := c.String("tag")
for name := range instances {
if fuzzyTag == "" || fuzzy.SequenceMatch(fuzzyTag, name) {
fmt.Println(name)
}
}
},
},
}
app.Run(os.Args)
}
func actionViewConfig(c *cli.Context) {
err, profile := loadProfile(c, true)
if err != nil {
panic(err)
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Key", "Value"})
table.Append([]string{"Name", profile.Name})
table.Append([]string{"Region", profile.Region})
table.Append([]string{"User", profile.User})
table.Append([]string{"Cert", profile.CertLocation})
table.Append([]string{"MaxCacheAge", fmt.Sprintf("%d", profile.MaxCacheAge)})
table.Append([]string{"Alias", profile.AliasPrefix})
table.Append([]string{"AWSProfile", profile.AWSProfile})
table.Append([]string{"AWSAccessKey", profile.AWSSecretKey})
table.Append([]string{"AWSSecretKey", profile.AWSAccessKey})
table.Render()
}
func writeConfig(loc string, content []byte) error {
if _, err := os.Stat(loc); os.IsNotExist(err) {
ioutil.WriteFile(loc, content, 0770)
fmt.Println(fmt.Sprintf("created %s", loc))
return nil
}
config, err := os.OpenFile(loc, os.O_APPEND|os.O_WRONLY, 0770)
if err != nil {
return err
}
defer config.Close()
if _, err = config.Write(content); err != nil {
return err
}
if err = os.Chmod(loc, 0770); err != nil {
return err
}
fmt.Println(fmt.Sprintf("appended to %s", loc))
return nil
}
func cp(src, dst string) error {
s, err := os.Open(src)
if err != nil {
return err
}
defer s.Close()
d, err := os.Create(dst)
if err != nil {
return err
}
if _, err := io.Copy(d, s); err != nil {
d.Close()
return err
}
return d.Close()
}
func actionSetup(c *cli.Context) {
aeCompletionLoc := fmt.Sprintf("%s/completion.bash", baseDir)
aeExecLoc := fmt.Sprintf("%s/ec2.cli", baseDir)
bashrcLoc := fmt.Sprintf("%s/.bashrc", homeDir)
bashProfileLoc := fmt.Sprintf("%s/.bash_profile", homeDir)
zshrcLoc := fmt.Sprintf("%s/.zshrc", homeDir)
if err := os.Mkdir(baseDir, 0775); os.IsExist(err) {
exit(fmt.Sprintf("ec2.cli is already installed, remove %s and try again", baseDir))
} else if err != nil {
panic(err)
} else {
fmt.Println(fmt.Sprintf("created %s", baseDir))
}
currExecLoc, _ := osext.Executable()
if err := cp(currExecLoc, aeExecLoc); err != nil {
panic(err)
}
if err := os.Chmod(aeExecLoc, 0775); err != nil {
panic(err)
}
if err := ioutil.WriteFile(aeCompletionLoc, bashAutoComplete, 0775); err != nil {
panic(err)
}
if _, err := os.Stat(bashProfileLoc); err == nil {
if err := writeConfig(bashProfileLoc, bashrcCall); err != nil {
panic(err)
}
} else if err := writeConfig(bashrcLoc, bashrcCall); err != nil {
panic(err)
}
if _, err := os.Stat(zshrcLoc); err == nil {
if err = writeConfig(zshrcLoc, zshAutoComplete); err != nil {
panic(err)
}
}
}
func actionSSH(c *cli.Context) {
if len(c.Args()) != 1 {
exit("ssh <instance-name>")
}
err, profile := loadProfile(c, true)
if err != nil {
panic(err)
}
maxCacheAge := profile.MaxCacheAge
if c.GlobalBool("flushCache") == true {
maxCacheAge = 0
}
err, instances := getInstances(profile.Region, maxCacheAge, profile)
var host string
if instance, ok := instances[trimSurroundingQuotes(c.Args().First())]; ok {
host = instance.Addr
} else {
exit(fmt.Sprintf("Unknown instance: %s\n%+v", c.Args().First(), instances))
}
var cmd *exec.Cmd
if profile.CertLocation != "" {
cmd = exec.Command(
"ssh", "-i", profile.CertLocation,
fmt.Sprintf("%s@%s", profile.User, host),
)
} else {
cmd = exec.Command(
"ssh", fmt.Sprintf("%s@%s", profile.User, host),
)
}
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
err = cmd.Start()
if err != nil {
panic(err)
}
err = cmd.Wait()
if err != nil {
exit(err.Error())
}
}
func actionStatus(c *cli.Context) {
err, profile := loadProfile(c, true)
if err != nil {
panic(err)
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Id", "Name", "Cert", "Type", "URL"})
maxCacheAge := profile.MaxCacheAge
if c.GlobalBool("flushCache") == true {
maxCacheAge = 0
}
err, instances := getInstances(profile.Region, maxCacheAge, profile)
if err != nil {
panic(err)
}
for _, instance := range instances {
table.Append([]string{
instance.Id, instance.Name,
instance.CertName, instance.InstanceType,
instance.PublicDnsName,
})
}
table.Render()
}
func actionAlias(c *cli.Context) {
err, profile := loadProfile(c, true)
if err != nil {
panic(err)
}
sshCertificateLocation := ""
if profile.CertLocation != "" {
if _, err := os.Stat(profile.CertLocation); err != nil {
exit("Cannot find certificate")
}
sshCertificateLocation = fmt.Sprintf(" -i %s", profile.CertLocation)
}
maxCacheAge := profile.MaxCacheAge
if c.GlobalBool("flushCache") == true {
maxCacheAge = 0
}
err, instances := getInstances(profile.Region, maxCacheAge, profile)
if err != nil {
panic(err)
}
for _, instance := range instances {
name := fmt.Sprintf("%s_%s", instance.Name, instance.Id)
name = regexWhiteChars.ReplaceAllString(name, "_")
fmt.Println(fmt.Sprintf(
"alias %s%s=\"ssh%s %s@%s\"", profile.AliasPrefix, strings.ToLower(name),
sshCertificateLocation, profile.User, instance.Addr,
))
}
}
func getReleases() ([]Release, error) {
res, err := http.Get(releasesAPI)
if err != nil {
return []Release{}, err
}
defer res.Body.Close()
var releases []Release
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&releases)
if err != nil {
return []Release{}, err
}
return releases, nil
}
func getNextRelease(releases []Release, version string, downgrade bool) (Release, bool, bool) {
for index, release := range releases {
if release.Version == version {
earliestRelease := index+1 == len(releases)
if index == 0 {
return releases[0], true, earliestRelease
} else if downgrade {
return releases[index], false, earliestRelease
} else {
return releases[index-1], false, earliestRelease
}