Cloudevelops The Official Cloudevelops Blog

Creating a simple Puppet fact

Basically puppet fact is just ruby script that is executed by puppet and returns certain value depending on which host it is. So creating own facts is not so hard and can be useful when you want to select specific hosts with some similar attributes.

Let’s look at example of facter fact that shows file system type that current mount point is using:

 1 require 'facter'
 3 Facter.add("rootfs_type", :timeout => 120) do
 4   confine :osfamily => "Debian"
 6   setcode do
 7     dfoutput = Facter::Util::Resolution.exec('df -Tl /')
 8     rootfs_type = dfoutput.split(/\n+/)[1].split(" ")[1]
 9     rootfs_type
10   end
12 end

1: require 'facter' - used to add some facter specific functionality to our facter ruby script

3: Facter.add - used to define fact name with some additional parameters (like execution timeout)

4: we can limit fact execution to some specific OS family, release, codename, etc. with confine directive

6: setcode - statement is used to determine the fact’s value;

7: our simple fact use Facter::Util::Resolution.exec function that executes df system command and which is source of our informantion about filesystem type

8: code can contain or do anything that ruby can

Fetching other facts is also possible - with Facter.value(<facter name>) function.

Custom facts are stored at lib/facter/ directory of puppet module and are added to hosts with puppet installed during next puppetizing.

After all done we can check if our fact is available on puppetized host:

sudo facter -p rootfs_type

After that fact can be used as ordinary variable at any puppet module. For example we can create cron job that is created only on hosts with btrfs file system that relocate chunks with less than 5% of usage :

 1 if $::rootfs_type == 'btrfs' {
 2     cron {
 3       'btrfs-balance':
 4         ensure   => present,
 5         command  => '/sbin/btrfs fi balance start -dusage=5 /',
 6         user     => 'root',
 7         hour     => '0',
 8         minute   => '0',
 9         monthday => '1',
10     }
11   }

More about puppet facts:

Puppet Custom Facts Walkthrough

Share this article: