Guozhen AIGlobal AI field notes and model intelligence

English translation

Variables and Facts in Ansible

Published:

Category: Ansible Operations

Read time: 3 min

Reads: 0

Lesson #9Views are counted together with the original Chinese articleImages are preserved from the source page

AI Article Decision Snapshot

Turn the lesson into workflow, model, budget, and security checks before choosing tools.

Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.

Workflow fit

Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.

Model or tool decision

Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.

Budget and usage signal

Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.

Security and privacy review

Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.

In the previous article, we discussed Ansible’s Inventory file format and learned how to manage information about different hosts and host groups. In this article, we’ll dive deep into Ansible variables and facts—key concepts that empower you to handle data more flexibly when writing Playbooks. Mastering variables and facts is essential for effective automation and will significantly enhance your operational efficiency.

Basic Concepts of Variables

In Ansible, a variable is a named object used to store data, which can then be referenced and reused throughout a Playbook. Variables enable dynamic configuration wherever needed.

Defining Variables

Variables can be defined in multiple locations, including:

  • In the Inventory file — associating variables with individual hosts or groups
  • In a Playbook — using the vars keyword to declare global (play-scoped) variables
  • Within tasks — dynamically creating variables using the set_fact module

Example: Defining Variables in an Inventory File

Here’s an example Inventory file where a variable is assigned to a host:

[webservers]
web01 ansible_host=192.168.1.10 ansible_port=22 web_user=admin

In this example, web_user is a variable that can be referenced later in a Playbook.

Using Variables in Playbooks

Within a Playbook, variables are referenced using the {{ variable_name }} syntax. For instance:

- name: Deploy web server
  hosts: webservers
  vars:
    document_root: /var/www/html
  tasks:
    - name: Ensure document root directory exists
      file:
        path: "{{ document_root }}"
        state: directory
        owner: "{{ web_user }}"

Here, both document_root and web_user are variables. Their values are dynamically inserted into the task using double curly braces.

Ansible Facts

Ansible automatically gathers information about managed hosts before executing each Playbook. This collected information is called facts. Facts include details such as the operating system, IP addresses, CPU architecture, and more—dynamically discovered at runtime.

Accessing Facts

Facts are typically prefixed with ansible_ and can be accessed just like any other variable. You can explicitly gather facts using the setup module—or rely on automatic fact collection, which is enabled by default.

Example: Collecting and Displaying Facts

A Playbook snippet demonstrating explicit fact gathering and output:

- name: Collect and display facts
  hosts: all
  tasks:
    - name: Gather facts
      setup:

    - name: Print IP address
      debug:
        msg: "The IP address is {{ ansible_eth0.ipv4.address }}"

In this example, the setup module collects facts from the target host(s), and the debug module prints the IPv4 address associated with the eth0 interface.

Custom Facts

Beyond built-in facts, users can define their own custom facts. These are typically placed in /etc/ansible/facts.d/ as executable scripts or JSON files.

Example: Defining a Custom Fact

Suppose you create a file /etc/ansible/facts.d/custom.fact containing:

{
  "my_custom_fact": "hello world"
}

You can then reference it in a Playbook like so:

- name: Use custom fact
  hosts: all
  tasks:
    - name: Print custom fact
      debug:
        msg: "My custom fact is {{ ansible_local.my_custom_fact }}"

Note: Custom facts appear under the ansible_local namespace.

Summary

In this article, we explored Ansible variables and facts—two foundational concepts that bring flexibility and intelligence to automation workflows. Variables allow you to pass and reuse data across plays and tasks, while facts provide real-time, host-specific metadata without manual intervention. With these tools mastered, you’ll be well-equipped to write dynamic, maintainable, and scalable Playbooks.

In the next article, we’ll examine Playbook structure and syntax—helping you organize and author robust, production-ready automation logic. We hope this article has strengthened your understanding of Ansible’s core capabilities—and we look forward to seeing your achievements in infrastructure automation!

Apply This Lesson

Turn this article into AI software, model, API, and security decisions.

English Article FAQ

Use this article as evidence before choosing AI tools

How should I use this AI Tutorials article?

Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.

Is this English article different from the Chinese original?

The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.

What should I read after Variables and Facts in Ansible?

Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.

Can this article alone choose an AI product or model?

No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.

Continue

Keep reading from here

Browse English site

Reader Messages

Reader messages

Questions, corrections, extra sources, or hands-on results can be left here. No login is required.

Max 800 characters

To reduce spam, each message is checked for length, link count, and posting frequency.

0/800

Messages

0 messages
Loading messages...