How do you create pretty json in CHEF (ruby)

后端 未结 3 1142
予麋鹿
予麋鹿 2021-02-09 16:58

How would you make an erb template that has human readable json?

The following code works, but it makes a flat json file

default.rb

default[\'         


        
3条回答
  •  太阳男子
    2021-02-09 17:37

    As pointed out by this SO Answer .erb templates are great for HTML, and XML, but is not good for json.

    Luckily, CHEF uses its own json library which has support for this using .to_json_pretty

    @coderanger in IRC, pointed out that you can use this library right inside the recipe. This article shows more extensively how to use chef helpers in recipes.

    default.rb

    # if ['foo']['bar'] is null, to_json_pretty() will error
    default['foo']['bar'] = {}
    

    recipe/foo.rb

    pretty_settings = Chef::JSONCompat.to_json_pretty(node['foo']['bar'])
    
    template "foo.json" do
      source 'foo.json.erb'
      variables :settings => pretty_settings
      action :create
    end
    

    Or more concise as pointed out by YMMV

    default.rb

    # if ['foo']['bar'] is null, to_json_pretty() will error
    default['foo']['bar'] = {}
    

    recipe/foo.rb

    template "foo.json" do
      source 'foo.json.erb'
      variables :settings => node['foo']['bar']
      action :create
    end
    

    templates/foo.json.erb

    <%= Chef::JSONCompat.to_json_pretty(@settings) %>
    

提交回复
热议问题