【问题标题】:How to call Chef resource inside ruby_block in Chef?如何在 Chef 的 ruby​​_block 中调用 Chef 资源?
【发布时间】:2016-07-06 06:32:41
【问题描述】:

我正在尝试调用 ruby​​_block 中的 Chef 资源。谁能告诉我这段代码有什么问题?

file '/tmp/arockia/storage.txt' do
end

lines = `cat /tmp/arockia/storage.txt | wc -l`
ruby_block 'Check for content' do
    block do
            lines = `cat /tmp/arockia/storage.txt | wc -l`
            if Integer(lines) == 0
                    r = Chef::Resource::Execute.new('Get-Disk-Storage',run_context)
                    r.command 'df -kh >> /tmp/arockia/storage.txt'
                    r.run_action :run
            end
    end
end

【问题讨论】:

  • 什么不工作/错误信息?
  • @StephenKing 没有错误。它说“执行红宝石块检查内容”
  • 您是否尝试过将其简化为最小示例,即删除if 条件?
  • 它与资源一起工作(:execute => "Get-Disk-Storage").run_action(:run)

标签: ruby chef-infra


【解决方案1】:

为什么不直接

require 'mixlib/shellout'

file '/tmp/arockia/storage.txt' do
  action :create_if_missing
  contents lazy { shell_out!('df -kh').stdout }
  not_if do
    ::File.file?('/tmp/arockia/storage.txt') && \
      ::File.size('/tmp/arockia/storage.txt') > 0
  end
end

?

厨师食谱中的反引号通常是个坏主意。 https://docs.chef.io/ruby.html#shelling-out

已更新以在评论中包含 coderanger 的建议。

【讨论】:

  • 非常感谢@Karen B.
  • 这仍然是错误的,正确的代码是contents lazy { shell_out!('df -kh').stdout }。使用 shell_out! 帮助程序可确保您获得 Chef 日志记录设置,并且如果命令失败,它将引发异常。此外,您还需要 lazy{},因为 contents 属性本身不接受块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 2018-03-01
  • 1970-01-01
  • 2015-08-12
  • 2018-12-15
相关资源
最近更新 更多