Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Ansible Playbook Variables

Introduction

In Ansible, variables play a crucial role in making playbooks dynamic and flexible. They allow users to store and reuse data throughout the playbook, enabling parameterization of configurations and task execution.

Key Concepts

  • Variables are placeholders for data that can be used in tasks, templates, and playbooks.
  • They can be defined in various scopes including playbooks, inventory files, and roles.
  • Variable precedence determines which value is used when multiple variables are defined with the same name.

Types of Variables

1. Playbook Variables

Defined within a playbook, these variables are accessible throughout the playbook.

2. Inventory Variables

Defined in the inventory file, they are specific to hosts or groups of hosts.

3. Role Variables

Defined within roles, these variables are specific to a role and can be defined in defaults or vars directories.

Defining Variables

Variables can be defined in different ways:

1. Inline in a Playbook


- hosts: all
  vars:
    http_port: 80
  tasks:
    - name: Ensure HTTP is installed
      yum:
        name: httpd
        state: present
            

2. In Inventory Files


[webservers]
web1 ansible_host=192.168.1.10 http_port=8080
web2 ansible_host=192.168.1.11 http_port=8081
            

3. Using Variable Files


# vars/main.yml
http_port: 80
max_clients: 200
            

Using Variables

Variables can be referenced in tasks using the Jinja2 templating syntax:


- name: Start HTTP service
  service:
    name: httpd
    state: started
    enabled: yes
  vars:
    my_http_port: "{{ http_port }}"
        

Best Practices

  • Use descriptive names for variables to improve readability.
  • Keep the variable definitions organized in separate files for better maintainability.
  • Utilize default values for role variables to enhance reusability.
  • Be mindful of variable precedence to avoid unexpected behavior.

FAQ

What is variable precedence in Ansible?

Variable precedence determines which variable is used when there are multiple definitions with the same name. The order of precedence generally follows: command line, playbook, role defaults, inventory, and role vars.

Can I define variables in files?

Yes, you can define variables in separate YAML files and include them in your playbooks using the vars_files directive.

What is Jinja2 syntax?

Jinja2 is a templating engine used in Ansible for dynamic expressions. Variables are referenced using the double curly braces syntax, e.g., {{ variable_name }}.