How to avoid error when using a registered variable in check mode?

Hi,

I have a playbook that has to use the command module and registers its
output in a variable like so:

- command: do something here
  register: my_variable

- debug: msg="Here is the output of {{ my_variable.stdout }}"

When running this in check_mode, the command task is skipped and the
variable my_variable does not have a object stdout. So ansible errors out.

How to avoid this? I got two thoughts, any hints or better practices
are highly welcome.

1. Set check_mode: no and always run the command task so the variable
always contains the stdout object.
2. Only run the debug task when my_variable.skipped is not defined.

Thanks in advance,
Johannes

Hello Johannes,

You might want to use the Jinja2 defined test.

Your debug task would look something like this.

`

  • debug: msg=“Here is the output of {{ my_variable.stdout }}”
    when: my_variable is defined

`

Just a thought…

  1. Set check_mode: no and always run the command task so the variable

always contains the stdout object.
2. Only run the debug task when my_variable.skipped is not defined.

  1. only run the debug task when not in check_mode
  2. set some sort of default value when in check_mode
    https://docs.ansible.com/ansible/playbooks_checkmode.html

Cheers,
Paul

Thanks, I already had that in mind for the element skipped of my_variable:

"2. Only run the debug task when my_variable.skipped is not defined."

Johannes

Thanks for the thoughts. Which one would you pick? Which seems the
cleanest?

Johannes