Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a ansible task only if a file or directory does NOT exist?

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 
like image 342
RobertK Avatar asked Jan 26 '16 18:01

RobertK


People also ask

How to check if file exists or not in Ansible?

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.

How do I make an Ansible task run only once?

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.

How do I run a specific part of my playbook in Ansible?

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 .

How do you handle an unreachable host in Ansible?

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.


Video Answer


1 Answers

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

like image 87
Bruce P Avatar answered Sep 20 '22 16:09

Bruce P