Vlad Cenan Vlad Cenan - 7 months ago 9
Ruby Question

How can I map each value found into a diffrent variable

I want to create a chef recipe and I'm stuck at this step:

members = search("node", "recipe:redis AND chef_environment:#{node.chef_environment}") || []
members.each do |node|
puts "#{node["ipaddress"]}"
end


This is working and returning me the IP addresses for those three servers found.
But I want to assign/give each VALUE found (ip address) to a variable because I will run a command like the following:

execute 'command' do
command "redis-trib.rb create --replicas 1 #{node1}:6379 #{node2}:6379 #{node3}:6379 #{node1}:6380 #{node2}:6380 #{node3}:6380"
end

Answer

You can do something like this:

nodes = members.map do |node|
          node["ipaddress"]
        end

And then use it like this:

execute 'command' do
  command "redis-trib.rb create --replicas 1 #{nodes[0]}:6379 #{nodes[1]}:6379 #{nodes[2]}:6379 #{nodes[0]}:6380 #{nodes[1]}:6380 #{nodes[2]}:6380"
end