BacklogZero®

Ansible in a Minute · Ansible Core ·

Use undef to clear a variable for a block

Short answer

Use undef() to undefine a variable of lesser precedence so a block must supply its own value.

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

clear api_token for one block with undef and a custom hint

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: Clear a play variable for one block
  hosts: localhost
  gather_facts: false
  vars:
    api_token: "play-token"
  tasks:
    - name: Show the play token
      ansible.builtin.debug:
        msg: "token={{ api_token }}"

    - name: Require api_token for this block
      vars:
        api_token: "{{ undef(hint='Provide api_token for this block') }}"
      block:
        - name: Print api_token
          ansible.builtin.debug:
            msg: "token={{ api_token }}"

How it works

undef() returns an undefined value. Use it in vars on a task or block to clear a lower-precedence value. The optional hint appears when Ansible reports the undefined variable.

When to use it

  • Forcing a block to require an explicit credential
  • Overriding host or play variables for a short scope

Requirements

  • Ansible: >=2.14

Validation

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

Notes

undef() was added in Ansible 2.12. Accessing the cleared variable fails unless you also use default or define a higher-precedence value. Prefer default when you want a fallback instead of a hard requirement.

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 undef to clear a variable for a block · Level Up Labs