Convert a hash into JSON in Puppet

December 22, 2022 

This article shows you how to convert a hash into JSON in Puppet using a simple ERB template that gets its data from Hiera.

Suppose you have this data in Hiera:

    foo: one
    bar: two

Converting a hash into a JSON file on the target node is surprisingly easy. First look up the data:

$myhash = lookup('myhash', Hash)

Then create a simple ERB template (here: mymodule/templates/myhash.erb)

<% require 'json' -%>
<% require 'pp' -%>
<%= JSON.pretty_generate(@myhash) %>

Then create a file resource using this template:

file { '/tmp/myhash.json':
  ensure  => file,
  content => template('mymodule/myhash.erb'),
  owner   => 'root',
  group   => 'root',
  mode    => '0644',

The end result after running Puppet will be nicely formatted JSON:

  "mykey": {
    "foo": "one",
    "bar": "two"

That's all it takes.

Samuli Seppänen
Samuli Seppänen
Author archive