Ansible:如果文件存在,不要 运行 shell 命令

Ansible: do not run shell command if a file exists

我想在 Ansible 剧本中执行以下操作:

- name: "Generate variant html report"
  shell: "<my command>"
  with_items: "{{ variants | default([]) }}"
  when: ({{ folderReports }}/{{ item }}).exists == False

when 中,我需要一种方法来创建文件路径,并确定它是否存在。我尝试使用“(” “)”来包围我的第一个表达式,但它似乎不起作用:

2016-10-13 16:22:48,130 p=94292 u=sautomation | fatal: [localhost]: FAILED! => {"failed": true, "msg": "The conditional check '({{ folderReports }}/{{ item }}).exists == True' failed. The error was: template error while templating string: unexpected '/'. String: {% if (/opt/diff-test1.diff).exists == True %} True {% else %} False {% endif %}\n\nThe error appears to have been in '/opt/ansible/roles/stats/tasks/main.yml': line 45, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: \"Generate report\"\n ^ here\n"}

要防止任务在指定文件已存在时执行,请使用 shell 模块的 creates 参数:

- name: "Generate variant html report"
  shell: "<my command>"
  args:
    creates: "{{ folderReports }}/{{ item }}"
  with_items: "{{ variants | default([]) }}"

您收到错误是因为 .exists 在您的条件中检查变量(事实)是否存在,而不是目标节点上的文件。