How to order Puppet class execution

Figuring out how to order the execution of Puppet classes was kind of a nightmare, but the solution just required reading more documentation (doh!) and not relying on googles. In the end, it was pretty easy!

Within a Puppet class, you can order resource execution by using ‘before’, ‘require’, ‘subscribe’, etc. However, within classes, you can’t use ‘before’. For instance, this doesn’t work:

[Bad Code]
class { 'my_first_class': before => Class['my_second_class'], }

class { 'my_second_class': }

The order of these classes will still be randomized, and ‘my_first_class’ will be loaded second about 50% of the time.

Solution: Staging!

We will use Puppet stages in order to solve this problem. If you look at a puppet log message, you’ll see something like this:

notice: /Stage[main]/Web::Web_packages/Package[apache2-mpm-prefork=2.2.1*]/ensure: ensure changed 'purged' to 'present'

If you look at the ‘Stage’ following the notice, the stage is ‘main’. This is the default stage for all Puppet actions. We can use stages to ensure that blocks of code occur in the correct order.

Here is how our new code works:

class { 'my_first_class': }

stage { 'last':
 require => Stage['main'],
 }

class { 'my_second_class':
 stage => last,
 }

Boom! Now, ‘my_second_class’ is part of the ‘last’ stage which happens after the ‘main’ stage (‘require’ means to come after). It will be be created after ‘my_first_class’.

One thought on “How to order Puppet class execution

Leave a Reply