Search code examples
ansibleconditional-statements

ansible when condition fails


the following when condition fails with parsing error.

  - name: some task
    debug:
      msg: "{{ansible_host}}"
    when: "({{somevariable}} == 'foo' and ABC_{{bar}}_xyz in group_names) or ({{somevariable}} == 'foo' and ABC_{{bar}}_efg in group_names)"

I basically want this task to run if a certain variable is equal to foo and the host belongs to a few certain groups in inventory

The error message

fatal: [x.x.x.x]: FAILED! => {"msg": "The conditional check '({{somevariable}} == 'foo' and ABC_{{bar}}_xyz in group_names) or ({{somevariable}} == 'foo' and ABC_{{bar}}_efg in group_names)' failed. The error was: error while evaluating conditional (({{somevariable}} == 'foo' and ABC_{{bar}}_xyz in group_names) or ({{somevariable}} == 'foo' and ABC_{{bar}}_efg in group_names)): 'foo' is undefined\n\nThe error appears to be in '/playbooks/playbook.yml': line 23, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: some task\n    ^ here\n"}

Solution

  • You should not use {{ }} with the when condition. see this official documentation. Means, your expression should look like below:

    when: "(somevariable == 'foo' and 'ABC_' + bar + '_xyz' in group_names) or (somevariable == 'foo' and 'ABC_' + bar + '_efg' in group_names)"