Ansible: How do I avoid registering a variable when a “when” condition is *not* met?

Unfortunately, this is the expected behavior. From Ansible Variables

Note
If a task fails or is skipped, the variable still is registered
with a failure or skipped status, the only way to avoid registering a
variable is using tags.

I do not know how to use tags to solve your issue.

EDIT: I found a way albeit a crude solution. Store the results so that it is not overwritten

  - set_fact: mypwd="{{make_password}}"
    when: make_password.changed

So your code will look like:

- name: Users | Generate password for user (Debian/Ubuntu)
  shell: makepasswd --chars=20
  register: make_password
  when: ansible_distribution in ['Debian', 'Ubuntu']

- set_fact: mypwd="{{make_password}}"
  when: make_password.changed

- name: Users | Generate password for user (Fedora)
  shell: makepasswd -m 20 -M 20
  register: make_password
  when: ansible_distribution in ['Fedora', 'Amazon']

- set_fact: mypwd="{{make_password}}"
  when: make_password.changed

- name: Users | Generate password for user (CentOS)
  shell: mkpasswd -l 20
  register: make_password
  when: ansible_distribution in ['CentOS']

- set_fact: mypwd="{{make_password}}"
  when: make_password.changed

- name: debug
  debug: var=mypwd

Leave a Comment