Conditional variable assignments

Hi,

this is probably easy but I cannot figure out how to do this with Ansible:

  • some task that registers variable x

  • some task that registers variable y

  • some task that registers variable z

  • register a variable ‘a’ for which holds: if x == True, a=y, else, a=z

  • some task that uses a

How can this be done with Ansible? I currently use two conditional tasks for the assignment and register the variable ‘a’ with a shell echo command – this does not seem right to me :wink:

All the best
Arne

It might be possible to work around this with jinja, but I am reminded of the words of the guru… “Ansible is not a programming language”…

Can I suggest instead…

Some task that registers variable X

Another task that registers variable a but is only run when X is true

A third task that registers variable a but is only run when X is false

A fourth task that uses variable a

Unless you need both y and z at the same time then this satisfies your use case and simplifies your actual playbook…

Of course even this might not be needed depending on what you are actually trying to do.

I hope that this helps,

Adam

I personally strongly dislike seeing Jinja2 conditionals in top level playbooks (too much like line noise), so I’d do this to keep it cleaner:

  • shell: foo
    register: x

  • shell: bar
    register: y

  • shell: baz
    register: z

  • set_fact: a={{ z }}

  • set_fact: a={{ y }}
    when: x