在 Ansible 剧本中,如果目录不存在,我想运行任务。
- name: Check for java exists in /opt
stat: path=/opt/jdk1.8.0_71
register: p
when: p.stat.isdir is defined and p.stat.isdir
但是我必须做什么才能确保以下任务仅在该目录不存在时运行?
- name: Extract java if dir not existing
command: tar xzf /tmp/jdk1.8.0_71 chdir=/opt
这就是
creates
参数的完美用途:
- name: Extract java if dir not existing
command: tar xzf /tmp/jdk1.8.0_71
args:
chdir: /opt
creates: /opt/jdk1.8.0_71
Ansible 将检查
/opt/jdk1.8.0_71
是否存在,如果不存在则仅运行该命令。
您也可以通过以下方式下载并解压(如果不存在)
- name: "If jdk not exists then only download and unarchive"
unarchive:
src: "https://download.oracle.com/java/17/latest/jdk-17_linux-aarch64_bin.tar.gz"
dest: /opt/
remote_src: yes
creates: /opt/jdk-17
register: foo
- name: "Rename if download happens "
command: mv /opt/jdk-17_linux-arch64 /opt/jdk-17
when: foo.changed == True
如果
/opt/jdk-17
目录存在,Ansible 将跳过上述任务。
- name: Extract java if dir not existing
command: tar xzf /tmp/jdk1.8.0_71 chdir=/opt
when: not p.stat.exists