How can I put the output of a Chef 'execute resource' into a variable

这一生的挚爱 提交于 2019-12-17 17:55:16

问题


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?


回答1:


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



回答2:


Works for me

require 'chef/mixin/shell_out'
passenger_root = shell_out("passenger-config --root").stdout


来源:https://stackoverflow.com/questions/16309808/how-can-i-put-the-output-of-a-chef-execute-resource-into-a-variable

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