Ansible: Include fails to execute tasks

From Glitchdata
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:


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


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


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


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


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


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