Darwick
Darwick

Reputation: 350

Ansible: How to check a value: key pair in the when condition

First of all, I have separated my playbooks in this way:

environtments/something/host_vars/host1.yml
roles/sshd/tasks/main.yml

The host's environment variable contains some value: key pairs, in this case:

specialinfo: 'blah'

And the role contains a block, which should be run when this 'specialinfo' value matches to blah:

- name: Check that specialvalue is blah
  block:
  - name: Do something
    ...
  - name: Do something else
    ...
  when: {{ specialinfo }} == 'blah'

Please help me to achive this, because I'm quite sure that the problem is inside the 'when' condition. If I need a copy (or something like that) inside a name, I can use {{ specialinfo }}

Please also notice that I can't use with_items here, because it can't be used inside the block element.

Upvotes: 0

Views: 481

Answers (1)

Moon
Moon

Reputation: 3047

First of all, you can't use double curly braces in when because the condition itself needs to be a jinja expression. Change the condition to when: specialinfo == 'blah'.

Note that, when condition for block applies to all the tasks inside the block. This means that the same ... == 'blah' condition will be applied to both Do something and Do something else tasks. If you want to control when a particular task to be executed, use when for the task alone like so:

- debug: Do something
    msg: is blah
  when: specialinfo == 'blah'

- debug: Do something else
    msg: is not blah
  when: specialinfo != 'blah'

Upvotes: 1

Related Questions