lonix
lonix

Reputation: 20937

Ansible undefined variables in check mode

Consider this playbook:

---
- name: test
  hosts: localhost
  gather_facts: no
  tasks:

  - name: foo
    shell: echo foo                             # skipped when running in check mode
    register: result

  - debug: msg="foo"
    when: (result is defined)
          and (result.stdout == 'foo')

I thought the is defined would result in short circuit evaluation as in other languages, but it doesn't.

If this is run in check mode, I get:

fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout'

I know I can ignore the error with ignore_errors: "{{ansible_check_mode}}", but I want to learn how to fix this problem.

How do I rewrite the when clause to prevent referencing undefined variables?

Upvotes: 2

Views: 1518

Answers (1)

Zeitounator
Zeitounator

Reputation: 44760

Actually, if you debug the var without a condition, you will see it is defined. It simply does not contain a stdout key since the task was skipped. The correct ways to work arround this (non exhaustive list):

- debug: msg="{{ result.stdout | default('no value') }}
  when: result.stdout | default('') == 'foo'
- debug: msg="foo"
  when:
    - result is not skipped
    - result.stdout == 'foo'

Note that since your above shell example is not changing anything on the remote target you can also decide to play it even when running in check mode:

  - name: foo
    shell: echo foo
    check_mode: false
    changed_when: false
    register: result

  - debug: msg="foo"
    when: result.stdout == 'foo'

Upvotes: 4

Related Questions