24

I'd like to put the output of a shell command into a variable for later use in a Chef recipe.

In bash I could do something like output=`tail -1 file.txt` and then I could echo $output

Can an 'execute resource' do this so that I can use the result later in the recipe?

Jake
  • 12,713
  • 18
  • 66
  • 96

2 Answers2

20

while Graham's solution seemed to work at first, I found out about Chef::Mixin:ShellOut

ruby_block "check_curl_command_output" do
    block do
      #tricky way to load this Chef::Mixin::ShellOut utilities
      Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut)      
      curl_command = 'curl --write-out %{http_code} --silent --output /dev/null '+node['url']
      curl_command_out = shell_out(curl_command)
      if curl_command_out.stdout == "302"
        ...
      else
        ...
      end
    end
    action :create
end

Chef::Mixin:ShellOut is particularly useful if you need to run the command as a specific user (cf. http://www.slideshare.net/opscode/chef-conf-windowsdougireton ):

ruby_block "run_command_as" do
    block do
    Chef::Resource::RubyBlock.send(:include,Chef::Mixin::ShellOut)
    add_group = shell_out("your command",
        {
          :user => "my_user",
          :password => "my_password",
          :domain => "mycorp.com"
        }
        )
    end
end
guido
  • 18,864
  • 6
  • 70
  • 95
Francois
  • 1,851
  • 1
  • 13
  • 15
  • This is a more elegant solution to the problem than the accepted answer, and provides better functionality. Thanks for posting, Francois! – cixelsyd Jul 03 '14 at 21:07
  • Is there anybody who wrote chefspec for this type of code? – Joel Handwell Dec 28 '15 at 23:18
  • Loading the shell_out helper manually into resources/providers is no longer necessary, and there's no need for the indirection with the ruby_block in this case. The simple one-liner below is a much better solution to start with. – lamont Aug 21 '20 at 01:41
3

Works for me

passenger_root = shell_out("passenger-config --root").stdout
lamont
  • 3,854
  • 1
  • 20
  • 26
Aivils Štoss
  • 858
  • 11
  • 9
  • The `require 'chef/mixin/shell_out'` line is no longer necessary. This should also really be the accepted answer. There's no need to use the ruby_block or to inject the shell_out methods any longer. (And i just updated the answer to remove the require line) – lamont Aug 21 '20 at 01:38