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

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


- name: Extract java if dir not existing
  command: tar xzf /tmp/jdk1.8.0_71 chdir=/opt
  when: not p.stat.exists