答案1
一个非常基本的解决方案。在您的任务中:
- name: Do command optionally ignoring create option
command:
cmd: touch /tmp/toto.txt
creates: "{{ ignore_creates | default(false) | bool | ternary('', '/tmp/toto.txt') | default(omit, true) }}"
然后,您可以使用额外的变量启动剧本,-e ignore_creates=true
以强制任务运行,即使文件存在。删除命令中的额外变量将再次启用条件。
答案2
重复表达式有时是可行的,不要太努力去遵守 DRY。尽管你可以重复使用带有变量的表达式。
- name: Testing creates parameter
hosts: localhost
vars:
# Long expression for reuse in command tasks
# Special value "omit" can be returned
# from any expression, including ternary filter
creates: "{{ ignore_creates | default(false) | bool | ternary(omit, creates_file) }}"
tasks:
- name: Do command optionally ignoring create option
command:
cmd: touch {{ creates_file }}
creates: "{{ creates }}"
vars:
# Task level var to for use in the creates expression
# Still a lot of typing,
# but perhaps you don't want to retype the filter
ignore_creates: false
creates_file: /tmp/ansiblecreatestest.txt
- command:
cmd: touch {{ creates_file }}
creates: "{{ creates }}"
vars:
ignore_creates: true
creates_file: /tmp/ansiblecreatestest.txt
将复杂的逻辑写入剧本、包装更多通用模块,无论做什么都会变得乏味和重复。
相反,可以考虑编写一个自定义模块来运行命令。将需要重新运行命令时的逻辑写入模块中。