Skip to content

Commit

Permalink
Merge pull request #171 from olegmlsn/no_default_key
Browse files Browse the repository at this point in the history
Do not select the default key with --ssh=agent
  • Loading branch information
umputun committed Feb 13, 2024
2 parents 60179fb + 2a8cb20 commit 31e622d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
8 changes: 5 additions & 3 deletions cmd/spot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ func makePlaybook(opts options, inventory string) (*config.PlayBook, error) {
}

func makeRunner(opts options, pbook *config.PlayBook) (*runner.Process, error) {
sshKey, err := sshKey(opts.SSHKey, pbook)
sshKey, err := sshKey(opts.SSHAgent, opts.SSHKey, pbook)
if err != nil {
return nil, fmt.Errorf("can't get ssh key: %w", err)
}
Expand Down Expand Up @@ -381,7 +381,7 @@ func targetsForTask(targets []string, taskName string, pbook runner.Playbook) []
}

// get ssh key from cli or playbook. if no key is provided, use default ~/.ssh/id_rsa
func sshKey(sshKey string, pbook *config.PlayBook) (key string, err error) {
func sshKey(sshAgent bool, sshKey string, pbook *config.PlayBook) (key string, err error) {
if sshKey == "" && (pbook == nil || pbook.SSHKey != "") { // no key provided in cli
sshKey = pbook.SSHKey // use playbook's ssh_key
}
Expand All @@ -394,7 +394,9 @@ func sshKey(sshKey string, pbook *config.PlayBook) (key string, err error) {
if err != nil {
return "", fmt.Errorf("can't get current user: %w", err)
}
sshKey = filepath.Join(u.HomeDir, ".ssh", "id_rsa")
if !sshAgent {
sshKey = filepath.Join(u.HomeDir, ".ssh", "id_rsa")
}
}

log.Printf("[INFO] ssh key: %s", sshKey)
Expand Down
17 changes: 16 additions & 1 deletion cmd/spot/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,21 @@ func Test_sshUserAndKey(t *testing.T) {
expectedUser: osUser.Username,
expectedKey: filepath.Join(osUser.HomeDir, ".ssh", "id_rsa"),
},
{
name: "SSHAgent set no key in playbook and command line",
opts: options{
TaskNames: []string{"test_task"},
SSHUser: "cmd_user",
SSHAgent: true,
},
conf: config.PlayBook{
Tasks: []config.Task{
{Name: "test_task"},
},
},
expectedUser: "cmd_user",
expectedKey: "",
},
{
name: "tilde expansion in key path",
opts: options{
Expand All @@ -441,7 +456,7 @@ func Test_sshUserAndKey(t *testing.T) {

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
key, err := sshKey(tc.opts.SSHKey, &tc.conf)
key, err := sshKey(tc.opts.SSHAgent, tc.opts.SSHKey, &tc.conf)
require.NoError(t, err, "sshKey should not return an error")
assert.Equal(t, tc.expectedKey, key, "key should match expected key")
sshUser, err := sshUser(tc.opts.SSHUser, &tc.conf)
Expand Down

0 comments on commit 31e622d

Please sign in to comment.