Playbook Imports and Includes in Ansible
Introduction
In Ansible, playbooks are used to define configurations, deployments, and orchestrations. As playbooks grow in size and complexity, it becomes essential to modularize them using imports and includes. This lesson will cover how to effectively use these features.
Key Concepts
- **Playbook**: A YAML file containing a list of tasks to be executed on managed hosts.
- **Import**: Brings in other playbooks or tasks at the time of parsing.
- **Include**: Dynamically includes a playbook or task during execution.
Imports vs Includes
Import
When you import a playbook or role, it is loaded at the start of the playbook run. This means all tasks are parsed before execution, allowing for static definitions.
---
- import_playbook: other_playbook.yml
Include
Includes allow for dynamic loading of tasks during execution. This is useful for conditionally executing tasks based on runtime variables.
---
- include_tasks: task_file.yml
Step-by-Step Process
Follow these steps to structure your playbooks using imports and includes:
- Define your main playbook where imports will be used.
- Identify reusable sections of your playbook.
- Create separate YAML files for tasks or playbooks.
- Use
import_playbook
for static inclusions andinclude_tasks
for dynamic inclusions. - Test your playbook to ensure all tasks are being executed as expected.
graph TD;
A[Define Main Playbook] --> B[Identify Reusable Sections];
B --> C[Create YAML Files];
C --> D{Choose Inclusion Type};
D -->|Static| E[Use import_playbook];
D -->|Dynamic| F[Use include_tasks];
E --> G[Test Playbook];
F --> G;
Best Practices
- Modularize your playbooks to improve readability and maintainability.
- Use imports for configuration data that doesn’t change often.
- Utilize includes for tasks that might change based on conditions.
- Keep related tasks in the same file to minimize confusion.
FAQ
What is the main difference between import and include?
Imports are parsed at the beginning, while includes are parsed at runtime. Use imports for static definitions and includes for dynamic tasks.
Can I use imports and includes interchangeably?
No, they serve different purposes. Imports are static, while includes offer flexibility during execution.
How do I debug issues with imports/includes?
Use the ansible-playbook
command with the -vvv
flag for detailed output to help identify issues.