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.
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.
---
- name: Print app_port with a default when it is undefined
hosts: all
gather_facts: false
tasks:
- name: Print app port
ansible.builtin.debug:
msg: "{{ app_port | default(8080) | int }}"How it works
default substitutes a fallback when the variable is undefined. 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-15
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.
Reference
- Handling undefined variables (Ansible docs)
Built for every Ansible use case in every organization
BacklogZero can generate this kind of automation in your environment, just like it did here.