gbaii gbaii - 1 month ago 22
Ruby Question

Chef each loop for each loop

I have these arrays

services=["service1","service2","service3"]
ports=[11001,11002,11003]


For each element of services I need to assign the correspondent element of ports in an conf.erb file.
What I have until now is:

node['recipe']['services'].each do |serv|
template "/etc/services/conf.d/service-#{serv}.conf" do
source "service-#{serv}.conf.erb"
owner 'serviceaccount'
group 'serviceaccount'
mode '0644'
variables(
:service => serv,
:ports => node['services']['ports']
)
end
end


It sounds bad and the result is bad.

The result should be 3 conf files:

service-service1.conf:

service-service1

port 11001

service-service2.conf:

service-service2

port 11002

service-service3.conf:

service-service3

port 11003

Any help is appreciated.

Thank you,
Gabriel

Answer

I would instead use a hash with the keys as your service names and values as your port numbers. Then you can increment through your hash with the key and the value.

Using your example code, something like:

services = { 'service1' => 11001, 'service2' => 11002, 'service3' => 11003 }

And then in your recipe:

node['recipe']['services'].each do |serv, port|
  template "/etc/services/conf.d/service-#{serv}.conf" do
    source "service-#{serv}.conf.erb"
    owner 'serviceaccount'
    group 'serviceaccount'
    mode '0644'
    variables(
      :service => serv,
      :ports => port
    )
  end
end

It's not very idiomatic chef though.