[英]how to assign in ruby without checking each step if the values you assign exist
[英]Check Hiera values exist, if so, assign each to variable
我有一個可能在Hiera中為節點設置的選項列表; mem_limit,cpu_timeout,threads ...
如果它們確實存在,我需要將它們設置在清單中定義的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')
}
為什么不使用自動類參數查找 ? 我在這里做了很多假設,但我認為你應該能夠一起避免顯式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 -%>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.