Accessing facts from Puppet code

When you write Puppet code, you can access facts in two ways: with the $fact_name syntax, or with the $facts['fact_name'] hash.

Using the $fact_name syntax

Facts appear in Puppet as top-scope variables. They can be accessed in manifests as $fact_name.

For example:
if $osfamily == 'RedHat' { 
  # ...
}
Tip: When you code with this fact syntax, it's not immediately obvious that you're using a fact — someone reading your code needs to know which facts exist to guess that you're accessing a top-scope variable. To make your code easier for others to read, use the $::fact_name syntax as a hint, to show that it's accessing a top-scope variable.

Using the $facts['fact_name'] hash syntax

Alternatively, facts are structured in a $facts hash, and your manifest code can access them as $facts['fact_name']. The variable name $facts is reserved, so local scopes cannot re-use it. Structured facts show up as a nested structure inside the $facts namespace, and can be accessed using Puppet's normal hash access syntax.

For example:
if $facts['os']['family'] == 'RedHat' {
  # ...
}

Accessing facts using this syntax makes for more readable and maintainable code, by making facts visibly distinct from other variables. It eliminates confusion that is possible when you use a local variable whose name happens to match that of a common fact.

Because of ambiguity with function invocation, the dot-separated access syntax that is available in Facter commands is not available with the $facts hash access syntax. However, you can instead use the fact function included in the stdlib module. Read more about it in the stdlib module README.

Improving performance by blocking or caching built-in facts

If Facter is slowing down your code, you can configure Facter to block or cache built-in facts. When a system has a lot of something — for example, mount points or disks — Facter can take a long time to collect the facts from each one. When this is a problem, you can speed up Facter’s collection by configuring these settings in the facter.conf file:
  • blocklist for blocking built-in facts you’re uninterested in.

  • ttls for caching built-in facts you don’t need retrieved frequently.