如何使用Ruby块在厨师食谱中分配变量 [英] How to use a Ruby block to assign variables in chef recipe

查看:44
本文介绍了如何使用Ruby块在厨师食谱中分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Chef食谱中即时执行Ruby逻辑,并认为实现这一目标的最佳方法是使用块。

I am trying to execute Ruby logic on the fly in a Chef recipe and believe that the best way to achieve this is with a block.

我遇到了困难将在块内分配的变量传输到厨师食谱的主代码。这是我尝试的方法:

I am having difficulty transferring variables assigned inside the block to the main code of the chef recipe. This is what I tried:

ruby_block "Create list" do
  block do
    to_use ||= []
    node['hosts'].each do |host|
      system( "#{path}/command --all" \
              " | awk '{print $2; print $3}'" \
              " | grep #{host} > /dev/null" )
      unless $? == 0
        to_use << host
      end
    end
    node['hosts'] = to_use.join(',')
  end
  action :create
end

execute "Enable on hosts" do
  command "#{path}/command --enable -N #{node['hosts']}"
end

我并没有尝试动态地重新分配Chef属性,而是尝试在块中创建新变量,但仍然可以在 execute 语句中找不到访问它们的方法。

Rather than try to re-assign the chef attribute on the fly, I also tried to create new variables in the block but still can't find a way to access them in the execute statement.

我最初使用的是类和调用方法但是它是在配方之前编译的,我真的需要在配方期间在运行时执行逻辑。

I was originally using a class and calling methods however it was compiled before the recipe and I really need the logic to be executed at runtime, during the recipe.

推荐答案

您的问题是编译时间与收敛时间。您的块将在收敛时运行,但是此时,执行资源中的 node ['host'] 已被评估。

Your problem is compile time versus converge time. Your block will be run at converge time but at this time the node['host'] in the execute resource has already been evaluated.

在这种情况下,最好的解决方案是使用惰性评估,因此变量将在资源聚合而不是在编译时扩展:

The best solution in this case would be to use lazy evaluation so the variable will be expanded when the resource is converged instead of when it is compiled:

execute "Enable on hosts" do
  command lazy { "#{path}/command --enable -N #{node['hosts']}" }
end

这里有个警告,惰性运算符必须包括完整的 command 属性文本该变量,它只能用作属性名称后的第一个关键字。

Here's a little warning though, the lazy operator has to include the full command attribute text and not only the variable, it can work only as first keyword after the attribute name.

这篇关于如何使用Ruby块在厨师食谱中分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆