简体   繁体   中英

How to check whether hash has a value for the key in puppet

I have a hash defined as below:

  Hash[String, String] $hashtest = { "abc" => "test1", "xyz" => "test2" },

I have String variable, I need to search for the given key in the hash and if a value is found, I need to assign that value to the variable "result" otherwise I need to assign a default value "test". How can I do this is in puppet? Or only way to do this is using if else condition?

It should be similar like this, but the below code is not working. Kindly correct me what I'm doing wrong. String $variable = $hashtest[$key]? { true => $hashtest[$key], false => "test" },

It would be really helpful if someone helps me with this thanks in advance.

I am assuming in your pseudocode you are intending to assign a value with a return from a selector, and not also providing a pseudocode for a ternary-like expression in Puppet. With that in mind, we can achieve this with something similar to Python:

String $variable = $key in $hashtest ? {
  true  => $hashtest[$key]
  false => "test"
}

Note that prior to Puppet 4 you would need the has_key? function (analogous to has_key Hash method in Ruby) from stdlib :

String $variable = has_key($hashtest, $key) ? {
  true  => $hashtest[$key]
  false => 'test'
}

In stdlib there is also a function roughly equivalent to a "null coalescing" operator in other languages (null being roughly equivalent to undef type in Puppet and nil in Ruby) that would provide a cleaner expression:

String $variable = pick($hashtest[$key], 'test')

Similar to the coalescing patterns in other languages, pick will return the first argument that is not undef or empty .

As well as matts answer you can also use the following

$variable = $hashtest[$key].lest || { 'test' }
$variable = ($key in $hashtest).bool2str($hashtest[$key], 'test')
$variable = $hashtest.has_key($key).bool2str($hashtest[$key], 'test')

All of these options are missing the most simple and powerful option that's been available from the core library since puppet 6; the get function .

The get function allows you specify a dot separated path of nested keys to look up as the first argument, and a default value for the second. By default, it will return undef if a value cannot be found, making it ideal for use in conditional expressions since undef is the only value in puppet that automatically converts to false . You can even pass a lambda to it to handle missing values.

In your case, the answer is as simple as $variable = $hashtest.get($key, 'test') or $variable = get($hashtest, $key, 'test') , though I personally find the first option easier to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM