ruby - 检查 Hiera 值是否存在,如果存在,则将每个值分配给变量

标签 ruby puppet hiera

我有一个可以在 Hiera 中为节点设置的选项列表; mem_limit、cpu_timeout、线程...

如果它们确实存在,我需要在 list 中定义的 Ruby 模板中设置它们。

list :

file { "/etc/file.conf":
  ensure  => present,
  owner   => root,
  group   => root,
  mode    => '0644',
  content => template("${module_name}/file.conf.erb")
}

文件.conf.erb:

<% if @mem_limit -%>
limit_memory=<%= @mem_limit %> 
<% end -%>

<% if @cpu_timeout -%>
cpu_timeout=<%= @cpu_timeout %> 
<% end -%>

<% if @threads -%>
multiple_threads=true
num_threads=<%= @threads %> 
<% end -%>

我可以在 list 中为每个选项添加以下内容,但如果我有超过一打,它看起来真的很糟糕!真的希望有一个更好的方法来做到这一点,但正在努力为大量可能的选项找到一种迭代方法。

if lookup('mem_limit', undef, undef, undef) != undef {
   $mem_limit = lookup('mem_limit')
}

最佳答案

为什么不使用 automatic class parameter lookup ?我在这里做了很多假设,但我认为您应该能够一起避免显式 lookup 函数。

对于这些选项,我认为将它们全部打包到一个散列中可能是最优雅的,如果您愿意,可以将其称为$sytem_options:

class foo (
  Optional[Hash] $system_options = {},
){

  # From your example, I'm not sure if there's any
  # content in this file if these options are not present
  # hence the if statement.

  if $system_options {
    file { '/etc/file.conf':
      ensure  => present,
      owner   => root,
      group   => root,
      mode    => '0644',
      content => template("${module_name}/file.conf.erb"),
    }
  } 
}

无论您使用 hiera 定位哪个层次结构...

---
foo::system_options:
  mem_limit: 1G

在您的 file.conf.erb 中假定本地作用域:

<% if @system_options['mem_limit'] -%>
limit_memory=<%= @system_options['mem_limit'] %> 
<% end -%>

<% if @system_options['cpu_timeout'] -%>
cpu_timeout=<%= @system_options['cpu_timeout'] %> 
<% end -%>

<% if @system_options['threads'] -%>
multiple_threads=true
num_threads=<%= @system_options['threads'] %> 
<% end -%>

关于ruby - 检查 Hiera 值是否存在,如果存在,则将每个值分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51311059/

相关文章:

ruby - Grep 文件并在 ruby​​ 中提取值

yaml - 有没有更好的方法来处理 yaml 的双引号 hiera

Puppet 编写一个在查找成功时运行的命令?

ruby-on-rails - rails mongoid 清晰的标准

ruby-on-rails - 错误运行 rails 生成设计 :install

ruby - 从自定义提供程序访问 Puppet 内置变量

apache - Puppet:无法按名称找到默认节点

centos - 使用 puppet 将 exclude 添加到现有的 yum repo 配置

puppet - 希拉如何运作?

ruby-on-rails - 如何在 rspec 中跳过 x 次测试