BacklogZero®

Ansible in a Minute · Ansible Core ·

Use default to handle an undefined variable

Short answer

Use the default filter so a task still runs when a variable is undefined.

Ansible in a Minute — default

Subscribe for updates

Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.

By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.

Request

print app_port with default 8080 when undefined

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
- name: Print app_port with default 8080 when undefined
  hosts: all
  gather_facts: false
  tasks:
    - name: Set app_port with default 8080
      set_fact:
        app_port: "{{ app_port | default(8080) }}"

    - name: Print app_port
      ansible.builtin.debug:
        msg: "app_port is {{ app_port }}"

How it works

default substitutes 8080 when app_port is undefined, then set_fact stores that value for later tasks. The play does not fail. Use default(omit) when you want Ansible to omit a module argument instead of sending a value.

When to use it

  • Optional extra vars on a job template
  • Sensible fallbacks for ports, paths, or names

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-16

Notes

Pass true as the second argument when you also want to replace an empty string. defined is a test. Use when: app_port is defined when you must skip the task instead of substituting a value. Use default(omit) when the module argument should be absent; see the related omit guide.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today →

Related guides

← Back to Ansible in a Minute

Use default to handle an undefined variable · Level Up Labs