Template question - looping and variables

So here’s my loop statement in my recipe.

for host in node['mycookbook']['hosts'] do
  template "/path/to/conf.d/#{host}.cfg" do
    source 'file.cfg.erb'
    owner 'owner'
    group 'group'
    mode 0664
  end
end

and in my template file its like this:

host_name    <% #{host} %> 

This doesn’t seem correct as I’m getting all sorts of errors with regards to that statement.
I’ve also tried using:

host_name    <%= host %> 

but that didn’t work.

Can I use/how do I use the host variable within the template itself?

You need to pass in host as a variable .

for host in node['mycookbook']['hosts'] do
  template "/path/to/conf.d/#{host}.cfg" do
    source 'file.cfg.erb'
    owner 'owner'
    group 'group'    variables({host: host})
    mode 0664
  end
end

and to use it in your template, prepend @ to the variable name:

host_name <% #{@host} %>

Check https://docs.chef.io/resource_template.html and look for the
'variables' section for more details.

Is there a way to do something like a host/ip map?

so the array is defined as

array = [“host1:1.1.1.1”, “host2:2.2.2.2”]

then loop thru the array, using hostnames where needed and ips where needed?

To do that, you would use a hash rather than an array.

Also note that in my sample, I replaced the for loop with the each operator; it’s more Ruby-like even for an array

myHash = {“host1” => “1.1.1.1”, “host2” => “2.2.2.2”}

myHash.each do |host, ip|
template “/path/to/conf.d/#{host}.cfg” do
source "file.cfg.erb"
owner 'owner’
group 'group’
mode 0664
variables(
host: host,
ip: ip
)
end
end

Kevin Keane
Whom the IT Pros Call
The NetTech
http://www.4nettech.com
Our values: Privacy, Liberty, Justice
See https://www.4nettech.com/corp/the-nettech-values.html

That sounds like an xy problem, didn’t you find a community cookbook to handle install and configuration of your target software ?