Last active
August 29, 2015 14:15
-
-
Save bewie/0efdc1c46103d8d24882 to your computer and use it in GitHub Desktop.
simple def to convert hash into ini file with pupet erb.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%- | |
# Function to make a structured and sorted .ini representation out of a hash | |
def recursive_hash_to_ini(hash, depth=0) | |
hash.keys.sort.each do |sorted_key| | |
if hash[sorted_key].is_a?(Array) | |
@ini_string += "\n" | |
hash[sorted_key].each do |item| | |
@ini_string += sorted_key + '=' + item +"\n" | |
end | |
elsif hash[sorted_key].is_a?(Hash) | |
@yini_string += '[' + sorted_key + "]\n" | |
recursive_hash_to_ini(hash[sorted_key], depth+1) | |
else | |
@ini_string += sorted_key + '=' + hash[sorted_key].to_s + "\n" | |
end | |
end | |
end | |
# Function to transform into full hash representation | |
def transform(hash) | |
return_vals = [] | |
hash.each do |key,val| | |
if val.is_a?(Hash) | |
transform(val).each do |stuff| | |
return_vals << { key => stuff } | |
end | |
else | |
return_vals << { key => val } | |
end | |
end | |
return_vals | |
end | |
# Function to deep merge hashes with same keys | |
class ::Hash | |
def deep_merge_with_array_values_concatenated(hash) | |
target = dup | |
hash.keys.each do |key| | |
if hash[key].is_a? Hash and self[key].is_a? Hash | |
target[key] = target[key].deep_merge_with_array_values_concatenated(hash[key]) | |
next | |
end | |
if hash[key].is_a?(Array) && target[key].is_a?(Array) | |
target[key] = target[key] + hash[key] | |
else | |
target[key] = hash[key] | |
end | |
end | |
target | |
end | |
end | |
# initial string | |
@ini_string = "" | |
if !@clusterdata.empty? | |
## Transform into full write up | |
transformed_config = transform(@clusterdata) | |
# Merge it back into a hash | |
tmphash = { } | |
transformed_config.each do |subhash| | |
tmphash = tmphash.deep_merge_with_array_values_concatenated(subhash) | |
end | |
# Transform it into yaml | |
recursive_hash_to_ini(tmphash) | |
end | |
-%> | |
### MANAGED BY PUPPET ###\n | |
<%= @ini_string -%> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment