AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Ansible include_vars: Load Variables from Files Dynamically (Complete Guide)

By Luca Berton · Published 2024-01-01 · Category: database-automation

How to use Ansible include_vars to load variables from YAML files at runtime. Dynamic OS-specific variables, directory loading, conditional includes.

Ansible include_vars: Load Variables from Files Dynamically (Complete Guide)

The ansible.builtin.include_vars module load variables from files dynamically. This guide covers all common use cases with practical playbook examples.

See also: Ansible set_fact: Create & Set Runtime Variables (Complete Guide)

Load from a Single File

- name: Load database credentials
  ansible.builtin.include_vars:
    file: vars/database.yml

- name: Load environment-specific vars ansible.builtin.include_vars: file: "vars/{{ env }}.yml"

Load from Directory

- name: Load all variable files from directory
  ansible.builtin.include_vars:
    dir: vars/
    extensions: ['yml', 'yaml']
    ignore_unknown_extensions: true

See also: ansible.builtin.set_fact Module: Set Variables Dynamically (Complete Guide)

OS-Specific Variables

- name: Load OS-specific variables
  ansible.builtin.include_vars: "{{ item }}"
  with_first_found:
    - "vars/{{ ansible_distribution }}-{{ ansible_distribution_major_version }}.yml"
    - "vars/{{ ansible_distribution }}.yml"
    - "vars/{{ ansible_os_family }}.yml"
    - vars/default.yml

Load into Named Variable

- name: Load config into specific variable
  ansible.builtin.include_vars:
    file: vars/app-config.yml
    name: app_config

- name: Use the loaded variable ansible.builtin.debug: msg: "Port: {{ app_config.port }}"

See also: Ansible Environment Variables: Set, Read & Manage env vars (Complete Guide)

FAQ

How do I load variables from a file in Ansible?

Use ansible.builtin.include_vars: file=vars/myfile.yml. Variables are loaded at runtime and available for all subsequent tasks. For static loading at parse time, use vars_files in the play.

What is the difference between include_vars and vars_files?

vars_files loads at play parse time (static). include_vars loads at task runtime (dynamic) — meaning it can use variables in the filename and be wrapped in conditionals or loops.

Conclusion

The ansible.builtin.include_vars module is a versatile tool for load variables from files dynamically. Use the examples above as starting points and adapt them to your infrastructure needs.

Related Articles

Ansible Variables GuideAnsible Facts Guide

Module Parameters Reference

| Parameter | Required | Default | Description | |---|---|---|---| | file | No | — | Path to a single YAML/JSON variables file | | dir | No | — | Path to a directory of variable files to load | | name | No | — | Assign loaded variables to a named dictionary | | extensions | No | ['yaml','yml','json'] | File extensions to load from a directory | | depth | No | 0 | Depth of directory recursion when using dir | | ignore_unknown_extensions | No | false | Ignore files with unknown extensions | | files_matching | No | — | Regex pattern to filter files in a directory | | ignore_files | No | — | List of file names to skip | | free-form | No | — | Path to a file (shorthand for file) |

Load Variables from a Single File

- name: Load database configuration
  ansible.builtin.include_vars:
    file: vars/database.yml

- name: Display loaded variable ansible.builtin.debug: msg: "DB host: {{ db_host }}, DB port: {{ db_port }}"

Load OS-Specific Variables

- name: Load OS-specific variables
  ansible.builtin.include_vars: "{{ item }}"
  with_first_found:
    - "vars/{{ ansible_distribution }}-{{ ansible_distribution_major_version }}.yml"
    - "vars/{{ ansible_distribution }}.yml"
    - "vars/{{ ansible_os_family }}.yml"
    - "vars/default.yml"

Load Variables into a Named Dictionary

- name: Load app config into namespace
  ansible.builtin.include_vars:
    file: vars/app-config.yml
    name: app_config

- name: Access namespaced variables ansible.builtin.debug: msg: "App port: {{ app_config.port }}, App env: {{ app_config.environment }}"

Load All Files from a Directory

- name: Load all variable files from directory
  ansible.builtin.include_vars:
    dir: vars/services/
    extensions:
      - yml
      - yaml

- name: Load only matching files ansible.builtin.include_vars: dir: vars/environments/ files_matching: "^{{ env_name }}.*\\.yml$"

Complete Playbook: Multi-Environment Deployment

---
- name: Deploy application with environment-specific config
  hosts: app_servers
  become: true

vars: env_name: "{{ lookup('env', 'DEPLOY_ENV') | default('staging') }}"

tasks: - name: Load base configuration ansible.builtin.include_vars: file: vars/base.yml

- name: Load environment-specific overrides ansible.builtin.include_vars: file: "vars/{{ env_name }}.yml"

- name: Load OS-specific settings ansible.builtin.include_vars: "{{ item }}" with_first_found: - files: - "vars/os/{{ ansible_distribution }}-{{ ansible_distribution_major_version }}.yml" - "vars/os/{{ ansible_os_family }}.yml" - "vars/os/default.yml"

- name: Load secrets from vault ansible.builtin.include_vars: file: "vars/vault/{{ env_name }}-secrets.yml"

- name: Display merged configuration ansible.builtin.debug: msg: | Environment: {{ env_name }} App version: {{ app_version }} DB host: {{ db_host }} Log level: {{ log_level }}

- name: Deploy application template ansible.builtin.template: src: app.conf.j2 dest: /etc/app/app.conf owner: root group: root mode: "0640"

Variable File Structure

vars/
├── base.yml              # Shared defaults
├── staging.yml           # Staging overrides
├── production.yml        # Production overrides
├── os/
│   ├── RedHat-9.yml      # RHEL 9 specifics
│   ├── Ubuntu.yml        # Ubuntu specifics
│   └── default.yml       # Fallback
├── services/
│   ├── nginx.yml
│   ├── postgres.yml
│   └── redis.yml
└── vault/
    ├── staging-secrets.yml
    └── production-secrets.yml

include_vars vs vars_files

| Feature | include_vars | vars_files | |---|---|---| | Dynamic paths | Yes | Limited | | Conditional loading | Yes (when) | No | | Directory loading | Yes (dir) | No | | Task-level | Yes | Play-level only | | Namespacing | Yes (name) | No |

When should I use include_vars vs vars_files?

Use vars_files for static, always-needed variables at the play level. Use ansible.builtin.include_vars when you need dynamic file selection, conditional loading, or directory-based variable loading.

Can include_vars load JSON files?

Yes. ansible.builtin.include_vars supports both YAML (.yml, .yaml) and JSON (.json) files by default.

What is variable precedence with include_vars?

Variables loaded with include_vars have "include_vars" precedence (priority 18 of 22), which is higher than role defaults, inventory variables, and vars_files, but lower than extra vars and task vars.

Category: database-automation

Browse all Ansible tutorials · AnsiblePilot Home