Capistrano 3 sudo task

不想你离开。 提交于 2019-12-03 05:35:48

问题


I want to write a recipe with Capistrano 3 executing a task on the remote server with sudo.

With Capistrano 2 this could be done for example:

default_run_options[:pty] = true

task :hello do
  run "#{sudo} cp ~/something /something"
end

With Capistrano 3 I found:

set :pty, true

But I could not get to execute a task running with sudo.

How can I run a task with sudo?


回答1:


The Capistrano 3 guide recommends the use of passwordless sudo. This allows your less-priveleged user execute the sudo command without having to enter a password via the PTY.

You can use the task that Kentaro wrote above, and add something like the following to your /etc/sudoers file:

deploy ALL=NOPASSWD:/bin/cp ~/something /something

http://www.capistranorb.com/documentation/getting-started/authentication-and-authorisation/#toc_8




回答2:


I usually write like this:

task :hello do
  on roles(:all) do |host|
    execute :sudo, :cp, '~/something', '/something'
  end
end

Edit

Capistrano 3 does not support sudo with password.

However, I created a small gem, which enables you to use sudo with password in Capistrano 3 task.

Add sshkit-sudo to your application's Gemfile:

# Gemfile
gem 'sshkit-sudo'

And require 'sshkit/sudo' in you Capfile:

# Capfile
require 'sshkit/sudo'

Now, you can execute a command with sudo as follows:

task :hello do
  on roles(:all) do
    sudo :cp, '~/something', '/something'
  end
end



回答3:


To resolve this issue I needed to add set :pty, true to my deploy.rb file.

I can now run the following:

# config valid only for Capistrano 3.1
lock '3.1.0'

set :application, 'APP_NAME'
set :pty, true
set :ssh_options, {:forward_agent => true}

namespace :deploy do

  desc 'Restart NGINX'
  task :restart do
    on roles(:app), in: :sequence, wait: 1 do
       execute :sudo, "./restart.sh"
    end
  end

end

This task basically runs a shell script called restart.sh that has a command within sudo service nginx restart.




回答4:


you want "as user do end", like

as "root" do
  execute :something
end



回答5:


If you really need to use sudo you can always map the command like SSHKit.config.command_map[:rm] = 'sudo rm' which will make execute :rm into the proper rm command invoked with sudo. If your deploy user is in the sudoers things will work as expected.



来源:https://stackoverflow.com/questions/19948809/capistrano-3-sudo-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!