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

Check Hiera values exist, if so, assign each to variable

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

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

清单:

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

file.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 -%>

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

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 -%>