【问题标题】:Check Hiera values exist, if so, assign each to variable检查 Hiera 值是否存在,如果存在,请将每个值分配给变量
【发布时间】:2018-12-21 00:06:49
【问题描述】:

我有一个可以在 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")
}

文件.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')
}

【问题讨论】:

    标签: ruby puppet hiera


    【解决方案1】:

    为什么不使用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 -%>
    

    【讨论】:

    • 谢谢你...它解决了我最初的问题(回想起来,我没有解释 100%)。如果哈希是在类 foo 中声明的,我可以在那里访问它......但是如果我还需要从子类访问相同的 hiera 哈希,那么语法会如何变化,即:声明了 file.conf.erb在类 foo::bar{} 中,所以 @system_options['mem_limit'] 不起作用。我猜我要么需要在类 foo::bar{} 中放置一些东西,要么稍微不同的 @system_options['mem_limit'] 在 .erb(或两者)中不起作用。这将 100% 解决我的问题,非常感谢! :)
    • 没关系... class foo::bar inherits foo {} 解决了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 2021-01-18
    • 2013-03-05
    • 1970-01-01
    • 2014-05-22
    • 2023-03-13
    相关资源
    最近更新 更多