如何在Ansible中等待指定目录创建完成
如何让Ansible Playbook等待目录存在
问题描述
我希望暂停我的Ansible playbook,直到某个目录存在。我了解可以通过以下代码检查文件是否存在:
- name: Wait until the file /home/myfile.txt is present before continuing wait_for: path: /home/myfile.txt state: present
但该方法似乎对目录无效。我还知道可以通过以下示例代码检查目录:
# Determine if a path exists and is a directory. Note that we need to test # both that p.stat.isdir actually exists, and also that it's set to true. - name: Get stats of the FS object ansible.builtin.stat: path: /path/to/something register: p - name: Print a debug message ansible.builtin.debug: msg: "Path exists and is a directory" when: p.stat.isdir is defined and p.stat.isdir
是否可以将这两种方法结合使用?
解决方案
当然可以结合,以下是几种可行的实现方式:
方式1:使用wait_for模块的state: directory(推荐,Ansible 2.10+)
在Ansible 2.10及以上版本中,wait_for模块新增了state: directory参数,直接就能实现等待目录存在的需求,写法最简洁:
- name: 等待目标目录存在 ansible.builtin.wait_for: path: /path/to/target_dir state: directory # 可选:设置检查间隔和超时时间 delay: 5 timeout: 300
方式2:使用wait_for的test参数(兼容旧版本)
如果你的Ansible版本较低,不支持state: directory,可以用test参数指定目录判断条件:
- name: 等待目标目录存在(兼容旧版本) ansible.builtin.wait_for: path: /path/to/target_dir state: present test: "directory" delay: 5 timeout: 300
或者用自定义Shell测试逻辑,确保路径是目录而非文件:
- name: 等待目录存在(自定义测试逻辑) ansible.builtin.wait_for: path: /path/to/target_dir test: "! -f %p && -d %p" delay: 5 timeout: 300
其中%p会自动替换为指定的path路径,! -f %p确保不是文件,-d %p确保是目录。
方式3:stat模块结合until循环(两种方法的直接结合)
这就是你提到的两种方法的结合形式,把目录检查逻辑放到until循环中,让Playbook重复执行stat任务直到目录存在:
- name: 等待目录存在(stat+until循环) ansible.builtin.stat: path: /path/to/target_dir register: dir_stat until: dir_stat.stat.isdir is defined and dir_stat.stat.isdir retries: 60 delay: 5
retries:指定最大重试次数(这里是60次)delay:每次重试的间隔时间(这里是5秒)- 总等待时长为
retries × delay,这里是300秒(5分钟)
内容的提问来源于stack exchange,提问作者user35202
相关产品推荐
相关产品推荐

