Dazul
Dazul

Reputation: 157

Do not run ansible command if file exists

I am trying to do a playbook in which I run a command only if a file does not exists. My challenge is that a part of the filename is created randomly. I tried something like:

- name: Generate file
  command: <command> "{{ item.name }}"
  chdir: "{{ target_zone_dir }}"
  creates:
    - "{{ target_zone_dir }}/K{{ item.name }}.+[0-9][0-9][0-9]+[0-9][0-9][0-9][0-9][0-9].key"
    - "{{ target_zone_dir }}/K{{ item.name }}.+[0-9][0-9][0-9]+[0-9][0-9][0-9][0-9][0-9].private"
  check_mode: no
  with_items:
    - "{{ target_zone_domains }}"

But my files are alwas generated, even if other one exists.

Upvotes: 0

Views: 249

Answers (1)

mdaniel
mdaniel

Reputation: 33158

What CiroRa said is mostly true, with the difference that it need not be so black-and-white as zero files or else.

- command: /bin/ls -1
  args:
    chdir: "{{ target_zone_dir }}"
  register: target_files
- when: not target_files.stdout is search("K"+item.name+".+[0-9]*.(key|private)")
  with_items: "{{ target_zone_domains }}"

I'm sure there are more "ansible-y" ways of doing that first task, but you get the idea

Upvotes: 1

Related Questions