在 ansible playbook 中,如果文件已存在于块任务中,如何跳过任务?

在 ansible playbook 中,如果文件已存在于块任务中,如何跳过任务?

我有这样的任务:

- 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

但它会产生一个错误:ERROR! 'changed_when' is not a valid attribute for a Block

/opt/jetbrains-toolbox.tar.gz如果/opt/jetbrains-toolbox已经存在下载,我该如何跳过下载?

答案1

---
- 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

由于您知道要下载的确切版本,因此您可能还想在下载中包含校验和。

相关内容