Reputation: 3124
I am trying to build a recipe for chef that has amongst others the following attribute:
default['web-server']['hosts'] = [ { host: "some-ip", server: "some-server", port: "9000" } ]
The idea is to iterate over it to create the config file (lighttpd in this case), like so:
<% if node['web-server']['hosts'].length > 0 -%>
<% node['web-server']['hosts'].each do |host| -%>
$HTTP["host"] =~ "<%= host.host %>" {
proxy.balance = "round-robin" proxy.server = (
"" => (
"play" => (
"host" => "<%= host.server %>",
"port" => <%= host.port %>
)
)
)
}
<% end -%>
<% else -%>
<% end -%>
However, upon running chef-client
on the test node, I am greeted with:
FATAL: Chef::Mixin::Template::TemplateError: undefined method `host' for #<Mash:0x00000002b9a878>
What's the correct way of looping over an array of hashes?
Upvotes: 0
Views: 7078
Reputation: 3124
Ok, I figured this out. The correct syntax is to access the hash keys via hash[:key]
, i.e.
$HTTP["host"] =~ "<%= host[:host] %>" {
proxy.balance = "round-robin" proxy.server = (
"" => (
"play" => (
"host" => "<%= host[:server] %>",
"port" => <%= host[:port] %>
)
)
)
}
<% end -%>
<% else -%>
<% end -%>
Upvotes: 3