Skip to content

Commit

Permalink
Merge pull request #1229 from matjack1/use-ssh-keys-when-executing-co…
Browse files Browse the repository at this point in the history
…mmands

[FIX] - Make kamal use ssh keys from config when performing commands
  • Loading branch information
djmb authored Dec 2, 2024
2 parents 084d1d4 + e31b985 commit 9982909
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/kamal/commands/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def initialize(config)
end

def run_over_ssh(*command, host:)
"ssh#{ssh_proxy_args} -t #{config.ssh.user}@#{host} -p #{config.ssh.port} '#{command.join(" ").gsub("'", "'\\\\''")}'"
"ssh#{ssh_proxy_args}#{ssh_keys_args} -t #{config.ssh.user}@#{host} -p #{config.ssh.port} '#{command.join(" ").gsub("'", "'\\\\''")}'"
end

def container_id_for(container_name:, only_running: false)
Expand Down Expand Up @@ -94,5 +94,15 @@ def ssh_proxy_args
" -o ProxyCommand='#{config.ssh.proxy.command_line_template}'"
end
end

def ssh_keys_args
"#{ ssh_keys.join("") if ssh_keys}" + "#{" -o IdentitiesOnly=yes" if config.ssh&.keys_only}"
end

def ssh_keys
config.ssh.keys&.map do |key|
" -i #{key}"
end
end
end
end
10 changes: 10 additions & 0 deletions test/commands/app_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,16 @@ class CommandsAppTest < ActiveSupport::TestCase
assert_equal "ssh -J root@2.2.2.2 -t app@1.1.1.1 -p 22 'ls'", new_command.run_over_ssh("ls", host: "1.1.1.1")
end

test "run over ssh with keys config" do
@config[:ssh] = { "keys" => [ "path_to_key.pem" ] }
assert_equal "ssh -i path_to_key.pem -t root@1.1.1.1 -p 22 'ls'", new_command.run_over_ssh("ls", host: "1.1.1.1")
end

test "run over ssh with keys config with keys_only" do
@config[:ssh] = { "keys" => [ "path_to_key.pem" ], "keys_only" => true }
assert_equal "ssh -i path_to_key.pem -o IdentitiesOnly=yes -t root@1.1.1.1 -p 22 'ls'", new_command.run_over_ssh("ls", host: "1.1.1.1")
end

test "run over ssh with proxy_command" do
@config[:ssh] = { "proxy_command" => "ssh -W %h:%p user@proxy-server" }
assert_equal "ssh -o ProxyCommand='ssh -W %h:%p user@proxy-server' -t root@1.1.1.1 -p 22 'ls'", new_command.run_over_ssh("ls", host: "1.1.1.1")
Expand Down

0 comments on commit 9982909

Please sign in to comment.