DEV Community

Harsh Mishra
Harsh Mishra

Posted on

Ansible Facts: Complete Guide for Beginners

Ansible Facts: Complete Guide

Ansible facts are pieces of information about the managed nodes (hosts) that are gathered by Ansible during the execution of a playbook or an ad hoc command. These facts provide critical details about the system's state, such as IP addresses, operating system details, hardware configurations, and more. Ansible facts are often used to make playbooks dynamic and adaptable to different environments.

This guide will cover everything you need to know about Ansible facts, from basic usage to advanced techniques.


1. What are Ansible Facts?

Ansible facts are variables collected by the setup module. These variables describe the state of a managed node and are automatically made available during a playbook run or ad hoc execution. Some examples of facts include:

  • System hostname
  • IP address and network interfaces
  • Operating system details
  • CPU and memory information
  • Disk space and partitions

Key Features of Facts:

  • Automatically Collected: Facts are gathered by default before running any tasks.
  • Accessible as Variables: Facts can be accessed like any other variable in Ansible.
  • Customizable: You can control which facts are gathered or even define custom facts.

2. Gathering Facts

2.1 Automatic Fact Gathering

Ansible gathers facts by default at the beginning of a playbook run. The gathered facts are stored as variables under the ansible_facts namespace.

Example:

- name: Gather and display facts
  hosts: all
  tasks:
    - name: Display the hostname
      debug:
        msg: "The hostname is {{ ansible_facts['hostname'] }}"
Enter fullscreen mode Exit fullscreen mode

2.2 Controlling Fact Gathering

Fact gathering can be controlled using the gather_facts keyword in your playbook.

Enable or Disable Fact Gathering:

# Disable fact gathering
- name: Run tasks without gathering facts
  hosts: all
  gather_facts: no
  tasks:
    - name: Ping the host
      ping:
Enter fullscreen mode Exit fullscreen mode

2.3 Gathering Facts Manually

You can explicitly invoke the setup module to gather facts during a playbook run or an ad hoc command.

Example:

- name: Gather facts manually
  hosts: all
  gather_facts: no
  tasks:
    - name: Collect facts
      ansible.builtin.setup:
Enter fullscreen mode Exit fullscreen mode

Using an Ad Hoc Command:

ansible all -m ansible.builtin.setup
Enter fullscreen mode Exit fullscreen mode

3. Accessing Facts

Ansible facts are stored as nested variables and can be accessed using their keys.

3.1 Using Facts in Playbooks

Facts are available as variables in the ansible_facts dictionary.

Example:

- name: Use facts in tasks
  hosts: all
  tasks:
    - name: Display the operating system
      debug:
        msg: "The operating system is {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}"
Enter fullscreen mode Exit fullscreen mode

3.2 Commonly Used Facts

Here are some commonly accessed facts:

  • System Information:
    • ansible_facts['hostname']: Hostname of the system.
    • ansible_facts['fqdn']: Fully Qualified Domain Name.
  • Network Information:
    • ansible_facts['default_ipv4']['address']: Default IPv4 address.
    • ansible_facts['interfaces']: List of network interfaces.
  • Operating System:
    • ansible_facts['distribution']: OS distribution (e.g., Ubuntu, CentOS).
    • ansible_facts['os_family']: OS family (e.g., Debian, RedHat).
  • Hardware Information:
    • ansible_facts['processor']: List of processors.
    • ansible_facts['memtotal_mb']: Total memory in MB.

4. Limiting Gathered Facts

4.1 Limiting Facts with Filters

You can limit the facts gathered by the setup module using filters.

Example: Gathering Specific Facts

- name: Gather only network facts
  hosts: all
  tasks:
    - name: Gather network facts
      ansible.builtin.setup:
        filter: ansible_default_ipv4
Enter fullscreen mode Exit fullscreen mode

Example: Excluding Specific Facts

- name: Exclude specific facts
  hosts: all
  tasks:
    - name: Exclude memory-related facts
      ansible.builtin.setup:
        filter: "!ansible_mem*"
Enter fullscreen mode Exit fullscreen mode

4.2 Speeding Up Fact Gathering

By limiting the gathered facts, you can significantly reduce playbook runtime in large environments.


5. Custom Facts

Custom facts allow you to define your own variables for use in playbooks. These facts are stored in JSON or INI format on the managed node.

5.1 Creating Custom Facts

Location for Custom Facts:

Place your custom fact files in the /etc/ansible/facts.d/ directory on the managed node.

Example: Custom Fact in JSON

Create a file /etc/ansible/facts.d/custom_facts.json with the following content:

{
  "my_custom_fact": "Hello, Ansible!",
  "env": "production"
}
Enter fullscreen mode Exit fullscreen mode

Example: Custom Fact in INI

Create a file /etc/ansible/facts.d/custom_facts.ini with the following content:

[general]
my_custom_fact = Hello, Ansible!
env = production
Enter fullscreen mode Exit fullscreen mode

5.2 Accessing Custom Facts

Custom facts are automatically included in the ansible_facts namespace.

- name: Display custom facts
  hosts: all
  tasks:
    - name: Show custom facts
      debug:
        msg: "My custom fact is {{ ansible_facts['my_custom_fact'] }}"
Enter fullscreen mode Exit fullscreen mode

6. Using Facts Dynamically

Ansible facts are particularly useful when you need to write dynamic playbooks. You can use facts to conditionally execute tasks or templates.

6.1 Conditional Tasks with Facts

- name: Install packages based on OS
  hosts: all
  tasks:
    - name: Install Apache on Debian
      apt:
        name: apache2
        state: present
      when: ansible_facts['os_family'] == "Debian"

    - name: Install Apache on RedHat
      yum:
        name: httpd
        state: present
      when: ansible_facts['os_family'] == "RedHat"
Enter fullscreen mode Exit fullscreen mode

6.2 Templates with Facts

Facts can be used in Jinja2 templates to generate configuration files dynamically.

Template Example (nginx.conf.j2):

server {
    listen {{ ansible_facts['default_ipv4']['address'] }};
    server_name {{ ansible_facts['fqdn'] }};
}
Enter fullscreen mode Exit fullscreen mode

Playbook Example:

- name: Use facts in a template
  hosts: all
  tasks:
    - name: Generate nginx config
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
Enter fullscreen mode Exit fullscreen mode

7. Fact Caching

Ansible supports caching facts to avoid gathering them repeatedly, which can improve performance in large environments.

7.1 Enabling Fact Caching

To enable fact caching, update your ansible.cfg:

[defaults]
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_facts
Enter fullscreen mode Exit fullscreen mode

7.2 Using Cached Facts

When fact caching is enabled, Ansible will store the gathered facts in the specified location and reuse them in subsequent runs.


8. Debugging Facts

To debug or inspect all gathered facts, you can use the debug module.

- name: Display all facts
  hosts: all
  tasks:
    - name: Show all facts
      debug:
        var: ansible_facts
Enter fullscreen mode Exit fullscreen mode

For a more concise output:

- name: Display specific fact
  hosts: all
  tasks:
    - name: Show hostname
      debug:
        msg: "Hostname is {{ ansible_facts['hostname'] }}"
Enter fullscreen mode Exit fullscreen mode

9. Best Practices for Working with Facts

  1. Limit Fact Gathering: Use filters to gather only the facts you need to improve performance.
  2. Use Namespaced Access: Always use ansible_facts['fact_name'] to avoid conflicts with other variables.
  3. Cache Facts: Enable fact caching in environments with many hosts or long playbook runs.
  4. Leverage Custom Facts: Use custom facts for environment-specific variables.
  5. Debug Facts: Use the debug module to inspect and validate facts during development.

10. Conclusion

Ansible facts are a powerful feature that enables dynamic playbook execution and provides a wealth of system information. By understanding and leveraging facts effectively, you can make your Ansible automation workflows more flexible, efficient, and adaptable to various environments.

Key Takeaways:

  • Facts are automatically collected and stored in the ansible_facts dictionary.
  • You can control fact gathering and limit it for performance optimization.
  • Custom facts allow you to define your own variables for specific use cases.
  • Fact caching can improve performance in large-scale deployments.
  • Facts can be used dynamically in tasks, templates, and conditionals to create robust playbooks.

By mastering Ansible facts, you'll have a versatile tool at your disposal for writing powerful and adaptable automation workflows.

Top comments (0)