本文介绍了如何在 Puppet DSL 中将哈希转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 hash 散列,我需要将其嵌入到 exec 资源命令中.我的想法是将 hash 序列化为 string 并将其插入到 exec call 中.exec 调用将通过 ruby -e 'ruby code here' 执行 ruby​​ 代码.

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'.

使用 irb,我知道 hash.to_s 创建了 hash 的单行可解析版本.或者我可以使用json.我怀疑您是否可以在 puppet 中调用 to_s,但我不确定.

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.

Puppet 的 stdlib 有 parseyamlparsejson 可以反序列化,但是有没有办法序列化为可解析的 string?我可以编写一个自定义的 puppet 函数来完成它,但如果有的话,我更喜欢已经内置的解决方案.

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.

更新我正在考虑定义一个木偶函数.我以前从未写过,所以不确定语法.这是我的第一次尝试:

UpdateI 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

推荐答案

你总是可以在你的 puppet 模块中执行 ruby​​ 代码:

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

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

显然不要过度使用它很重要,但是当一个非常简单的 ruby​​ 函数可以实现您需要的功能时它特别有用.

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

这篇关于如何在 Puppet DSL 中将哈希转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 08:21