DevOps
Infrastructure as Code
Ansible: Variables & Handlers

Ansible: Variables & Handlers

Make your automation dynamic, flexible, and efficient. Variables allow you to reuse values throughout your project, while Handlers ensure that tasks like service restarts only happen when necessary.


🔑 Dynamic Automation with Variables

Variables in Ansible let you store values like port numbers, user names, or file paths so you don't have to hardcode them.

1. Defining Variables

The most common way is using the vars keyword directly in your playbook:

- hosts: all
  vars:
    http_port: 80
    app_user: devuser

2. Using Variables (Jinja2 Syntax)

To use a variable, wrap it in double curly braces: {{ variable_name }}.

  tasks:
    - name: Ensure port is open
      debug:
        msg: "The application is running on port {{ http_port }}"

🔄 The Variables Hierarchy

Ansible allows you to define variables in many places. If the same variable is defined twice, Ansible uses a specific order of precedence:

SourcePriorityBest Use Case
Role DefaultsLowestDefault values that can be easily overridden.
Inventory VarsMediumValues specific to a group of servers (e.g., db_servers).
Playbook VarsHighValues specific to a particular automation workflow.
Extra Vars (-e)HighestOne-off overrides passed through the command line.

⚡ Efficiency with Handlers

Handlers are special tasks that only run when they are "notified" by another task. They are typically used for restarting services after a configuration file has changed.

Why use them?

If you have 10 tasks in a playbook, you don't want to restart Nginx 10 times. A handler will:

  1. Wait until all other tasks are finished.
  2. Run only once, regardless of how many tasks notified it.
  3. Run only if a task it is watching actually reported a "Changed" status.

Example: The Notify-Handler Relationship

  tasks:
    - name: 1. Update Nginx Config
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: restart nginx  # Trigger the handler
 
    - name: 2. Copy SSL Certificate
      copy:
        src: cert.pem
        dest: /etc/nginx/ssl/
      notify: restart nginx  # Trigger the same handler
 
  handlers:
    - name: restart nginx
      service:
        name: nginx
        state: restarted

[!IMPORTANT] Handler Lifecycle Handlers execute at the very end of a play. If any task fails before the end of the play, notified handlers will not run unless you use the force_handlers: yes setting.