Ansible playbook syntax for executing a task when Ansible controller file exists

Viewed 30

When using Ansible, the controller is the machine you execute playbooks from.

I want to only run an Ansible task in a playbook when the controller has a file.

Is there a way to write something like this and exists(x.tgz), below?

- name: "copy up and unarchive the x for x if we have it on our controller"
  unarchive:
    src: x.tgz
    dest: /usr/local/lib/x
  when: "{{ { enable_me | bool } and exists(x.tgz) }}"
1 Answers

I want to only run an Ansible task in a playbook when the controller has a file.

By default, lookup plugins execute and are evaluated on the Ansible control machine only.

Is there a way to write something like this and exists(x.tgz), below?

Therefore and instead of using multiple tasks to check for the file existence, addressing delegation and running once, registering the result, running tasks conditionally on the registered result, you could probably write something like this

when: ( enable_x | bool ) and lookup('file', './x.tgz', errors='warn')

since it will

  • Check if the file exists on the Ansible Control Node
  • Returns the path to file found
  • Filter returns true if there is a path

Further Documentation

Further Q&A

Related