Variables in Playbooks - CrewAI
Introduction
Variables in playbooks are essential for dynamic and flexible task execution. They allow us to store values that can be reused throughout the playbook, making it easier to manage and update scripts. In this tutorial, we will explore what variables are, how to define them, and how to use them in playbooks.
What are Variables?
Variables are placeholders for data that can be used in playbooks. They can store different types of data such as strings, integers, lists, and dictionaries. By using variables, you can write more modular and reusable playbooks.
Defining Variables
Variables can be defined in several ways in playbooks:
- Directly in the playbook
- In inventory files
- As command-line arguments
- From external files
Let's start with defining variables directly in a playbook:
---
- name: Example Playbook
hosts: localhost
vars:
my_variable: "Hello, CrewAI!"
tasks:
- name: Print variable
debug:
msg: "{{ my_variable }}"
Using Variables
Once defined, variables can be used in tasks, templates, and handlers. Here's how you can use a variable in a task:
- name: Create a file with content from a variable
hosts: localhost
vars:
file_content: "This is the content of the file."
tasks:
- name: Create a file
copy:
dest: /tmp/myfile.txt
content: "{{ file_content }}"
Variable Types
Variables can store different types of data:
- String
- Integer
- List
- Dictionary
Here are examples of each type:
- name: Variable Types
hosts: localhost
vars:
string_var: "This is a string"
int_var: 42
list_var:
- "item1"
- "item2"
dict_var:
key1: "value1"
key2: "value2"
tasks:
- name: Print all variables
debug:
msg: |
String: {{ string_var }}
Integer: {{ int_var }}
List: {{ list_var }}
Dictionary: {{ dict_var }}
Using Variables in Templates
Variables can also be used in templates to dynamically generate content. Jinja2 is the templating engine used in playbooks. Here’s how you can use a variable in a Jinja2 template:
# template.j2
Hello, {{ name }}!
And here’s how you can apply the template in a playbook:
- name: Use Template
hosts: localhost
vars:
name: "CrewAI"
tasks:
- name: Apply template
template:
src: template.j2
dest: /tmp/greeting.txt
Conclusion
In this tutorial, we've covered the basics of variables in playbooks. We've explored how to define them, use them in tasks, and utilize them in templates. By leveraging variables, you can create more flexible and maintainable playbooks. Practice using variables in your playbooks to become more proficient in managing dynamic configurations.