How to fix Ansible Lint warning: no-jinja-when

977 views Asked by At

I just got warning raised by Ansible Lint.

This is the issue:

[no-jinja-when] [HIGH] No Jinja2 in when
You can skip specific rules or tags by adding them to your configuration file:
# .ansible-lint
warn_list:  # or 'skip_list' to silence them completely
  - no-jinja-when  # No Jinja2 in when

This is my task:

- name: remove unecessary batch
  file:
    path: "{{ item.path }}"
    state: absent
  when: var_service == "service2" and item.path | regex_replace(cron_regex_for_s2_deletion, '\\1') not in batches_{{ var_fuction | regex_replace('^service2-batch-', '') }}
  with_items: "{{ result.files }}"

I'm not sure how to fix the when condition to fulfil Ansible lint recommendations.

1

There are 1 answers

0
β.εηοιτ.βε On BEST ANSWER

when conditions are always templated:

The when clause is a raw Jinja2 expression without double curly braces

Source: https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_conditionals.html#basic-conditionals-with-when

So, you cannot have any expression block {{ ... }} or statement block {% ... %} in it.

In order to get a variable from a dynamic name you should use the vars lookup, so:

lookup(
  'vars', 
  'batches_' ~ var_fuction | regex_replace('^service2-batch-', '')
)

You can also make that when more readable by switching your and for a list:

You can use logical operators to combine conditions. When you have multiple conditions that all need to be true (that is, a logical and), you can specify them as a list

Source: https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_conditionals.html#conditionals-based-on-ansible-facts

Some extra YAML multiline trickery could also help you keep the expression on a line, as that could also be a warning Ansible lint could raise.

You end up with this condition:

when: 
  - var_service == 'service2' 
  - >-
      item.path | regex_replace(cron_regex_for_s2_deletion, '\1') 
      not in lookup(
        'vars', 
        'batches_' ~ var_fuction | regex_replace('^service2-batch-', '')
      )