Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Facts and Templates

Custom and External Facts

Extend Facter with custom Ruby facts, executable and text external facts, and facts.d files. Learn pluginsync, fact precedence, caching and how to avoid slow facts.

The built-in facts cover hardware and operating system, but your organization has its own questions. Which datacenter is this machine in? Which application version is deployed? Is the node part of the payment-card network? Puppet lets you answer such questions with custom facts, which are small programs or data files that Facter runs on every node.

There are two ways to add a fact: write a custom fact in Ruby and ship it inside a module, or drop an external fact (a text file or an executable) into a facts.d directory. This lesson shows both, explains how they reach the nodes, and warns about the performance trap that catches most beginners. The runnable blocks are JavaScript stand-ins that mimic what Facter does when it loads those files.

Custom facts in Ruby

A custom fact lives in a module at lib/facter/<name>.rb. Puppet copies everything under lib/ from modules to the agent at the start of each run, a feature called pluginsync. Because the agent receives the new fact code before it collects facts, a freshly written fact is usually available on the first run after you deploy the module.

Ruby
# modules/site_facts/lib/facter/datacenter.rb
Facter.add(:datacenter) do
  setcode do
    # Derive the datacenter from the host name, e.g. web1.fra.example.com
    hostname = Facter.value(:networking)['fqdn'].to_s
    hostname.split('.')[1] || 'unknown'
  end
end

Points to notice:

  • Facter.add(:name) declares the fact; setcode holds the code that returns its value.
  • Use Facter.value(:other_fact) to depend on another fact. Facter works out the order for you.
  • Return a plain value, an array or a hash. A hash becomes a structured fact and is read in manifests as $facts['datacenter']['region'].
  • Return nil when you cannot determine the value. The fact is then simply absent.

If you want a command's output, use Facter::Core::Execution.execute('cmd') rather than backticks. It handles missing commands and timeouts more gracefully.

Several resolutions and weights

A fact can have more than one Facter.add block. Facter tries them from the highest weight to the lowest, and the first one that returns a value wins. A confine line restricts a block to certain platforms:

Ruby
Facter.add(:package_manager) do
  confine osfamily: 'Debian'
  setcode { 'apt' }
end

Facter.add(:package_manager) do
  confine osfamily: 'RedHat'
  setcode { 'dnf' }
end

External facts

Not everyone wants to write Ruby. External facts let you use any language. Put a file into the facts directory on the node, or ship it from a module in facts.d/:

  • Linux and Unix: /etc/puppetlabs/facter/facts.d/
  • Windows: C:\ProgramData\PuppetLabs\facter\facts.d\

Facter reads three file types:

Type Example How it works
Text .txt role=webserver One key=value per line
Structured .yaml / .json tier: gold Parsed as data, may be nested
Executable a shell or Python script Run; it prints key=value lines or JSON/YAML

An executable fact must be marked executable and must print its facts to standard output. A tiny example in Bash:

Terminal
#!/bin/bash
# /etc/puppetlabs/facter/facts.d/disk_free.sh
echo "root_free_percent=$(df --output=pcent / | tail -1 | tr -dc '0-9')"

Because the facts directory is a plain directory, you can manage it with Puppet itself. That is a common pattern: a profile writes role=webserver into facts.d so that later runs and other tools know the role.

PUPPET
file { '/etc/puppetlabs/facter/facts.d/role.txt':
  ensure  => file,
  content => "role=webserver\n",
}

Notice the chicken-and-egg problem: the new fact only appears on the next run, because facts are collected before the catalog is applied.

Precedence and caching

When two sources define the same name, Facter picks by weight. Custom Ruby facts have a default weight of 0 and external facts are normally higher, so an external fact overrides a custom fact of the same name. To avoid confusion, give every fact a unique, prefixed name such as acme_datacenter.

Facts run on every Puppet run, usually every 30 minutes. A slow fact multiplies across your fleet. Two controls help:

  • Set a timeout on a resolution so a hung command cannot block the run.
  • Use the Facter cache (facter.conf, ttls) for facts that rarely change and are expensive to compute.

The first rule of custom facts: keep them fast and read-only. A fact must never change the system. If it needs a network call, cache the result or reconsider.

Stand-ins: how Facter resolves facts

The first block imitates the weight-and-confine logic of Ruby resolutions. The second parses the text format of an external fact file. Both are JavaScript stand-ins that illustrate the algorithm; they are not Facter.

JS Stand-in: resolutions with confine and weight

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: parse external fact files

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second example shows a real danger: two files defined app_version and one silently won. Real Facter has its own precedence rules, so unique names are the safe cure.

flowchart LR
  M["Module lib/facter/*.rb"] -->|pluginsync| A["Agent"]
  X["facts.d files and scripts"] --> A
  A --> F["Facter merges all facts"]
  F --> S["Facts sent to server"]

Custom facts arrive by pluginsync; external facts are already on the node.

When a fact is the wrong tool

If the value is a decision rather than an observation, put it in Hiera. "This node is in the Frankfurt datacenter" is better derived from the hostname by a fact, but "Frankfurt uses ntp.fra.example.com" belongs in data. Facts report; data decides. See Profiles with Hiera and Parameters.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does a custom Ruby fact live inside a module?

    Everything under lib/ is synchronized to agents by pluginsync; Facter loads facts from lib/facter.
  2. 2. You manage /etc/puppetlabs/facter/facts.d/role.txt with a file resource. When can manifests see the new fact?

    Facter runs first, so a fact created during the apply phase appears on the following run.
  3. 3. Which is NOT an external fact format?

    Manifests are Puppet code, not fact sources. External facts are text, structured data or executables.
  4. 4. What is the main performance rule for custom facts?

    Slow facts delay every agent run, and facts must never change the system.

Summary

  • Custom facts are Ruby files in lib/facter, distributed by pluginsync; external facts are text, YAML/JSON or executables in facts.d.
  • Use confine, weight and Facter.value to build robust resolutions.
  • Give facts unique prefixed names; duplicates resolve by weight and are confusing.
  • Keep facts quick and read-only; use timeouts and the cache.
  • A fact reports an observation; configuration decisions belong in Hiera.

Next: EPP Templates