Question

How would I accomplish the following in Capistrano?

sudo su - postgres
/usr/pgsql-9.2/bin/pg_ctl status -D /var/lib/pgsql/9.2/data/

The following task doesn't work:

task :postgres_check do
 on roles(:db) do in: :sequence |host|
  execute "sudo su - postgres << EOF
   /usr/pgsql-9.2/bin/pg_ctl status -D /var/lib/pgsql/9.2/data/ 
   EOF"  
 end
end

The commands in the execute statement works in a bash script.

EDIT 1:

I also tried the following:

task :postgres_check do
  on roles(:postgres_pref_db), in: :sequence do |host|
   execute  "/usr/pgsql-9.2/bin/pg_ctl status -D /var/lib/pgsql/9.2/data", :shell => "sudo su - postgres" 
  end
 end

Which errors with:

DEBUG [68eb95f2] Command: /usr/pgsql-9.2/bin/pg_ctl status -D /var/lib/pgsql/9.2/data
DEBUG [68eb95f2]        pg_ctl: could not open PID file "/var/lib/pgsql/9.2/data/postmaster.pid": Permission denied
cap aborted!
SSHKit::Command::Failed: /usr/pgsql-9.2/bin/pg_ctl status -D /var/lib/pgsql/9.2/data stdout: Nothing written

It appears that it still executing the command as the ssh user.

Was it helpful?

Solution

I came across this and explored the answer for myself. I wouldn't have accepted the answer either to I'll provide what I did.

task :copy_files do
  on  roles(:web) do |host|
    as 'other_user' do
        execute "whoami"
    end 
  end
end

Capistrano 3 uses SSH KIT and I found these examples really helpful for getting bash commands to work inside my tasks. https://github.com/capistrano/sshkit/blob/master/EXAMPLES.md

You'll want to checkout ssh kit and see about on(), within(), with(), as() ... they can be used nested in any order. So you end up having a lot of control even if it takes a few minutes to learn.

I think for your specific example you will want to use as() and within() to become the postgres user and run commands within a certain directory.

Also I had to disable requiretty on my /etc/sudoers for my deploy user.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top