24

我想将 shell 命令的输出放入一个变量中,以便以后在 Chef 食谱中使用。

在 bash 我可以做类似的事情output=`tail -1 file.txt`然后我可以echo $output

“执行资源”可以这样做,以便我稍后可以在配方中使用结果吗?

4

2 回答 2

20

虽然格雷厄姆的解决方案一开始似乎有效,但我发现了 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 特别有用(参见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
于 2013-12-16T14:27:55.673 回答
3

为我工作

passenger_root = shell_out("passenger-config --root").stdout
于 2018-07-04T13:03:42.353 回答