从ansible剧本中删除(如果不存在)

时间:2018-09-26 20:35:48

标签: shell ansible

我是Ansible的新手,在我的一本剧本中面临以下问题

可用的剧本任务代码:

- name: Delete existing dist folder
  shell: "[ -d {{ base_path }}/dist ] && rm -rf {{ base_path }}/dist"

输出:

fatal: [masked.amazonaws.com]: FAILED! => {
"changed": true,
"cmd": "[ -d /home/centos/masked/masked/dist ] && rm -rf /home/centos/masked/masked/dist",
"delta": "0:00:00.098034",
"end": "2018-09-26 20:26:06.940872",
"invocation": {
    "module_args": {
        "_raw_params": "[ -d /home/centos/masked/masked/dist ] && rm -rf /home/centos/masked/masked/dist",
        "_uses_shell": true,
        "argv": null,
        "chdir": null,
        "creates": null,
        "executable": null,
        "removes": null,
        "stdin": null,
        "warn": true
    }
},
"msg": "non-zero return code",
"rc": 1,
"start": "2018-09-26 20:26:06.842838",
"stderr": "",
"stderr_lines": [],
"stdout": "",
"stdout_lines": []

如果我手动运行此命令,它将正常工作

[ -d /home/centos/masked/masked/dist ] && rm -rf 
/home/centos/masked/masked/dist

有人知道什么地方可能出问题吗?

感谢您的回应。

谢谢。

2 个答案:

答案 0 :(得分:1)

non-zero return code

如果左侧用[ -d {{ base_path }}/dist ]计算为false,则返回非零代码。请改用三行表格。或编写一个shell脚本并调用它,

if [ -d {{ base_path }}/dist ]; then
    rm -rf {{ base_path }}/dist
fi

答案 1 :(得分:1)

使用file模块删除目录,而不是shell

- name: Delete existing dist folder
  file:
    path: "{{ base_path }}/dist"
    state: absent

根据the documentation,它非常接近rm -rf

  

如果absent,将递归删除目录,并且文件或符号链接将取消链接。请注意,如果路径不存在(状态不变),则不存在不会导致文件失败。