1

I searched a lot for exact the same thing that I wanted to do, but found nothing. So, I'm here to ask:

I have a playbook.yml, where defined some tasks. The first task of that playbook is checking existence of file and, if file exists I want to execute only the tasks, that are defined in the tasks.yml file and stop executing of tasks from playbook.yml (or vice versa). I have read Ansible documentation of course, first of all. But I still don't get if I'm able to do exactly what I want with import/include_tasks modules (tried both of them).

2

Q: "Checking the existence of a file"

A: Use stat. For example

- stat:
    path: /etc/foo.conf
  register: st

Q: "If the file exists execute tasks, that are defined in tasks.yml file"

A: Use include_tasks. For example

- include_tasks: tasks.yml
  when: st.stat.exists

Q: "Stop executing of tasks from playbook.yml"

A: Use meta. For example

- meta: end_play
  when: st.stat.exists
  • thank you for your reply. I wasn't clear enough with my question: the task, that is "checking existence of a file", is used for existence of docker container, so I use shell module it this way: name: Check if there is no container on the host command: docker ps -a | grep container_name register: existence ignore_errors: yes And after that, as you mentioned, I use include_tasks module. But it still works in an unexpected way (I don't understand something, I guess). And thank you very much for mentioning the meta module, I will add that. – Andrey N. Nov 26 '19 at 13:31
0

roles/includeandend/tasks/main.yml

---
- name: Unconditional include
  include_tasks: include.yml

- name: include only if file exists
  include_tasks: '{{ item }}'
  vars:
    params:
      files:
        - includeandend.yml
  #  query() returns a blank list for the loop if no files are found.
  loop: "{{ q('first_found', params, errors='ignore') }}"

- debug:
    msg: "If included, this will not execute"

roles/includeandend/tasks/include.yml

---
- debug:
    msg: "In an included file. Play will continue."

roles/includeandend/tasks/includeandend.yml

---
- debug:
    msg: "In an included file. Play will end now."

- meta: end_play

playbook.yml

---
- hosts: localhost
  gather_facts: False

  roles:
    - includeandend

In Ansible, it is typical to assume a tasks file exists within a given project. The playbook author will write it that way.

My implementation works around that by only including if exists with a first_found lookup.

Because of the requirement to stop playbook.yml, I use meta: end_play.

  • Thank you for your reply! I'll try to implement your variant on the playbook. – Andrey N. Nov 26 '19 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.