将 facter 注入文件内容 - 没有将 Hash 隐式转换为 String

Injecting facter into file content - no implicit conversion of Hash into String

我想将 facter <prop> 中的一些值注入到文件内容中。

它适用于 $fqdn,因为 facter fqdn returns string

node default {
  file {'/tmp/README.md':
    ensure  => file,
    content => $fqdn, # $(facter fqdn)
    owner   => 'root',
  }

}

但是,它不适用于散列对象 (facter os):

   node default {
      file {'/tmp/README.md':
        ensure  => file,
        content => $os, # $(facter os) !! DOES NOT WORK
        owner   => 'root',
      }

   }

并在 运行 puppet agent -t:

时收到此错误消息

Error: Failed to apply catalog: Parameter content failed on File[/tmp/README.md]: Munging failed for value {"architecture"=>"x86_64", "family"=>"RedHat", "hardware"=>"x86_64", "name"=>"CentOS", "release"=>{"full"=>"7.4.1708", "major"=>"7", "minor"=>"4"}, "selinux"=>{"config_mode"=>"enforcing", "config_policy"=>"targeted", "current_mode"=>"enforcing", "enabled"=>true, "enforced"=>true, "policy_version"=>"28"}} in class content: no implicit conversion of Hash into String (file: /etc/puppetlabs/code/environments/production/manifests/site.pp, line: 2)

如何在 pp 文件中将哈希值转换为字符串?

如果您有 Puppet >= 4.5.0,现在可以os将各种数据类型本地转换为清单中的字符串(即在 pp 文件中)。转换函数记录在案 here.

这会做你想做的事:

file { '/tmp/README.md':
  ensure  => file,
  content => String($os),
}

或更好:

file { '/tmp/README.md':
  ensure  => file,
  content => String($facts['os']),
}

在我的 Mac OS X 上,这会导致文件包含:

{'name' => 'Darwin', 'family' => 'Darwin', 'release' => {'major' => '14', 'minor' => '5', 'full' => '14.5.0'}}

查看所有文档,因为有很多选项可能对您有用。

当然,如果你想要 $os 里面的键,

file { '/tmp/README.md':
  ensure  => file,
  content => $facts['os']['family'],
}

现在,如果您没有最新的 Puppet,也没有字符串转换函数,那么旧的方法是通过模板和嵌入式 Ruby (ERB),例如

$os_str = inline_template("<%= @os.to_s %>")
file { '/tmp/README.md':
  ensure => file,
  content => $os_str,
}

这实际上会导致格式略有不同的哈希,因为 Ruby,而不是 Puppet 进行格式化:

{"name"=>"Darwin", "family"=>"Darwin", "release"=>{"major"=>"14", "minor"=>"5", "full"=>"14.5.0"}}