puppetepp

Write hash as JSON inside puppet epp template


I am facing while printing values from .epp template in puppet

  1. I have following data in hiera, which defines groups (array of hashes)
profiles::groups:
  - name: 'admins'
    type: 1
    rights: []
  - name: 'users'
    type: 2
    rights: []
  1. The above hiera key is called in .epp template like this
   .....    
   groups = <%= require 'json'; JSON.pretty_generate scope['groups'] %> 
   .....
  1. Above declaration should print the values in file in following format (from above epp template) but gives error as mentioned below
....... 
groups = [
  {
    "name": "admins",
    "type": 1,
    "rights": []
  },
  {
    "name": "users",
    "type": 2,
    "rights": []
  }
]
.....
Error Message: Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Evaluation Error: Error while evaluating a Function Call, epp(): Invalid EPP: Syntax error at 'json' 

While declaring the same format in .erb template works fine and it produces desired output.


Solution

  • In erb it's embedded ruby you can use regular ruby functions, on epp it's embedded Puppet so you need to use Puppet functions. There is a to_json_pretty available in stdlib https://forge.puppet.com/modules/puppetlabs/stdlib which will do the job and you can use it like this;

    groups = <%= $groups.to_json_pretty %> 
    

    I've just tested it out with;

    # test/manifests/jsontest.pp
    class test::jsontest {
    
      $groups = lookup('test::groups')
    
      file { '/root/epp':
        ensure  => file,
        content => epp("test/jsondata.epp", {groups => $groups})
      }
    }
    
    # test/templates/jsondata.epp
    groups = <%= $groups.to_json_pretty %> 
    
    # common.yaml
    test::groups:
      - name: 'admins'
        type: 1
        rights: []
      - name: 'users'
        type: 2
        rights: []