Ansible playbookida rollarni qanday chaqirish mumkin?
sobes.tech AI
AIdan javob
Roles in Ansible can be invoked in several ways within a playbook.
-
Using the
roleskeyword at the playbook level:# playbooks/my_playbook.yml - name: Apply roles to servers hosts: webservers become: yes roles: - role: common # Call the 'common' role - role: nginx # Call the 'nginx' role vars: # Pass variables to the role nginx_port: 8080 - another_role # Shortened form of invocationThis method is used to invoke roles that will be executed sequentially on all hosts defined in the
hostssection. -
Using the
include_rolemodule in the task list:# playbooks/my_playbook.yml - name: Apply roles with conditions hosts: appservers tasks: - name: Include database role (only for dev) include_role: name: database when: env == 'dev' # Conditional invocation - name: Include application role include_role: name: app vars: app_version: 1.2.0 # Pass variables to the roleThe
include_rolemodule executes the role as if it were a list of tasks included in the current play. It allows using conditions (when) and loops (loop) to control role execution. -
Using the
import_rolemodule in the task list:# playbooks/my_playbook.yml - name: Import application role hosts: appservers tasks: - name: Import application role for all hosts import_role: name: app vars: app_config_file: /etc/app/config.conf # Pass variablesThe
import_rolemodule is processed during the playbook parsing phase, before actual execution. This means that directives likewhenwill apply to all tasks within the role, not just the role invocation itself. Variables passed viavarswill be available inside the role.
The main difference between include_role and import_role lies in the timing of processing: import_role is processed statically at parse time, while include_role is processed dynamically during playbook execution. This affects the ability to use conditions and loops:
| Function | include_role |
import_role |
|---|---|---|
| Processing | Dynamic | Static |
Use when to invoke |
Yes | No |
Use loop to invoke |
Yes | No |
| Ability to use variables defined earlier in the play | Yes | No |
The choice between these methods depends on the required flexibility and processing time. For simple role inclusion, usually the roles keyword or import_role suffices. For more complex scenarios with conditions and loops, include_role is used.