AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Ansible assert Module: Validate Conditions and Fail Early (Complete Guide)

By Luca Berton · Published 2024-01-01 · Category: troubleshooting

How to use Ansible assert module to validate conditions, check prerequisites, and fail with clear messages.

Ansible assert Module: Validate Conditions and Fail Early (Complete Guide)

The ansible.builtin.assert module assert that given expressions are true. This guide covers all common use cases with practical playbook examples.

See also: Ansible debug vs assert: When to Use Each Module

Basic Assertion

- name: Verify minimum disk space
  ansible.builtin.assert:
    that:
      - ansible_mounts | selectattr('mount', 'equalto', '/') | map(attribute='size_available') | first > 1073741824
    fail_msg: "Less than 1GB free on root partition"
    success_msg: "Disk space check passed"

Validate Variables

- name: Validate input variables
  ansible.builtin.assert:
    that:
      - app_version is defined
      - app_version | regex_search('^\d+\.\d+\.\d+$')
      - env in ['dev', 'staging', 'production']
      - http_port | int > 0
      - http_port | int < 65536
    fail_msg: "Invalid input variables. Check app_version, env, and http_port."

See also: Ansible Role Input Validation with validate_argument_spec

Pre-flight Checks

- name: Pre-deployment validation
  ansible.builtin.assert:
    that:
      - ansible_distribution == "Ubuntu"
      - ansible_distribution_major_version | int >= 22
      - ansible_memtotal_mb >= 2048
      - ansible_processor_vcpus >= 2
    fail_msg: "Host does not meet minimum requirements"

Quiet Mode

- name: Silent assertion (no output on success)
  ansible.builtin.assert:
    that:
      - vault_db_password is defined
      - vault_db_password | length >= 12
    quiet: true

See also: ansible.builtin.assert Module: Validate Variables & Conditions (Guide)

FAQ

What does ansible assert do?

The assert module tests conditions and fails the play with a clear message if any condition is false. Use it for input validation, prerequisite checks, and ensuring hosts meet requirements.

When should I use assert vs when?

Use assert to fail fast with a descriptive error when requirements are not met. Use when to skip tasks conditionally. Assert is for "this must be true", when is for "do this if true".

Conclusion

The ansible.builtin.assert module is a versatile tool for assert that given expressions are true. Use the examples above as starting points and adapt them to your infrastructure needs.

Related Articles

Ansible Playbook GuideAnsible Variables Guide

Module Parameters Reference

| Parameter | Required | Default | Description | |---|---|---|---| | that | Yes | — | List of conditions to evaluate (must all be true) | | fail_msg | No | "Assertion failed" | Message when assertion fails | | success_msg | No | — | Message when assertion passes | | quiet | No | false | Suppress success output |

Basic Assertion

- name: Verify minimum disk space
  ansible.builtin.assert:
    that:
      - ansible_mounts | selectattr('mount', 'equalto', '/') | map(attribute='size_available') | first > 1073741824
    fail_msg: "Root partition has less than 1 GB free space"
    success_msg: "Root partition has sufficient space"

Multiple Conditions

- name: Validate deployment prerequisites
  ansible.builtin.assert:
    that:
      - ansible_distribution in ['RedHat', 'CentOS', 'Rocky', 'AlmaLinux']
      - ansible_distribution_major_version | int >= 8
      - ansible_memtotal_mb >= 2048
      - ansible_processor_vcpus >= 2
    fail_msg: >
      Host {{ inventory_hostname }} does not meet requirements:
      OS: {{ ansible_distribution }} {{ ansible_distribution_version }}
      RAM: {{ ansible_memtotal_mb }} MB (need 2048+)
      CPUs: {{ ansible_processor_vcpus }} (need 2+)
    success_msg: "All prerequisites met on {{ inventory_hostname }}"

Validate Variables Before Use

- name: Ensure required variables are defined
  ansible.builtin.assert:
    that:
      - app_version is defined
      - app_version | length > 0
      - db_host is defined
      - db_port | int > 0
      - db_name is defined
    fail_msg: "Missing required variables. Check group_vars or extra-vars."

- name: Validate version format (semver) ansible.builtin.assert: that: - app_version is match('^[0-9]+\.[0-9]+\.[0-9]+$') fail_msg: "app_version '{{ app_version }}' is not valid semver (expected X.Y.Z)"

Validate API Responses

- name: Check API health endpoint
  ansible.builtin.uri:
    url: "http://{{ app_host }}:{{ app_port }}/health"
    return_content: true
  register: health_check

- name: Assert API is healthy ansible.builtin.assert: that: - health_check.status == 200 - health_check.json.status == "healthy" - health_check.json.database == "connected" fail_msg: "API health check failed: {{ health_check.json | default('no response') }}"

Complete Playbook: Pre-Deployment Validation

---
- name: Pre-deployment validation
  hosts: all
  become: true
  gather_facts: true

tasks: - name: Validate OS requirements ansible.builtin.assert: that: - ansible_os_family in ['RedHat', 'Debian'] - ansible_distribution_major_version | int >= 8 or ansible_distribution == 'Ubuntu' fail_msg: "Unsupported OS: {{ ansible_distribution }} {{ ansible_distribution_version }}"

- name: Validate network connectivity ansible.builtin.wait_for: host: "{{ db_host }}" port: "{{ db_port }}" timeout: 5 register: db_conn failed_when: false

- name: Assert database is reachable ansible.builtin.assert: that: - db_conn is not failed fail_msg: "Cannot reach database at {{ db_host }}:{{ db_port }}"

- name: Validate disk space for deployment ansible.builtin.assert: that: - item.size_available > 5368709120 fail_msg: "Insufficient space on {{ item.mount }}: {{ (item.size_available / 1073741824) | round(1) }} GB free" loop: "{{ ansible_mounts | selectattr('mount', 'in', ['/', '/opt', '/var']) | list }}"

- name: All checks passed ansible.builtin.debug: msg: "✅ {{ inventory_hostname }} passed all pre-deployment checks"

assert vs fail

| Feature | assert | fail | |---|---|---| | Multiple conditions | Yes (list in that) | No (use when) | | Success message | Yes | No | | Quiet mode | Yes | No | | Best for | Validation gates | Single condition failures |

Can I use assert in check mode?

Yes. ansible.builtin.assert works in check mode and does not modify the system — it only evaluates conditions.

How do I make assertions non-fatal?

Use ignore_errors: true or wrap in a block/rescue to handle assertion failures gracefully without stopping the playbook.

Category: troubleshooting

Browse all Ansible tutorials · AnsiblePilot Home