Ansible Playbook – Skip Task if File Already Exists

ansibleansible-playbook

I have a task like this :

- name: install jetbrains toolbox
changed_when:
block:
  - name: download toolbox
    get_url:
      url: 'https://download.jetbrains.com/toolbox/jetbrains-toolbox-{{ toolbox_version }}.tar.gz'
      dest: /tmp/toolbox.tar.gz
  - name: open toolbox
    unarchive:
      src: /tmp/toolbox.tar.gz
      dest: /opt/jetbrains-toolbox
args:
  creates: /opt/jetbrains-toolbox

But it yields an error : ERROR! 'changed_when' is not a valid attribute for a Block

How can I skip the download download of /opt/jetbrains-toolbox.tar.gz skip the download if /opt/jetbrains-toolbox is already there ?

Best Answer

---
- name: register status of /tmp/toolbox.tar.gz
  stat:
    path: /tmp/toolbox.tar.gz
  register: toolbox_path

- name: install jetbrains toolbox
  # check if toolbox_path is a regular file
  when: "not toolbox_path.stat.exists"
  block:
    - name: download toolbox
      get_url:
        url: "https://download.jetbrains.com/toolbox/jetbrains-toolbox-{{ toolbox_version }}.tar.gz"
        dest: /tmp/toolbox.tar.gz

    - name: open toolbox
      unarchive:
        src: /tmp/toolbox.tar.gz
        dest: /opt/jetbrains-toolbox

You might also want to include checksums in the download as you know the exact version you want to download.