Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Variables in Playbooks

Introduction

In Ansible, variables are a powerful way to manage dynamic values that can change from one run to another. Variables can be used to store values that you want to reuse throughout your playbooks. This allows for more flexible and maintainable playbooks.

Defining Variables

Variables in Ansible can be defined in several places, including:

  • Inventory files
  • Playbooks
  • Roles
  • Extra vars

Here is an example of defining a variable in a playbook:

---
- name: Example playbook
  hosts: all
  vars:
    example_variable: "Hello, World!"
  tasks:
    - name: Print the variable
      debug:
        msg: "{{ example_variable }}"
                

Using Variables

Once defined, variables can be used in playbooks using the Jinja2 templating syntax {{ variable_name }}. Here is an example:

---
- name: Using variables example
  hosts: all
  vars:
    greeting: "Welcome to Ansible"
  tasks:
    - name: Print greeting
      debug:
        msg: "{{ greeting }}"
                

Variable Precedence

Ansible variables have different levels of precedence. The following list shows the order of precedence from the lowest to the highest:

  1. Role defaults
  2. Inventory file or script group vars
  3. Inventory group_vars/all
  4. Playbook group_vars/all
  5. Inventory group_vars/*
  6. Playbook group_vars/*
  7. Inventory file or script host vars
  8. Inventory host_vars/*
  9. Playbook host_vars/*
  10. Host facts / cached facts
  11. Play vars
  12. Play vars_prompt
  13. Play vars_files
  14. Registered vars
  15. Set_facts / include_vars
  16. Role (and include_role) vars
  17. Block vars (only for tasks in block)
  18. Task vars (only for the task)
  19. Extra vars (always win)

Facts as Variables

Facts are system properties collected by the setup module when a playbook runs. These facts can be used as variables in your playbooks. Here is an example:

---
- name: Using facts example
  hosts: all
  tasks:
    - name: Print the system's architecture
      debug:
        msg: "The system architecture is {{ ansible_architecture }}"
                

Default Values

You can provide default values for variables using the Jinja2 syntax. This is useful when a variable might not always be defined. Here is an example:

---
- name: Default values example
  hosts: all
  tasks:
    - name: Print variable with default
      debug:
        msg: "{{ my_variable | default('Default Value') }}"
                

Conclusion

Variables are a fundamental part of creating flexible and maintainable playbooks in Ansible. By understanding how to define, use, and manage variables, you can write more powerful and reusable automation scripts.