在Chef中访问模板属性

时间:2019-02-17 03:29:58

标签: ruby chef

我在Chef/Ruby中声明了一个变量,并为其分配了一个值。对于不同的环境,该值是不同的。我在这样的各个环境文件中设置值:

region = us-west-1 

在模板文件中,我以这种方式使用

region =<%= @region %>

,在配方中为

:region =>node.region

合并我的修订时,实例不出现。 是这样做的正确方法,还是我错过了什么?

1 个答案:

答案 0 :(得分:0)

这是我最喜欢的两种方法:

  • 使用厨师属性。

在属性文件中定义属性的默认值。因此,请在<cookbook_name>/attributes/default.rb文件中添加以下行:

default['instance_region'] = 'us-west-1'

,然后在您要添加模板的食谱中:

variables(region: node['instance_region'])

您可以按照您提到的在模板中访问它:

region =<%= @region %>
  • 使用厨师库。

对于更广泛的用途,您可以在Chef库中定义此类值。因此在<cookbook>/libraries/common.rb中添加:

module Common
   def instance_region
     # This will return the name of AWS region that the nodes is in.
     shell_out!('curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone/').stdout
   end
 end

然后在您的食谱中,只需调用普通instance_region

就可以使用它
相关问题