Skip to content

Commit

Permalink
Add user to docker group if not superuser
Browse files Browse the repository at this point in the history
This allows docker commands to function with a non-root
ssh user

Fixes: basecamp#980
  • Loading branch information
NeilW committed Oct 10, 2024
1 parent 493c569 commit 4f93502
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/kamal/cli/server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def bootstrap
if execute(*KAMAL.docker.superuser?, raise_on_non_zero_exit: false)
info "Missing Docker on #{host}. Installing…"
execute *KAMAL.docker.install
execute *KAMAL.docker.add_group
else
missing << host
end
Expand Down
5 changes: 5 additions & 0 deletions lib/kamal/commands/docker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ def superuser?
[ '[ "${EUID:-$(id -u)}" -eq 0 ] || command -v sudo >/dev/null || command -v su >/dev/null' ]
end

# Add the user to the docker group if we're not root
def add_group
[ '[ "${EUID:-$(id -u)}" -eq 0 ] || sudo usermod -aG docker "${USER:-$(id -un)}"' ]
end

def create_network
docker :network, :create, :kamal
end
Expand Down
1 change: 1 addition & 0 deletions test/cli/server_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class CliServerTest < CliTestCase
stub_setup
SSHKit::Backend::Abstract.any_instance.expects(:execute).with(:docker, "-v", raise_on_non_zero_exit: false).returns(false).at_least_once
SSHKit::Backend::Abstract.any_instance.expects(:execute).with('[ "${EUID:-$(id -u)}" -eq 0 ] || command -v sudo >/dev/null || command -v su >/dev/null', raise_on_non_zero_exit: false).returns(true).at_least_once
SSHKit::Backend::Abstract.any_instance.expects(:execute).with('[ "${EUID:-$(id -u)}" -eq 0 ] || sudo usermod -aG docker "${USER:-$(id -un)}"').at_least_once
SSHKit::Backend::Abstract.any_instance.expects(:execute).with(:sh, "-c", "'curl -fsSL https://get.docker.com || wget -O - https://get.docker.com || echo \"exit 1\"'", "|", :sh).at_least_once
SSHKit::Backend::Abstract.any_instance.expects(:execute).with(:mkdir, "-p", ".kamal").returns("").at_least_once
Kamal::Commands::Hook.any_instance.stubs(:hook_exists?).returns(true)
Expand Down
4 changes: 4 additions & 0 deletions test/commands/docker_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,8 @@ class CommandsDockerTest < ActiveSupport::TestCase
test "superuser?" do
assert_equal '[ "${EUID:-$(id -u)}" -eq 0 ] || command -v sudo >/dev/null || command -v su >/dev/null', @docker.superuser?.join(" ")
end

test "add_group" do
assert_equal '[ "${EUID:-$(id -u)}" -eq 0 ] || sudo usermod -aG docker "${USER:-$(id -un)}"', @docker.add_group.join(" ")
end
end

0 comments on commit 4f93502

Please sign in to comment.