DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

How to Access System Information Facts in Ansible Playbooks

Use the ansible_facts dictionary to read system information in Ansible playbooks. This guide covers gathering, subsets, conditions, templates, ad hoc inspection and migration away from deprecated injected variables.
WorldAnsible Playbooks Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read host facts from the ansible_facts dictionary, for example ansible_facts['distribution'] or ansible_facts['os_family']. Ansible normally gathers these facts at the start of each play, so most playbooks can use them immediately. Avoid older bare variables such as ansible_distribution: they depend on fact-variable injection, generate deprecation warnings, and are scheduled to stop being injected by default in a future ansible-core release.

What Ansible facts are and when they exist

Ansible facts are variables collected from a managed host. They describe operating-system identity, kernel and architecture details, network interfaces, hardware, virtualisation and other properties exposed by the fact-collection module. Facts belong to the host on which they were gathered, so a play can make decisions per server instead of assuming every machine is identical.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The ansible.builtin.gather_facts action is part of ansible-core. In a normal play, Ansible invokes it automatically before the first task unless the play sets gather_facts: false. The action uses ansible.builtin.setup as its default fact module. The resulting data is stored in the ansible_facts dictionary for that host.

Fact collection happens once per play unless you explicitly run the gather action again. If a later task changes the host, the original values remain in memory until facts are gathered again. A second gather is useful after an operating-system change, network reconfiguration or package operation whose result must be detected in the same play.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

The supported access syntax

Use dictionary notation and the fact name without the historical ansible_ prefix:

- name: Show the operating system family
  ansible.builtin.debug:
    msg: "{{ ansible_facts['os_family'] }}"

- name: Show the distribution release
  ansible.builtin.debug:
    msg: "{{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}"

Both single and double quotes are valid inside the Jinja expression. Bracket notation is preferable because it makes the dictionary boundary explicit and works consistently when a key contains characters that are awkward in dotted notation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Purpose Expression Important detail
Operating-system name ansible_facts['system'] Reports the kernel system family, such as Linux or a platform-specific value.
Distribution family ansible_facts['os_family'] Useful for broad branching, such as Debian-family versus RedHat-family systems.
Distribution name ansible_facts['distribution'] Identifies the distribution reported by the host.
Distribution release ansible_facts['distribution_version'] Keep it as a value supplied by the host; compare versions deliberately rather than as arbitrary strings.
Kernel release ansible_facts['kernel'] Describes the running kernel version.
Machine architecture ansible_facts['architecture'] Use it when selecting architecture-specific packages or binaries.
Host name ansible_facts['hostname'] The host name collected from the managed node.
Fully qualified name ansible_facts['fqdn'] May depend on the node’s DNS and host-name configuration.
Default IPv4 address ansible_facts['default_ipv4']['address'] Nested keys must be addressed through the dictionary as well.
All interfaces ansible_facts['interfaces'] Returns the interface names; detailed data is under interface-specific fact keys.

The exact key set varies by platform and by the subsets you collect. Test a key on the operating systems in your inventory before making it mandatory in a role.

Use facts in tasks, conditions and templates

Print or inspect a value

- name: Display selected facts
  ansible.builtin.debug:
    msg:
      distribution: "{{ ansible_facts['distribution'] | default('unknown') }}"
      family: "{{ ansible_facts['os_family'] | default('unknown') }}"
      architecture: "{{ ansible_facts['architecture'] | default('unknown') }}"

The default filter prevents a template failure when a fact is unavailable. Use it for optional data, not to conceal a prerequisite that the play cannot safely operate without.

Branch on an operating-system family

- name: Install an Apache-family package
  ansible.builtin.package:
    name: httpd
    state: present
  when: ansible_facts['os_family'] == 'RedHat'

- name: Install a Debian-family package
  ansible.builtin.package:
    name: apache2
    state: present
  when: ansible_facts['os_family'] == 'Debian'

Prefer the broadest fact that answers the decision. A family check generally survives distribution derivatives better than a list of individual distribution names. If a package name or behaviour genuinely differs by release, add a narrower condition after the family decision.

Select a variable instead of duplicating tasks

- name: Select the service package name
  ansible.builtin.set_fact:
    web_package: >-
      {{ 'httpd' if ansible_facts['os_family'] == 'RedHat' else 'apache2' }}

- name: Install the selected package
  ansible.builtin.package:
    name: "{{ web_package }}"
    state: present

This pattern keeps the operation in one task. Add an explicit failure for unsupported families when silently choosing a default would be dangerous.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Render facts in a template

# templates/node-info.conf.j2
OS={{ ansible_facts['distribution'] | default('unknown') }}
OS_VERSION={{ ansible_facts['distribution_version'] | default('unknown') }}
ARCH={{ ansible_facts['architecture'] | default('unknown') }}
- name: Write host information
  ansible.builtin.template:
    src: node-info.conf.j2
    dest: /etc/node-info.conf
    mode: '0644'

Facts are evaluated for each target host while the template is rendered, so the same task can safely write host-specific values across a mixed inventory.

Use nested and list data carefully

- name: Show the default interface address when available
  ansible.builtin.debug:
    var: ansible_facts['default_ipv4']['address']
  when:
    - ansible_facts['default_ipv4'] is defined
    - ansible_facts['default_ipv4']['address'] is defined

Guard nested access one level at a time. Checking only the final expression can still fail while Ansible evaluates a missing parent dictionary.

Control whether and how facts are gathered

Skip collection for a play

- name: Run tasks that do not need host facts
  hosts: routers
  gather_facts: false
  tasks:
    - name: Run a command using only inventory variables
      ansible.builtin.command: /usr/local/bin/router-check

Skipping collection reduces startup work, but every fact reference in that play must then be removed, replaced with an inventory value, or supplied by another task. A common failure after setting gather_facts: false is an undefined-variable error from a task that previously relied on automatic setup.

Gather facts explicitly

- name: Refresh facts after a host change
  ansible.builtin.gather_facts:

- name: Use the refreshed distribution value
  ansible.builtin.debug:
    msg: "{{ ansible_facts['distribution'] }}"

Use the fully qualified collection name, ansible.builtin.gather_facts, in new playbooks. The action normally invokes ansible.builtin.setup. Calling it explicitly is also useful in a play that disabled automatic gathering and later reaches a task that needs system information.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Limit the collected subsets

The setup fact module supports subsets so a play can request only categories it needs. For example, a play may request networking or hardware information rather than the full default set:

- name: Gather only network facts
  ansible.builtin.gather_facts:
    gather_subset:
      - network

Subset names and available data can vary with ansible-core and the managed platform. Verify the result on your target systems, and do not assume that a reduced subset contains unrelated keys such as distribution details.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Choose parallel or serial fact-module execution

The gather action can run fact modules in parallel or serially. Parallel execution can shorten collection when several fact modules are involved; serial execution gives a deterministic merge order when modules contribute overlapping data. Use the action’s parallel option when that ordering or performance trade-off matters, and test the selected mode with the fact modules enabled in your environment.

Inspect facts without writing a playbook

For an ad hoc dump, run the fully qualified gather action against the inventory:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ansible all -m ansible.builtin.gather_facts --tree /tmp/facts

Ansible writes each host’s collected facts to a file beneath /tmp/facts. This is useful for discovering the actual key names on a new operating system, checking whether a subset was collected, and comparing hosts before adding a condition to a role. Treat the output as host information: protect the directory if your fact set includes data that should not be broadly readable.

To inspect values during a play, use the debug module rather than printing the entire dictionary:

- name: Inspect the complete fact dictionary while developing
  ansible.builtin.debug:
    var: ansible_facts

Full dumps can be very large. Remove or narrow this task after troubleshooting so normal logs contain only the values operators need.

Why bare variables such as ansible_distribution are being retired

Historically, Ansible could expose the same fact in two places: inside ansible_facts and as a top-level variable whose name started with ansible_. Thus, ansible_distribution corresponded to ansible_facts['distribution']. The duplicate top-level form is controlled by the INJECT_FACTS_AS_VARS setting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

That injection setting currently defaults to enabled in ansible-core, but the default is deprecated. Ansible-core 2.20 and later report deprecation warnings when playbooks rely on injected fact variables. The planned ansible-core 2.24 change is to make injection disabled by default; the exact release timing can change, so treat 2.24 as a stated plan rather than a guaranteed date.

Code that reads ansible_facts['distribution'] does not depend on injection. Code that reads ansible_distribution can fail as soon as injection is disabled, even though fact gathering itself still works.

Legacy form Dictionary form Recommendation
ansible_distribution ansible_facts['distribution'] Replace the legacy name.
ansible_os_family ansible_facts['os_family'] Replace the legacy name.
ansible_system ansible_facts['system'] Do not add the ansible_ prefix inside the dictionary.

A common migration mistake is writing ansible_facts['ansible_system']. That key is normally wrong because the prefix is removed inside the dictionary.

Configuration during a transition

If an older role cannot yet be migrated, the setting can be controlled in ansible.cfg under the [defaults] section:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
[defaults]
inject_facts_as_vars = True

The equivalent environment-variable form is version-dependent; check the configuration dump for the spelling accepted by the ansible-core version you run. Keeping injection enabled is only a compatibility bridge, not a fix for new code. Test your playbooks with injection disabled before upgrading so failures appear in a controlled environment.

Special case: variables loaded by community.sops

The porting guidance notes a known caveat for community.sops.load_vars: that plugin can emit repeated injection warnings because its current variable-setting path lacks an alternative in some versions. The guidance specifically advises not to mechanically convert SOPS-loaded variables to ansible_facts; distinguish those plugin variables from facts gathered by setup and follow the plugin’s compatibility guidance.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

A migration procedure that catches hidden dependencies

  1. Search all playbooks, roles and templates. Look for names beginning with ansible_, including references in when clauses, handlers, defaults, task names and Jinja templates.
  2. Map each name to its dictionary key. Remove the leading ansible_ when moving the value under ansible_facts. For example, change ansible_distribution to ansible_facts['distribution'].
  3. Check nested structures. Convert expressions such as interface or default-address references one level at a time and add guards for optional parents.
  4. Run with injection disabled. Use the configuration option for your ansible-core version, execute representative inventories, and treat undefined-variable errors as migration findings rather than restoring the old syntax.
  5. Remove temporary compatibility settings. Once roles and templates use the dictionary, allowing injection to remain enabled only preserves an unnecessary dependency.
  6. Retest plays that skip gathering. A corrected expression still cannot work in a play with gather_facts: false unless facts are gathered later or supplied another way.

Troubleshoot “facts are not showing” problems

The dictionary is undefined

Confirm that the play has not set gather_facts: false. If it has, add ansible.builtin.gather_facts before the first fact-dependent task or remove the fact dependency. Also verify that the target is a normal managed host and that connection and privilege settings allow the setup module to run.

A key is missing

Print ansible_facts with the debug module or inspect an ad hoc dump to learn the keys actually returned by that host. The key may belong to a subset you did not collect, may be unavailable on that platform, or may have a different value shape than expected. Use default and explicit is defined checks for genuinely optional information.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The play fails after a system change

Facts represent the state observed at collection time. If a task changes the operating system, hostname, interface configuration or another fact source, run ansible.builtin.gather_facts again before reading the new value.

The old variable works but emits warnings

That behaviour indicates injected fact variables are still enabled. Replace the bare name with the corresponding ansible_facts key, then test with injection disabled. Do not suppress the warning as a long-term solution.

A condition behaves differently across hosts

Display the exact values and types used by the condition. Distribution names and versions are host-reported data, and spelling or formatting can differ. Prefer os_family for a broad branch, normalize values only when necessary, and keep release-specific comparisons explicit.

Practical design rules for reliable fact use

  • Use ansible_facts['key'] in all new tasks, roles and templates.
  • Use fully qualified module names such as ansible.builtin.gather_facts and ansible.builtin.debug.
  • Gather only the subsets needed when startup time matters, and verify that required keys remain present.
  • Keep fact-dependent tasks together or document the point at which facts are refreshed.
  • Guard optional and nested values instead of assuming every platform returns the same structure.
  • Use inventory variables for deliberate operator choices; use facts for properties discovered from the host.
  • Test with INJECT_FACTS_AS_VARS disabled before adopting an ansible-core release that changes its default.

Minimal complete example

---
- name: Configure a web package by operating-system family
  hosts: web
  gather_facts: true
  tasks:
    - name: Select the package name
      ansible.builtin.set_fact:
        web_package: >-
          {{ 'httpd' if ansible_facts['os_family'] == 'RedHat' else 'apache2' }}

    - name: Stop on unsupported families
      ansible.builtin ansible.builtin.fail:
        msg: "Unsupported operating-system family: {{ ansible_facts['os_family'] }}"
      when: ansible_facts['os_family'] not in ['RedHat', 'Debian']

    - name: Install the web package
      ansible.builtin.package:
        name: "{{ web_package }}"
        state: present

    - name: Record host identity
      ansible.builtin.copy:
        dest: /etc/managed-host.txt
        content: |
          Distribution: {{ ansible_facts['distribution'] | default('unknown') }}
          Version: {{ ansible_facts['distribution_version'] | default('unknown') }}
          Architecture: {{ ansible_facts['architecture'] | default('unknown') }}
        mode: '0644'

Correct the module name in the failure task to ansible.builtin.fail when copying this example; the fully qualified name must not contain a duplicated namespace. The example otherwise demonstrates automatic gathering, dictionary access, guarded optional values and a family-based decision.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.