Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

puppet

hiera

I've got a list of options that might be set in Hiera for a node; mem_limit, cpu_timeout, threads...

If they do exist, I need them to be set in a Ruby template, defined in the manifest.

manifest:

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

I could put the following in the manifest for each option, but if I've got more than a dozen it looks really awful! Really hoping there's a nicer way to do this, but struggling to find an iterative way for a large number of possible options.

if lookup('mem_limit', undef, undef, undef) != undef {
   $mem_limit = lookup('mem_limit')
}
like image 295
Chris Avatar asked Dec 07 '25 05:12

Chris


1 Answers

Why not use automatic class parameter lookup? I'm making a lot of assumptions here, but I think you should be able to avoid the explicit lookup function all together.

For these options, I think it would probably be most elegant to pack them all into a hash, call it $sytem_options if you'd like:

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"),
    }
  } 
}

And whichever hierarchy you're targeting with hiera...

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

Assuming local scope in your 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 -%>
like image 77
burling Avatar answered Dec 08 '25 19:12

burling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!