Puppet: Passing a hash of variables to a defined type

One of the more interesting challenges I had recently involved a bit of automation with regard to user creation. If you’ve ever tried to automate resource creation with either defined types or classes, the nuances of puppet can be a bit of a pain, but they can also be very powerful. Here’s an example of a defined type that can execute an arbitrary number of commands with any number of variables (We just happen to be importing certificates in this example):

First the defined type:

define import_certs($cert_path, $cert_name) {
  exec {"Import $cert_name":
    command => "/usr/bin/certutil -A -d /path/to/certificate/db -a -i ${cert_path} -t C,C,C -n \"${cert_name}\"",
  }
}

As you can see the type accepts 2 variables, $cert_path and $cert_name. Certutil requires a friendly name and this allows us to name our certificates appropriately. NOTE: that double quotes are required for variable interpolation (This bit me a couple of times). Now let’s take a look at how to pass a hash to this defined type so that we can import as many certificates as needed:

In your declaration, you end up creating a hash of hashes and pass the defined type the entire hash of hashes using “create_resources”:

$my_certificates = {
  certificate_file_1 => { cert_path => '/path/to/certificate/file', cert_name => 'Friendly Certificate Name' },
  certificate_file_2 => { cert_path => '/path/to/certificate/file', cert_name => 'Friendly Certificate Name' },
  certificate_file_n => { cert_path => '/path/to/certificate/file', cert_name => 'Friendly Certificate Name' },
}

create_resources(import_certs, $my_certificates)

As you can see, this is a quick and dirty way to shove a lot of certificates into a database (For a browser perhaps). Of course the limits are boundless, I know this will come in handy again in the future so I put it on <virtual> paper.

One thought on “Puppet: Passing a hash of variables to a defined type

  1. rowy

    thank you, this was very useful. have been assigning static smart params in my ENC (Foreman) but this allows a more dynamic approach.

Leave a Reply

Your email address will not be published. Required fields are marked *