BacklogZero®

Ansible in a Minute · Ansible Core ·

Load custom facts then use them in when

Short answer

Set a custom fact first, then use that value in when so later tasks can skip or run.

Subscribe for updates

Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.

By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.

Request

set site_id to 1234 then print only when site_id equals 1234

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
- name: Load a custom fact then use it in when
  hosts: all
  gather_facts: false
  tasks:
    - name: Set a site-specific custom fact
      ansible.builtin.set_fact:
        site_id: "1234"

    - name: Print when the custom fact matches
      ansible.builtin.debug:
        msg: "site_id is 1234"
      when: site_id == "1234"

How it works

Load your own facts before any task that depends on them. set_fact stores site_id for later tasks. when tests that value without curly braces. A custom facts module at the top of the task list works the same way.

When to use it

  • Gathering site-specific data before a conditional install
  • Skipping tasks until a custom fact exists

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-28

Notes

Put the fact-loading task first. A later when cannot read a fact that does not exist yet. For facts that must persist on the host across plays, use facts.d instead of set_fact.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today →

Related guides

← Back to Ansible in a Minute

Load custom facts then use them in when · Level Up Labs