Ansible command ignore creates
Solution 1:
One very basic solution. In your task:
- 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) }}"
Then you can launch your playbook with the the extra var -e ignore_creates=true
to force the task to run even if the file exists. Removing the extra var in your command will turn the condition on again.
Solution 2:
Repeating expressions can be a practical sometimes, don't try too hard to comply to DRY. Although you can reuse an expression with variables.
- 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
Writing fancy logic into the playbook, wrapping more generic modules, will get tedious and repetitive whatever you do.
Instead, consider writing a custom module to run the commands. Write the logic for when the commands need to be re-run into the module.