简体   繁体   中英

Run sudo commands in Chef resource block

To simplify, consider following block in a cookbook (cookbook-test) recipe.

 79: bash 'Running sudo test sleep command' do
 80:   user 'root'
 81:   cwd '/tmp'
 82:   code <<-EOH
 83:   sudo sleep 1000
 84:   EOH
 85: end

Running this as

"chef-client -o cookbook-test"

Output:

Mixlib::ShellOut::ShellCommandFailed
------------------------------------
Expected process to exit with [0], but received '1'
---- Begin output of "bash"  "/tmp/chef-script20150813-3835-3kj758" ----
STDOUT:
STDERR: sudo: sorry, you must have a tty to run sudo
---- End output of "bash"  "/tmp/chef-script20150813-3835-3kj758" ----
Ran "bash"  "/tmp/chef-script20150813-3835-3kj758" returned 1

I added "sudo sleep" just to exemplify usecase. In real case, we run scripts inside above resource block, and these scripts has sudo commands.

After some debugging found that "bash" and "execute" resource blocks both do not have tty allocated to run commands inside them.

Please share your thoughts.

Here's the thing:

Any facility you could use in Chef to run sudo with an allocated tty could also be used by anybody else , which means the requiretty directive in your sudoers is effectively useless. So you might as well just remove it and save yourself the trouble of working around it.

Having said that, here are some ways to work around the problem:

  1. Are you able to ssh to localhost without a password? You could just use ssh -tt localhost sudo somecomand ... .

  2. You can use the expect tool, which is designed for controlling terminal-oriented programs. Something like expect -c "spawn sudo somecommand; interact" .

  3. You can use screen , with something like screen sudo somecommand .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM