Ansible - Importing tasks using import_tasks
by
Jeremy Canfield |
Updated: April 01 2024
| Ansible articles
There are a few different ways to invoke one or more roles in a playbook.
- roles
- import_playbook
- import_role
- include_role
- include_tasks
- import_tasks (this article)
Let's say you have the following structure.
├── /usr/local
│ ├── main.yml
│ ├── hello.yml
│ ├── roles
│ │ ├── foo
│ │ ├── ├── tasks
│ │ ├── ├── ├── main.yml
│ │ ├── bar
│ │ ├── ├── tasks
│ │ ├── ├── ├── main.yml
import_tasks can be used to import tasks from one playbook in another. In this example, since the main playbook main.yml and hello.yml are in the same directory, you could do something like this.
---
- hosts: all
tasks:
- import_tasks: hello.yml
...
And let's say hello.yml contains the following.
- name: greeting
debug:
msg: Hello World
Running the main.yml playbook . . .
ansible-playbook main.yml
Should return something like this.
TASK [greeting]
ok: [localhost] => {
"msg": "Hello World"
}
Since the main.yml playbooks for the "foo" and "bar" roles are not in the same directory as the main playbook main.yml, in this scenario, the absolute or relative path to the main.yml playbooks for the "foo" and "bar" roles would need to be used.
---
- hosts: localhost
tasks:
- import_tasks: roles/foo/tasks/main.yml
- import_tasks: roles/bar/tasks/main.yml
...
Did you find this article helpful?
If so, consider buying me a coffee over at