Using pre_tasks in Ansible Playbooks | Generated by AI

Home 2025.12

Question: How do I use pre_tasks in an Ansible playbook?

Answer:

In Ansible playbooks, pre_tasks are a list of tasks that execute before any roles or regular tasks in a play. They are commonly used for initial setup steps such as checking prerequisites, registering variables, updating package caches, or gathering facts conditionally.

Basic Syntax

---
- name: Example playbook demonstrating pre_tasks
  hosts: webservers
  become: yes

  pre_tasks:
    - name: Display a message before everything starts
      debug:
        msg: "This runs as a pre_task"

    - name: Update apt cache (Debian/Ubuntu only)
      apt:
        update_cache: yes
      when: ansible_os_family == "Debian"

    - name: Install required package before roles run
      package:
        name: git
        state: present

  roles:
    - common
    - nginx

  tasks:
    - name: Regular tasks run after pre_tasks and roles
      debug:
        msg: "This is a normal task"

Execution Order in a Play

  1. pre_tasks
  2. roles (if any)
  3. tasks
  4. post_tasks (if any)

Common Use Cases for pre_tasks

Example: Conditional fact gathering

pre_tasks:
  - name: Gather facts only if not already gathered
    setup:
    when: ansible_connection is not defined

Example: Fail early if a condition is not met

pre_tasks:
  - name: Ensure required variable is defined
    assert:
      that: my_required_var is defined
      fail_msg: "my_required_var must be defined when running this playbook"

Important Notes

You can also combine pre_tasks with post_tasks for full control over execution flow.

References:


Back

x-ai/grok-4.1-fast

Donate