In an Ansible playbook I want to run tasks if a directory does not exists.
- 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
But what must I do to ensure that the following tasks runs only if this dir does not exist?
- name: Extract java if dir not existing command: tar xzf /tmp/jdk1.8.0_71 chdir=/opt
To check whether the destination file exists and then run tasks based on its status, we can use the Ansible's stat module (or win_stat for Windows targets). With this module we can identify not only whether the destination path exists or not but also if it is a regular file, a directory or a symbolic link.
For such requirements where we need one tasks to run only once on a batch of hosts and we will be running that from Ansible controller node, we have feature parameter named run_once. When we have this parameter mentioned in a task, that task will run only once on first host it finds despite the host batch.
The easiest way to run only one task in Ansible Playbook is using the tags statement parameter of the “ansible-playbook” command. The default behavior is to execute all the tags in your Playbook with --tags all .
Resetting unreachable hosts If Ansible cannot connect to a host, it marks that host as 'UNREACHABLE' and removes it from the list of active hosts for the run. You can use meta: clear_host_errors to reactivate all hosts, so subsequent tasks can try to reach them again.
This is what the creates
parameter is perfect for:
- 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 will check to see if /opt/jdk1.8.0_71
exists and only run the command if it does not exist.
Command Module
You can also download and untar(if not exist) in the following way
- 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
Ansible will skip the above task if /opt/jdk-17
directory exists.
Unachive module
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With