Search code examples
puppethiera

Puppet write a command that runs if lookup succeeds?


I have the following in my puppet manifest and it works:

package {
  lookup('latest_packages'): ensure => latest,
}

Now we are adding another option to ensure absent, this lookup can contain values but it can also be non-existent. When the hiera data doesn't exists it causes my manifest to fail.

package {
  lookup('latest_packages'): ensure => absent,
}

If that data doesn't exists I get back this on the agent:

Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Function lookup() did not find a value for the name 'removed_packages' on node dev-596e89d2fe5e08410003f2e6

How can I set this up to run only if lookup finds values? Do I need to wrap the package function in a conditional?


Solution

  • The fastest path to success here is probably to make use of the default value argument to the lookup function. We can also add in the data type and merge behavior just to help focus the lookup:

    lookup('removed_packages', Array[String], 'unique', [])
    

    Also, based on your error message I am guessing the key you are looking up is actually removed_packages for the absent case.

    • Array[String]: data type that guarantees your package list will be an array of strings. This helps protect against undesired inputs to this resource from your data.

    • unique: Combines any number of arrays and scalar values to return a merged and flattened array with all duplicate values removed. This is nice and efficient.

    • []: the default value, so that for a nonexistent removed_packages key the resource will resolve to:

      package { []: ensure => absent }

      which will be a benign and successfully compiled resource in your catalog.