Template Question


#1

I have two attributes like this:

default[‘proxy’][‘proxy-backend’][‘hosts’] = %w[127.0.0.1, 127.0.0.2]
default[‘proxy’][‘proxy-backend’][‘ports’] = %w[111, 112]

I want it to look like this in the template:

hosts = ‘127.0.0.1:111, 127.0.0.1:112, 127.0.0.2:111, 127.0.0.2:112’

Everything I tried so far isn’t working

Thanks for any advice!
Jenn


#2

The Array#product method should get you all of the combinations, then you just need to join each into the correct string form.

[1] pry(main)> ips = %w{ ip1 ip2 ip3 }
=> ["ip1", "ip2", "ip3"]
[2] pry(main)> ports = %w{ p1 p2 p3 }
=> ["p1", "p2", "p3"]
[3] pry(main)> ips.product(ports)
=> [["ip1", "p1"],
 ["ip1", "p2"],
 ["ip1", "p3"],
 ["ip2", "p1"],
 ["ip2", "p2"],
 ["ip2", "p3"],
 ["ip3", "p1"],
 ["ip3", "p2"],
 ["ip3", "p3"]]
[5] pry(main)> ips.product(ports).map { |ip,port| "#{ip}:#{port}" }.join(", ")
=> "ip1:p1, ip1:p2, ip1:p3, ip2:p1, ip2:p2, ip2:p3, ip3:p1, ip3:p2, ip3:p3"

#3

Remember to use caution when using arrays as values for attributes. If you’re trying to override things, you could run in to behavior that doesn’t work exactly how you expect. Read https://coderanger.net/arrays-and-chef/ for a good overview of how this behavior works.

You’re probably fine in this case, but it’s a good thing to be aware of.


#4

Thank you! Great information! Working as expected!