我创建了以下数据包项目:
{
"name": "data_bag_item_nameservers_servers",
"json_class": "Chef::DataBagItem",
"chef_type": "data_bag_item",
"data_bag": "nameservers",
"raw_data": {
"id": "servers",
"serverslist": [
"xxx.xxx.xxx.xxx",
"xxx.xxx.xxx.xxx"
]
}
}
在模板erb中我添加了以下调用,
<% @serverslist.each_with_index do |nmserver| %>
nameserver <%= nmserver %>
<% end %>
但它不适合我并且给出错误,
在资源&#39;模板上执行操作创建时出错[/etc/resolve.conf]&#39;
厨师::密新::模板:: TemplateError
未定义的方法each_with_index&#39;为零:NilClass
有人可以帮助我如何在食谱食谱中调用这些数据包项目值?
提前致谢!
答案 0 :(得分:5)
您是否考虑过使用节点属性的更简单的选项?
在运行时,很容易超越cookbook默认设置。我指出这一点,因为根据我的经验,很少需要数据包。
我已经包含了两个例子。
“演示”食谱
├── attributes
│ └── default.rb
├── Berksfile
├── Berksfile.lock
├── chefignore
├── metadata.rb
├── README.md
├── recipes
│ └── default.rb
├── templates
│ └── default
│ └── dummy.erb
└── test
└── integration
├── default
│ └── serverspec
│ └── default_spec.rb
└── helpers
└── serverspec
└── spec_helper.rb
default['demo']['nameservers']['one'] = "one"
default['demo']['nameservers']['two'] = "two"
default['demo']['nameservers']['three'] = "three"
template "/etc/dummy" do
source "dummy.erb"
owner 'root'
group 'root'
mode '0644'
end
<% node['demo']['nameservers'].each do |name,server| %>
nameserver <%= server %>
<% end %>
require 'spec_helper'
describe file('/etc/dummy') do
it { should be_file }
it { should be_owned_by 'root' }
it { should contain 'nameserver one' }
it { should contain 'nameserver two' }
it { should contain 'nameserver three' }
end
“演示”食谱,包含测试/集成目录下的测试数据包
├── Berksfile
├── Berksfile.lock
├── chefignore
├── metadata.rb
├── README.md
├── recipes
│ └── default.rb
├── templates
│ └── default
│ └── dummy.erb
└── test
└── integration
├── data_bags
│ └── stuff
│ └── nameservers.json
├── default
│ └── serverspec
│ └── default_spec.rb
└── helpers
└── serverspec
└── spec_helper.rb
示例数据
{
"id": "nameservers",
"list": [
"one",
"two",
"three"
]
}
配方现在更加复杂。必须显式检索数据包中的数据,然后将其作为变量
传递到模板中nameservers = data_bag_item('stuff', "nameservers")
template "/etc/dummy" do
source "dummy.erb"
owner 'root'
group 'root'
mode '0644'
variables ({
"servers" => nameservers["list"]
})
end
<% @servers.each do |server| %>
nameserver <%= server %>
<% end %>
require 'spec_helper'
describe file('/etc/dummy') do
it { should be_file }
it { should be_owned_by 'root' }
it { should contain 'nameserver one' }
it { should contain 'nameserver two' }
it { should contain 'nameserver three' }
end
答案 1 :(得分:3)
您需要从食谱代码中显式加载数据包,通常使用data_bag_item(bagname, itemname)
函数,然后使用其variables
属性将其传递给模板。