English translation
Creating and Using Roles in Ansible
AI Article Decision Snapshot
Turn the lesson into workflow, model, budget, and security checks before choosing tools.
Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.
Workflow fit
Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.
Model or tool decision
Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.
Budget and usage signal
Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.
Security and privacy review
Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.
In the previous article, we provided an overview of Ansible modules—covering their fundamental concepts and significance in automation and operations. This article delves into Ansible’s role mechanism, focusing on how to create and use roles to organize and reuse Ansible code more efficiently.
The Concept of Roles
An Ansible role is a structured way to organize tasks, variables, files, templates, and other content—designed to make Ansible projects more efficient and maintainable. Roles allow you to modularize distinct functional components, facilitating team collaboration and code reuse.
Creating a Role
Creating an Ansible role is straightforward and can be accomplished using the ansible-galaxy command. Below are the steps:
-
Generate the Directory Structure
Run the following command to create a new Ansible role:
ansible-galaxy init my_roleThis command creates a directory named
my_rolein the current working directory and automatically generates the standard role structure, including the following subdirectories and files:my_role/ ├── tasks/ │ └── main.yml ├── handlers/ │ └── main.yml ├── meta/ │ └── main.yml ├── vars/ │ └── main.yml ├── defaults/ │ └── main.yml ├── files/ └── templates/ -
Define Tasks
Specify the primary tasks for the role in
tasks/main.yml. For example:--- - name: Install nginx apt: name: nginx state: present - name: Start nginx service: name: nginx state: started enabled: yesThis snippet defines that the
my_rolerole installs and starts the Nginx service.
Define Variables
You may define required variables in either vars/main.yml or defaults/main.yml. Omit this step if no variables are needed. Typically, variables defined in defaults/main.yml have lower precedence, whereas those in vars/main.yml take higher precedence.
# defaults/main.yml
---
nginx_package: nginx
Add Handlers
Define handlers in handlers/main.yml. Handlers are triggered only when notified by tasks (e.g., after a task succeeds). For instance:
---
- name: Restart nginx
service:
name: nginx
state: restarted
You can notify this handler from within a task—for example, to restart Nginx after installation:
- name: Install nginx
apt:
name: nginx
state: present
notify: Restart nginx
Using a Role
Once created, a role can be invoked directly in a playbook. Below is an example playbook that uses the my_role role:
---
- hosts: webservers
become: yes
roles:
- my_role
In this playbook, the roles keyword instructs Ansible to load all tasks, handlers, and associated content from the my_role role automatically.
Reusability of Roles
Roles enable seamless reuse across multiple playbooks. For example, if you need to install Nginx on several servers, simply include my_role in each relevant playbook—eliminating redundant logic and ensuring consistency.
Conclusion
Organizing Ansible tasks using roles leads to cleaner, more modular code—and significantly improves reusability and maintainability. In this article, we demonstrated how to create and use roles, including defining tasks, variables, and handlers. Mastering roles will greatly enhance your productivity and efficiency when working with Ansible.
In the next article, we’ll explore how to share roles via Ansible Galaxy—further boosting team collaboration and development agility. Stay tuned!
Apply This Lesson
Turn this article into AI software, model, API, and security decisions.
English Article FAQ
Use this article as evidence before choosing AI tools
How should I use this AI Tutorials article?
Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.
Is this English article different from the Chinese original?
The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.
What should I read after Creating and Using Roles in Ansible?
Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.
Can this article alone choose an AI product or model?
No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.
Continue