How do I turn a hash to a string in Puppet DSL?

走远了吗. 提交于 2019-12-11 11:29:24

问题


I have a hash of hashes that I need to embed in an exec resource command. My thought was to serialize the hash to a string and interpolate it into the exec call. The exec call will be executing ruby code via ruby -e 'ruby code here'.

Using irb, I know that hash.to_s creates a single line parse-able version of the hash. Or I could use json. I doubt you can call to_s in puppet, but am not sure.

The stdlib for Puppet has parseyaml and parsejson to deserialize, but is there a way to serialize to a parse-able string? I can write a custom puppet function to do it, but prefer an already built in solution if there is one.

Update I am considering defining a puppet function. I have never written one before, so am not sure of the syntax. Here is my first attempt:

Puppet::Parser::Functions.newfunction(
    :serialize_hash, 
    :arity => 2,
    :doc => "Serialize a hash to any depth and optionally escape the double quotes.",
    :type => :rvalue) do |args| 
  hash = args[0]
  escape_quotes = args[1]
  serialized = hash.to_s
  if (escape_quotes)
    serialized.sub!(/"/, "\\\"")
  end
  serialized 
end

回答1:


You can always execute ruby code inline with your puppet module:

$my_string = inline_template('<%= @my_hash.to_s %>')

Obviously it is important to not overuse this, but it is particularly useful when a very simple ruby function can achieve what you need.



来源:https://stackoverflow.com/questions/28729033/how-do-i-turn-a-hash-to-a-string-in-puppet-dsl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!