Ansible: Include fails to execute tasks

From Glitchdata
Revision as of 23:32, 21 February 2017 by Admin (talk | contribs) (Created page with " Ansible has two "levels", one is the playbook level, where you can supply plays, the other one is the task level, where you can supply tasks. The include works on both levels...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Ansible has two "levels", one is the playbook level, where you can supply plays, the other one is the task level, where you can supply tasks. The include works on both levels, but you won't be able to include new plays if you're already at the tasks level.

For example this is okay:

main.yml

---
- include: play1.yml
- include: play2.yml

play1.yml

----
- name: run couple of tasks on all hosts
  hosts: all
  tasks: [{debug: {msg: "Task1"}}]

play2.yml

----
- name: run some more tasks on some hosts
  hosts: some
  tasks: [{debug: {msg: "Task2"}}]

As here in the main.yml you are still at the playbook level, so you can include the files, which are playbooks themselves as well. This means that you can simply run play1.yml separately from ansible-playbook anytime as well.

But, once you are at the task level, you can only include files that only contain tasks:

main.yml

---
- name: run couple of ymls
  hosts: all
  tasks:
    - include: "task1.yml"
    - include: "task2.yml"

task1.yml

---
- name: An actual command
  debug: { msg: "Task 1" }

task2.yml

---
- name: An other actual command
  debug: { msg: "Task 2" }

This is also okay, as both task1.yml and task2.yml files only contain tasks, and they are not full-fledged playbooks. Trying to run them separately with ansible-playbook won't work anymore, as they are only a bunch of tasks.

Note that in this example, if you'd include play1.yml instead of like task1.yml, then the playbook would fail, as you're already at the "tasks" level, from where you can't import any more playbooks.