访问Chef中的模板属性

问题描述 投票:0回答:1

我在Chef/Ruby中声明一个变量并为其赋值。不同环境的值不同。我在各个环境文件中设置值,如下所示:

region = us-west-1 

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

region =<%= @region %>

在食谱中

:region =>node.region

合并修复程序时,实例不会出现。这是正确的做法还是我错过了什么?

ruby chef
1个回答
0
投票

以下是我最喜欢的两种方法:

  • 使用厨师属性。

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

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

然后在你添加模板的食谱中:

variables(region: node['instance_region'])

如上所述,您可以在模板中访问它:

region =<%= @region %>
  • 使用厨师图书馆。

为了更广泛的使用,您可以在厨师库中定义此类值。所以在<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来使用它

© www.soinside.com 2019 - 2024. All rights reserved.