How to Use Variables in Ansible Playbooks

Introduction

Define and use variables from inventories, vars files, facts, and command line. This comprehensive guide walks you through every method with practical examples.

Quick Answer

---
- name: Use Variables in Ansible Playbooks
  hosts: all
  become: true
  tasks:
    - name: Main task
      ansible.builtin.debug:
        msg: "Implementing solution"

Step-by-Step Guide

Step 1: Prerequisites

# Ensure Ansible is installed
ansible --version

# Verify connectivity
ansible all -m ping

Step 2: Implementation

- name: Implement solution
  ansible.builtin.debug:
    msg: "Step 2 complete"
  register: result

Step 3: Verification

- name: Verify result
  ansible.builtin.assert:
    that: result is success
    fail_msg: "Verification failed"

Complete Playbook

---
- name: How to Use Variables in Ansible Playbooks
  hosts: all
  become: true
  vars:
    target_state: present

  pre_tasks:
    - name: Gather facts
      ansible.builtin.setup:
        gather_subset: min

  tasks:
    - name: Execute main logic
      ansible.builtin.debug:
        msg: "Running on {{ inventory_hostname }}"
      register: main_result

    - name: Report status
      ansible.builtin.debug:
        msg: "Success: {{ main_result }}"

  handlers:
    - name: Restart service
      ansible.builtin.service:
        name: myapp
        state: restarted

Common Mistakes

MistakeWhy It FailsCorrect Approach
Missing becomePermission deniedAdd become: true
Wrong variable scopeUndefined variableUse set_fact or vars
Not idempotentChanges on every runCheck state before acting
No error handlingPlaybook abortsUse block/rescue

Best Practices

  1. Always test first — use --check --diff before applying
  2. Use FQCN — fully qualified collection names prevent conflicts
  3. Handle errors — never let playbooks fail silently
  4. Document your code — future you will thank present you
  5. Version control — commit playbooks to git
  • Ansible Best Practices
  • Ansible Troubleshooting Guide
  • Ansible Performance Optimization

Conclusion

Define and use variables from inventories, vars files, facts, and command line. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability.