Resolving Ansible lookup() error with ansible_lsb.codename

Abstract: Resolve Ansible lookup errors for ansible_lsb.codename by explicitly gathering LSB facts using the setup module with a filter.

Created: 2026-10-09 by

The ansible_lsb.codename variable is not a native fact in modern Ansible releases, causing lookup errors when referenced directly. To resolve this, you must explicitly load the lsb_release facts using the setup module with the filter parameter set to *lsb*. This ensures the distribution codename data is available for your playbooks.

Understanding the Missing Fact

Ansible gathers system information through a process called fact gathering, which runs by default at the start of every playbook execution. Historically, certain platform-specific details were included in the standard fact set, but recent versions have optimized this process by reducing the number of facts collected by default. The ansible_lsb dictionary, which contains Linux Standard Base (LSB) information such as the distributor ID, description, release number, and codename, is one of these excluded facts.

When a playbook attempts to access ansible_lsb.codename without first ensuring those facts are loaded, Ansible returns an undefined variable error or a lookup failure. This is particularly common when migrating older playbooks to newer Ansible control nodes or when working in environments where minimal fact gathering is preferred for performance reasons. The error typically manifests as a fatal error during the task execution phase, preventing subsequent tasks from running.

Why It Was Removed

The removal of LSB facts from the default set was a deliberate design choice to improve playbook execution speed. Collecting LSB information requires executing external commands on the target host, which adds latency to every run. By excluding it by default, Ansible reduces overhead for users who do not need distribution-specific details. However, this change breaks backward compatibility for scripts that relied on the implicit availability of these variables.

Solution: Explicitly Loading LSB Facts

The most robust way to fix this issue is to explicitly request the LSB facts within your playbook. You can achieve this by adding a dedicated task that uses the setup module with a filter. This approach is cleaner than modifying global configuration files and allows you to control exactly when and where the facts are gathered.

- name: Gather LSB facts
  ansible.builtin.setup:
    filter: "*lsb*"

This task should be placed early in your playbook, before any tasks that reference ansible_lsb.codename. Once executed, the fact becomes available for use in templates, conditionals, and other tasks. The filter syntax uses wildcards to match all facts containing "lsb" in their key names, ensuring that ansible_lsb.distrib_id, ansible_lsb.release, and ansible_lsb.codename are all populated.

Alternative: Using the lsb_release Module

If you prefer not to use the setup module, you can alternatively use the community.general.lsb_info module. This module is specifically designed to gather LSB information and stores the results in variables prefixed with lsb_ rather than ansible_lsb_. Note that this changes the variable name you must use in your playbook from ansible_lsb.codename to lsb.codename.

- name: Get LSB info
  community.general.lsb_info:
  register: lsb_result

- name: Display codename
  debug:
    msg: "The codename is {{ lsb_result.codename }}"

This method is useful if you only need LSB data and want to avoid the broader scope of the setup module. However, it requires the community.general collection to be installed on the control node. For most users, the setup module approach is simpler because it relies on built-in functionality.

Global Configuration Approach

If you frequently encounter this issue across many playbooks, you might consider configuring Ansible to always include LSB facts. This can be done by modifying the ansible.cfg file on your control node. Add the following line under the [defaults] section:

fact_caching_connection = /tmp/ansible_fact_cache
fact_filter = *lsb*

However, this is generally discouraged because it forces LSB fact collection for every single task, even those that do not need it. It also affects performance globally. A better practice is to handle fact gathering locally within specific plays where the data is required, keeping your playbooks modular and efficient.

Debugging Undefined Variables

If you are still experiencing issues after implementing the fix, verify that the facts are actually present. Use the debug module to print the entire ansible_lsb dictionary. This helps confirm whether the filter worked correctly and whether the target host supports LSB reporting. Some minimal container images or custom Linux distributions may not provide LSB information at all, in which case the variable will remain empty even after explicit gathering.

For more complex scripting challenges involving variable expansion and shell interactions, you may find our guide on troubleshooting bash script quoting issues helpful, as improper handling of these variables can lead to similar errors in shell tasks. See Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting for related context.

Best Practices for Distribution Detection

While fixing the immediate error is important, consider whether relying on ansible_lsb.codename is the best long-term strategy. Distribution codenames can vary between major versions of the same OS family. For example, Ubuntu 20.04 is "focal" and Ubuntu 22.04 is "jammy". If your playbook needs to handle multiple versions, hardcoding checks against specific codenames can become brittle.

Instead, consider using higher-level abstractions provided by Ansible. The ansible_distribution and ansible_distribution_version facts are more stable and widely supported. You can combine these with conditional logic to apply different configurations based on major version numbers rather than codenames. This makes your playbooks more resilient to minor updates and point releases.

Additionally, if you are managing RHEL-based systems, note that they often use different identification methods compared to Debian-based systems. Understanding these differences is crucial for writing cross-platform playbooks. Our article on troubleshooting RHEL 7 Ansible execution provides deeper insights into platform-specific behaviors. Read Troubleshooting Linux RHEL 7 to understand how fact gathering differs across distributions.

Frequently Asked Questions

What happens if I don't specify the filter?

If you do not specify the filter, Ansible will only gather the default set of facts, which excludes LSB information. Consequently, any attempt to access ansible_lsb.codename will result in an undefined variable error. You must explicitly request these facts to make them available.

Can I enable LSB facts globally for all hosts?

Yes, you can set fact_filter = *lsb* in your ansible.cfg file. However, this is not recommended because it increases execution time for every task on every host, even those that do not need LSB data. Localized gathering is more efficient.

Does this error occur on Windows hosts?

No, the ansible_lsb facts are specific to Linux systems. On Windows, Ansible gathers different facts related to the operating system, such as ansible_os_family and ansible_windows_system32_path. LSB facts are irrelevant for Windows targets.

How do I check if LSB facts are already loaded?

You can run a simple playbook task with the debug module to print {{ ansible_lsb }}. If the output shows a dictionary with keys like distrib_id and codename, the facts are loaded. If it prints nothing or an error, they are not available.

Is there a performance penalty for gathering LSB facts?

There is a small performance penalty because Ansible must execute the lsb_release command on the target host. However, this cost is negligible for most environments. The benefit of having accurate distribution information outweighs the minor increase in runtime.

What if my host doesn't support lsb_release?

If the target host does not have the lsb-release package installed or lacks LSB support, the fact gathering will fail or return empty values. In such cases, you may need to install the necessary packages or use alternative methods to identify the distribution, such as checking /etc/os-release directly.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More