Conditional register not working

Hi,

I’m trying to do a conditional register in a playbook:

tasks:

  • shell: echo /opt/cache/www/
    register: www_data
    when: ansible_hostname | match(“^xy-”)

  • shell: echo /mnt/code/www/
    register: www_data
    when: ansible_hostname | match(“^az-”)

  • debug: var=www_data.stdout
    when: www_data.rc is defined and www_data.rc == 0

Only the last register “/mnt/code/www/” is shown by debug, and for the other I’m getting failures.
I would like to know what is the proper way to do this.

Thanks,

Can you share what a failure means in the above, any output you have, and what ansible version you are running?

Thanks!

I found the answer in a previous post: https://groups.google.com/d/topic/ansible-project/NGXcbyQvz-Y/discussion

So register stores the variable even if the task is skipped, and this is the intended behaviour.

I was able to do what I want with one longer shell command, although I was expecting something more elegant:

tasks:

  • name: test
    shell: if [ {{ ansible_hostname | match(“^xy-”) }} == True ]; then echo /opt/cache/www; else if [ {{ ansible_hostname | match(“^az-”) }} == True ]; then echo /mnt/code/www; fi; fi
    register: www_data

  • debug: var=www_data.stdout
    when: www_data.rc == 0

Hi Michael,

ansible version is 1.6.3, and below is a sample output. You will see that debug task is being executed only for the vars registered in the second shell task. For failures I was wrong, sorry, there are all “failed=0” in this run.

Might be a good addition to the docs that register always store, even when tasks are skipped. I can write a line and send a pull request if you want.
Also, maybe print a warning when the same register is being used more than once?

Thanks!

`

“Also, maybe print a warning when the same register is being used more than once?”

It’s somewhat common for someone to use a repeated variable “result”, so this isn’t really a problem.

The above conditionals could be made easier using “set_fact” BTW:

  • set_fact: path=default_path_goes_here
  • set_fact: path=other_path
    when: ansible_hostname | match(“^xy-”)

+1 for cowsay installs. Don’t see it enough :slight_smile:

I’m glad to know about set_fact now. Thanks Michael!