Parker Smith Software

 

Respond to server prompts in Capistrano

By Brian Webb

10 Jul 2008

At Parker Smith we try to use Capistrano as much as possible to do routine tasks for us, sometimes it is something where the server requires some sort of input during the process, like creating a user, then supplying and confirming a password. With the Capistrano defaults you'll see the prompt, the script will halt, and you won't be able to get your response to the server. Here is how you fix that:

1
2
3

# in deploy.rb
default_run_options[:pty] = true

Setting the pty run option is what tells Capistrano to allow you to give response input to the script from the terminal, the next step is all in how you tell Capistrano to execute the command. Lets say that our task is to create a new user on the server and supply a password.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# deploy.rb

set :new_user, "myuser"
set :new_user_pw, "secret"

desc "Setup a new user and supply the password"
task :setup_user do
  run "useradd  -m -d /home/#{new_user} -s /bin/bash #{new_user}"

  run "passwd #{new_user}" do |ch, stream, out|
    ch.send_data "#{new_user_pw}"+"\n" if out =~ /Enter new UNIX password:/
    ch.send_data "#{new_user_pw}"+"\n" if out =~ /Retype new UNIX password:/
  end

end

Lets take a look at the code above, first we set variables for the new username and their password, this is what will get sent to the server in the command to create a new user. Next is the setup_user task, in this particular example we are executing this task as root, perhaps this is the first time you have setup any users on the new machine, if not you could just change the "run" statements to "sudo".

The second command in the task runs the 'passwd' command, grabs the output, and sends information back. The 'out' variable is the output from the server prompt, we use a REGEX pattern to match what the prompt is, so we can make a decision on what to send back.

Thats it, now to setup your new user just run:

1
2

cap setup_user

If you want to run the command with a different user or port, just run your cap command like this:

1
2

cap setup_user -s user=root -s port=22
 
 
 
No Spam: 8 + 3 =
 
July 10, 2008 - Brian Webb
0
 
June 30, 2008 - Brian Webb
0