Skip to content

Commit

Permalink
Merge pull request #228 from uselagoon/ssh-in-config
Browse files Browse the repository at this point in the history
Feat: Support for SSH key definition in configuration file
  • Loading branch information
shreddedbacon authored Jul 12, 2022
2 parents 25c7859 + c6d0afb commit cf0f15c
Show file tree
Hide file tree
Showing 11 changed files with 176 additions and 42 deletions.
42 changes: 30 additions & 12 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type LagoonConfigFlags struct {
Token string `json:"token,omitempty"`
UI string `json:"ui,omitempty"`
Kibana string `json:"kibana,omitempty"`
SSHKey string `json:"sshkey,omitempty"`
}

func parseLagoonConfig(flags pflag.FlagSet) LagoonConfigFlags {
Expand Down Expand Up @@ -107,25 +108,32 @@ var configLagoonsCmd = &cobra.Command{
returnNonEmptyString(lc.GraphQL),
returnNonEmptyString(lc.HostName),
returnNonEmptyString(lc.Port),
returnNonEmptyString(lc.UI),
returnNonEmptyString(lc.Kibana),
}
if fullConfigList {
mapData = append(mapData, returnNonEmptyString(lc.UI))
mapData = append(mapData, returnNonEmptyString(lc.Kibana))
}
mapData = append(mapData, returnNonEmptyString(lc.SSHKey))
data = append(data, mapData)
}
sort.Slice(data, func(i, j int) bool {
return data[i][0] < data[j][0]
})
tableHeader := []string{
"Name",
"Version",
"GraphQL",
"SSH-Hostname",
"SSH-Port",
}
if fullConfigList {
tableHeader = append(tableHeader, "UI-URL")
tableHeader = append(tableHeader, "Kibana-URL")
}
tableHeader = append(tableHeader, "SSH-Key")
output.RenderOutput(output.Table{
Header: []string{
"Name",
"Version",
"GraphQL",
"SSH-Hostname",
"SSH-Port",
"UI-URL",
"Kibana-URL",
},
Data: data,
Header: tableHeader,
Data: data,
}, outputOptions)
return nil
},
Expand Down Expand Up @@ -155,6 +163,9 @@ var configAddCmd = &cobra.Command{
if lagoonConfig.Token != "" {
lc.Token = lagoonConfig.Token
}
if lagoonConfig.SSHKey != "" {
lc.SSHKey = lagoonConfig.SSHKey
}
lagoonCLIConfig.Lagoons[lagoonConfig.Lagoon] = lc
if err := writeLagoonConfig(&lagoonCLIConfig, filepath.Join(configFilePath, configName+configExtension)); err != nil {
return fmt.Errorf("couldn't write config: %v", err)
Expand All @@ -167,6 +178,7 @@ var configAddCmd = &cobra.Command{
"SSH-Port",
"UI-URL",
"Kibana-URL",
"SSH-Key",
},
Data: []output.Data{
[]string{
Expand All @@ -176,6 +188,7 @@ var configAddCmd = &cobra.Command{
lagoonConfig.Port,
lagoonConfig.UI,
lagoonConfig.Kibana,
lagoonConfig.SSHKey,
},
},
}, outputOptions)
Expand Down Expand Up @@ -277,6 +290,7 @@ var configLagoonVersionCmd = &cobra.Command{

var updateCheck string
var environmentFromDirectory string
var fullConfigList bool

func init() {
configCmd.AddCommand(configAddCmd)
Expand All @@ -300,6 +314,10 @@ func init() {
"Create the config file if it is non existent (to be used with --config-file)")
configAddCmd.Flags().StringVarP(&lagoonKibana, "kibana", "k", "",
"Lagoon Kibana URL (https://logs.amazeeio.cloud)")
configAddCmd.Flags().StringVarP(&lagoonSSHKey, "ssh-key", "", "",
"SSH Key to use for this cluster for generating tokens")
configLagoonsCmd.Flags().BoolVarP(&fullConfigList, "show-full", "", false,
"Show full config output when listing Lagoon configurations")
configFeatureSwitch.Flags().StringVarP(&updateCheck, "disable-update-check", "", "",
"Enable or disable checking of updates (true/false)")
configFeatureSwitch.Flags().StringVarP(&environmentFromDirectory, "enable-local-dir-check", "", "",
Expand Down
6 changes: 6 additions & 0 deletions cmd/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ func loginToken() error {
func retrieveTokenViaSsh() (string, error) {
skipAgent := false
privateKey := fmt.Sprintf("%s/.ssh/id_rsa", userPath)
// if the user has a key defined in their lagoon cli config, use it
if lagoonCLIConfig.Lagoons[lagoonCLIConfig.Current].SSHKey != "" {
privateKey = lagoonCLIConfig.Lagoons[lagoonCLIConfig.Current].SSHKey
skipAgent = true
}
// otherwise check if one has been provided by the override flag
if cmdSSHKey != "" {
privateKey = cmdSSHKey
skipAgent = true
Expand Down
8 changes: 8 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,10 @@ func getLagoonConfigFile(configPath *string, configName *string, configExtension
if lagoonConfigEnvar, ok := os.LookupEnv("LAGOONCONFIG"); ok {
configFilePath = lagoonConfigEnvar
}
// prefer LAGOON_CONFIG_FILE
if lagoonConfigEnvar, ok := os.LookupEnv("LAGOON_CONFIG_FILE"); ok {
configFilePath = lagoonConfigEnvar
}
}
if configFilePath != "" {
if fileExists(configFilePath) || createConfig {
Expand All @@ -451,6 +455,10 @@ func getLagoonContext(lagoonCLIConfig *lagoon.Config, lagoon *string, cmd *cobra
if lagoonContextEnvar, ok := os.LookupEnv("LAGOONCONTEXT"); ok {
lagoonContext = lagoonContextEnvar
}
// prefer LAGOON_CONTEXT
if lagoonContextEnvar, ok := os.LookupEnv("LAGOON_CONTEXT"); ok {
configFilePath = lagoonContextEnvar
}
}
if lagoonContext != "" {
*lagoon = lagoonContext
Expand Down
1 change: 1 addition & 0 deletions cmd/shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ var lagoonGraphQL string
var lagoonToken string
var lagoonUI string
var lagoonKibana string
var lagoonSSHKey string

// variable vars
var variableValue string
Expand Down
36 changes: 28 additions & 8 deletions cmd/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,30 @@ var sshEnvCmd = &cobra.Command{
cmd.Help()
os.Exit(1)
}
// get private key that the cli is using
skipAgent := false

privateKey := fmt.Sprintf("%s/.ssh/id_rsa", userPath)
// if the user has a key defined in their lagoon cli config, use it
if lagoonCLIConfig.Lagoons[lagoonCLIConfig.Current].SSHKey != "" {
privateKey = lagoonCLIConfig.Lagoons[lagoonCLIConfig.Current].SSHKey
skipAgent = true
}
// otherwise check if one has been provided by the override flag
if cmdSSHKey != "" {
privateKey = cmdSSHKey
skipAgent = true
}
sshConfig := map[string]string{
"hostname": lagoonCLIConfig.Lagoons[lagoonCLIConfig.Current].HostName,
"port": lagoonCLIConfig.Lagoons[lagoonCLIConfig.Current].Port,
"username": cmdProjectName + "-" + cmdProjectEnvironment,
"sshkey": privateKey,
}
if sshConnString {
fmt.Println(lagoonssh.GenerateSSHConnectionString(sshConfig, sshService, sshContainer))
fmt.Println(generateSSHConnectionString(sshConfig, sshService, sshContainer))
} else {
// get private key that the cli is using
skipAgent := false

privateKey := fmt.Sprintf("%s/.ssh/id_rsa", userPath)
if cmdSSHKey != "" {
privateKey = cmdSSHKey
skipAgent = true
}
// start an interactive ssh session
authMethod, closeSSHAgent := publicKey(privateKey, skipAgent)
config := &ssh.ClientConfig{
Expand Down Expand Up @@ -75,3 +83,15 @@ func init() {
sshEnvCmd.Flags().BoolVarP(&sshConnString, "conn-string", "", false, "Display the full ssh connection string")
sshEnvCmd.Flags().StringVarP(&sshCommand, "command", "C", "", "Command to run on remote")
}

// generateSSHConnectionString .
func generateSSHConnectionString(lagoon map[string]string, service string, container string) string {
connString := fmt.Sprintf("ssh -t %s-o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -p %v %s@%s", lagoon["sshKey"], lagoon["port"], lagoon["username"], lagoon["hostname"])
if service != "" {
connString = fmt.Sprintf("%s service=%s", connString, service)
}
if container != "" && service != "" {
connString = fmt.Sprintf("%s container=%s", connString, container)
}
return connString
}
81 changes: 81 additions & 0 deletions cmd/ssh_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package cmd

import (
"testing"
)

func Test_generateSSHConnectionString(t *testing.T) {
type args struct {
project string
environment string
lagoon map[string]string
service string
container string
}
tests := []struct {
name string
args args
want string
}{
{
name: "test1 - no service or container",
args: args{
lagoon: map[string]string{
"hostname": "lagoon.example.com",
"port": "22",
"username": "example-com-main",
},
},
want: `ssh -t -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking=no" -p 22 [email protected]`,
},
{
name: "test1 - service only, no container",
args: args{
lagoon: map[string]string{
"hostname": "lagoon.example.com",
"port": "22",
"username": "example-com-main",
},
service: "cli",
},
want: `ssh -t -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking=no" -p 22 [email protected] service=cli`,
},
{
name: "test3 - service and container",
args: args{
lagoon: map[string]string{
"hostname": "lagoon.example.com",
"port": "22",
"username": "example-com-main",
},
service: "nginx-php",
container: "php",
},
want: `ssh -t -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking=no" -p 22 [email protected] service=nginx-php container=php`,
},
{
name: "test4",
args: args{
lagoon: map[string]string{
"hostname": "lagoon.example.com",
"port": "22",
"username": "example-com-main",
"sshKey": "/home/user/.ssh/my-key",
},
service: "cli",
container: "cli",
},
want: `ssh -t /home/user/.ssh/my-key-o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking=no" -p 22 [email protected] service=cli container=cli`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmdProjectName = tt.args.project
cmdProjectEnvironment = tt.args.environment

if got := generateSSHConnectionString(tt.args.lagoon, tt.args.service, tt.args.container); got != tt.want {
t.Errorf("generateSSHConnectionString() = %v, want %v", got, tt.want)
}
})
}
}
3 changes: 2 additions & 1 deletion docs/commands/lagoon_config_list.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ lagoon config list [flags]
### Options

```
-h, --help help for list
-h, --help help for list
--show-full Show full config output when listing Lagoon configurations
```

### Options inherited from parent commands
Expand Down
21 changes: 12 additions & 9 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,36 +1,39 @@
module github.com/uselagoon/lagoon-cli

go 1.13
go 1.16

require (
github.com/Masterminds/semver v1.4.2
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/golang/mock v1.4.0
github.com/google/go-github v0.0.0-20180716180158-c0b63e2f9bb1
github.com/google/go-querystring v1.0.0 // indirect
github.com/google/uuid v1.1.1
github.com/hashicorp/go-version v1.2.0
github.com/integralist/go-findroot v0.0.0-20160518114804-ac90681525dc
github.com/logrusorgru/aurora v0.0.0-20191017060258-dc85c304c434
github.com/machinebox/graphql v0.2.3-0.20181106130121-3a9253180225
github.com/manifoldco/promptui v0.3.2
github.com/matryer/is v1.2.0 // indirect
// workaround for https://github.com/manifoldco/promptui/issues/98
github.com/nicksnyder/go-i18n v1.10.1 // indirect
github.com/olekukonko/tablewriter v0.0.4
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4
github.com/pkg/errors v0.8.0 // indirect
github.com/spf13/cobra v0.0.5
github.com/spf13/pflag v1.0.3
github.com/stretchr/testify v1.2.2
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 // indirect
gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20191105091915-95d230a53780 // indirect
gopkg.in/yaml.v2 v2.2.8
sigs.k8s.io/yaml v1.2.0
)

require (
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf // indirect
github.com/google/go-querystring v1.0.0 // indirect
github.com/matryer/is v1.2.0 // indirect
// workaround for https://github.com/manifoldco/promptui/issues/98
github.com/nicksnyder/go-i18n v1.10.1 // indirect
github.com/pkg/errors v0.8.0 // indirect
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 // indirect
gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20191105091915-95d230a53780 // indirect
)

// use this version for fixes to formatting of end header
replace github.com/olekukonko/tablewriter => github.com/shreddedbacon/tablewriter v0.0.2-0.20200114082015-d810c4a558bf

Expand Down
7 changes: 7 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Masterminds/semver v1.4.2 h1:WBLTQ37jOCzSLtXNdoo8bNM8876KhNqOKvrlGITgsTc=
github.com/Masterminds/semver v1.4.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
Expand All @@ -6,9 +7,11 @@ github.com/alecthomas/gometalinter v2.0.11+incompatible/go.mod h1:qfIpQGGz3d+Nmg
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf h1:qet1QNfXsQxTZqLG4oE62mJzwPIB8+Tee4RNCL9ulrY=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
Expand Down Expand Up @@ -45,8 +48,10 @@ github.com/integralist/go-findroot v0.0.0-20160518114804-ac90681525dc h1:4IZpk3M
github.com/integralist/go-findroot v0.0.0-20160518114804-ac90681525dc/go.mod h1:UlaC6ndby46IJz9m/03cZPKKkR9ykeIVBBDE3UDBdJk=
github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a h1:FaWFmfWdAUKbSCtOU2QjDaorUexogfaMgbipgYATUMU=
github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/logrusorgru/aurora v0.0.0-20191017060258-dc85c304c434 h1:im9kkmH0WWwxzegiv18gSUJbuXR9y028rXrWuPp6Jug=
github.com/logrusorgru/aurora v0.0.0-20191017060258-dc85c304c434/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4=
Expand All @@ -57,6 +62,7 @@ github.com/machinebox/graphql v0.2.3-0.20181106130121-3a9253180225/go.mod h1:F+k
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/manifoldco/promptui v0.3.2 h1:rir7oByTERac6jhpHUPErHuopoRDvO3jxS+FdadEns8=
github.com/manifoldco/promptui v0.3.2/go.mod h1:8JU+igZ+eeiiRku4T5BjtKh2ms8sziGpSYl1gN8Bazw=
github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A=
github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA=
github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
Expand Down Expand Up @@ -118,6 +124,7 @@ golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBn
gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20191105091915-95d230a53780 h1:CEBpW6C191eozfEuWdUmIAHn7lwlLxJ7HVdr2e2Tsrw=
gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20191105091915-95d230a53780/go.mod h1:3HH7i1SgMqlzxCcBmUHW657sD4Kvv9sC3HpL3YukzwA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
Expand Down
1 change: 1 addition & 0 deletions internal/lagoon/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ type Context struct {
Port string `json:"port"`
Token string `json:"token,omitempty"`
Version string `json:"version,omitempty"`
SSHKey string `json:"sshkey,omitempty"`
}
Loading

0 comments on commit cf0f15c

Please sign in to comment.