0

The issue that I'm facing is when I'm trying to automate a terraform script for bootstrap VMs. I keep all the templates in json files and depending on instance it will take one, two or more templates to create the node json file. My code looks like:

template.each do |t|
  node = JSON.parse(File.read("./terraform/node/#{t}.json"))
  atr << node.each { |k, v| puts "#{k}: #{v}" }
  concatenated = atr.flatten
  temp = concatenated  
  File.open("./terraform/node/#{instance_name}.json","w") do |f|
    f.puts JSON.pretty_generate(temp)
  end
end

The output file looks like:

[{"haproxy"=>{"app_server_role"=>["s1", "s2"]}}, {"apache"=>{"listen_ports"=>["80", "443"]}}, {"tags"=>[]}]

The issue is that inside the array we have the exact template stored in erb :

{"haproxy"=>{"app_server_role"=>["s1", "s2"]}}
{"tags"=>[]} ...

What I want is a valid json with the content of templates like:

 {"haproxy"=>{"app_server_role"=>["s1", "s2"]}, "apache"=>{"listen_ports"=>["80", "443"]}, {"tags"=>[]}

1 Answer 1

1
output_file = [{"haproxy"=>{"app_server_role"=>["s1", "s2"]}}, {"apache"=>{"listen_ports"=>["80", "443"]}}, {"tags"=>[]}]

output_file.each_with_object({}) { |h, h2| h2.merge!(h) }
 => {"haproxy"=>{"app_server_role"=>["s1", "s2"]}, "apache"=>{"listen_ports"=>["80", "443"]}, "tags"=>[]}

another great option suggested by mudasobwa:

output_file.reduce(&:merge)
Sign up to request clarification or add additional context in comments.

4 Comments

output_file.reduce(&:merge)?
even better! Thanks @mudasobwa
Looks pretty simple but in my case what is output_file? it will be atr << node.reduce(&:merge) ?
@CatalinaCenan, I named it that from your comment: The output file looks like:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.