Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

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.

Note: Use imports to ensure all variables and tasks are defined before execution.
---
            - 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:

  1. Define your main playbook where imports will be used.
  2. Identify reusable sections of your playbook.
  3. Create separate YAML files for tasks or playbooks.
  4. Use import_playbook for static inclusions and include_tasks for dynamic inclusions.
  5. 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.