Skip to content

Instantly share code, notes, and snippets.

@WhatsARanjit
Last active July 24, 2019 20:31
Show Gist options
  • Save WhatsARanjit/ea67ba17085968cb985c5898190dafc6 to your computer and use it in GitHub Desktop.
Save WhatsARanjit/ea67ba17085968cb985c5898190dafc6 to your computer and use it in GitHub Desktop.
Puppet data to XML
$data = {
'?xml version="1.0" encoding="UTF-8"?' => false,
'xml' => {
'fruit' => 'apple',
'vegetables' => {
'green' => 'cucumber',
'brown' => 'potato'
},
'nested' => {
'one' => {
'foo' => 'bar',
},
'two' => {
'foo' => 'bar',
}
}
}
}
file { '/tmp/example.xml':
ensure => file,
content => hash_to_xml($data),
}
file { '/tmp/example2.xml':
ensure => file,
content => hash_to_xml($data, 0, "\t", 4),
}
Puppet::Functions.create_function(:hash_to_xml) do
dispatch :hash_to_xml do
param 'Hash', :data
optional_param 'Integer', :level
optional_param 'String', :character
optional_param 'Integer', :num
end
def calc_indent(level)
@character * @num * level
end
def kv_to_xml(k, v = nil, level = 0, open = true, close = true)
output = ''
output += calc_indent(level)
output +="<#{k}>" if open
output += v if (open and close)
output += "</#{k}>" if close
output += "\n"
end
def hash_to_xml(h, level = 0, character = "\s", num = 2)
@character = character
@num = num
xml = ''
h.each do |key, value|
case value
when String
xml += kv_to_xml(key, value, level)
when Hash
xml += kv_to_xml(key, nil, level, true, false)
xml += hash_to_xml(value, level+1, @character, @num)
xml += kv_to_xml(key, nil, level, false, true)
when FalseClass
xml += kv_to_xml(key, nil, level, true, false)
else
fail('Error')
end
end
return xml
end
end
[root@puppet /opt/puppetlabs/puppet/modules/hash_to_xml]# puppet apply examples/test.pp && cat /tmp/example.xml && cat /tmp/example2.xml
Notice: Compiled catalog for puppet.puppetlabs.vm in environment production in 0.08 seconds
Notice: Applied catalog in 0.25 seconds
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<fruit>apple</fruit>
<vegetables>
<green>cucumber</green>
<brown>potato</brown>
</vegetables>
<nested>
<one>
<foo>bar</foo>
</one>
<two>
<foo>bar</foo>
</two>
</nested>
</xml>
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<fruit>apple</fruit>
<vegetables>
<green>cucumber</green>
<brown>potato</brown>
</vegetables>
<nested>
<one>
<foo>bar</foo>
</one>
<two>
<foo>bar</foo>
</two>
</nested>
</xml>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment