Define databases in Hiera using exported resources in Puppet


I like to keep all information and attributes of a node in hiera, including application settings and databases. This makes it easy to find all the resources that belongs to one server or application.

We are running dedicated database servers for most of our applications, so to be able to define the database in the nodes hiera definition we are using exported resources.

This is basically how we configure our nodes:

  - application
  - psql
      - ''
    port: '80'
    database: 'example_com'
    server: 'sqlserver01.internal.dmz'
    user: 'user01'
    password: 'password'

The psql_database section creates a database, “example_com”, on sqlserver01.internal.dmz, with the user “user01” and the password “password”. Passwords are encrypted using eyaml, but I’m using clear text here for simplicity.

Client stuff

The psql module let’s you create a exported resource with the tag “sqlserver01.internal.dmz”. The server sqlserver01.internal.dmz are collecting all Postgresql::Server::Db resources with it’s own hostname. The tag could be anything, but we are using hostnames because it makes sense in our environment.

When the client includes the psql module, a create_resources statement is used to convert the hash into resources.

$database_client = hiera('psql_database', {})
create_resources('psql::def_node_database', $database_client)

psql::def_node_database defines the postgresql database using Puppetlabs’ postgresql module.

  @@postgresql::server::db {$database:
    user     => $user,
    password => postgresql_password($user, $password),
    tag      => $server,
    owner    => $user,

The resource will be created when puppet agent is executed and stored with the clients catalog in PuppetDB.

Database server stuff

The database server now needs to pick up the resources. sqlserver01.internal.dmz includes a class with the following code which creates the database:

class psql::server::collector {
  Postgresql::Server::Db <<| tag == "${fqdn}" |>>

With this you can define databases in hiera at any level in the hierarchy.