我刚刚收到Ansible Lint的警告。
这就是问题所在:
[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
这是我的任务:
- 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 }}"
我不确定如何修复when
条件以满足Ansible lint建议。
when
条件总是模板化的:
when
子句是不带双花括号的原始Jinja2表达式
<一口> 来源:https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_conditionals.html basic-conditionals-with-when 一口>
因此,其中不能有表达式块{{ ... }}
或语句块{% ... %}
。
为了从动态名称中获取变量,您应该使用vars
查找,因此:
lookup(
'vars',
'batches_' ~ var_fuction | regex_replace('^service2-batch-', '')
)
你也可以通过切换列表的and
使when
更具可读性:
可以使用逻辑运算符组合条件。当您有多个需要全部为真的条件(即逻辑
and
)时,您可以将它们指定为一个列表
<一口>来源:https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_conditionals.html conditionals-based-on-ansible-facts一口>
一些额外的YAML多行技巧也可以帮助您将表达式保持在一行中,因为这也可能是Ansible lint可能引发的警告。
你最终得到这个条件:
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-', '')
)