Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsAnsible roles turn a collection of infrastructure tasks into a reusable, testable package. A well-designed role gives you a predictable place for tasks, handlers, templates, files, variables and dependencies, so the same configuration can be applied to staging and production without copying playbook code.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
This guide shows how to create a role, call it from a play, pass variables, declare prerequisites, install and pin shared roles, organize an infrastructure repository, and avoid the failure modes that make roles difficult to operate.
As an Amazon Associate I earn from qualifying purchases.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →What an Ansible role is and why it matters
An Ansible role is a reusable package of tasks and related automation artifacts loaded from a known directory structure. That convention lets Ansible find a role’s task entry point, handlers, templates, static files, defaults, variables and metadata without you wiring every path manually.
Instead of placing every operating-system package, configuration file and service restart in one large playbook, you can package one coherent capability as a role. Typical boundaries include a web server, baseline hardening, a monitoring agent, a database client or an application runtime.
#1 Best Overall
- [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
- [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
- [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
- [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
- [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
Roles are not separate execution engines. A play still selects the hosts and controls overall orchestration; the role supplies an organized implementation. This separation lets several plays reuse the same behavior while supplying different values for each environment.
What a role should own
- Tasks needed to install and configure one capability.
- Templates and static files required by that capability.
- Handlers for reloads or restarts caused by changes.
- Safe, documented defaults and any variables that are intentionally internal.
- Prerequisites that every invocation genuinely requires.
- Documentation describing inputs, supported platforms and side effects.
Keep the boundary meaningful. A role that configures an entire company environment becomes difficult to reuse, while a role that contains one trivial task adds indirection without much value. Split a long task flow when platform-specific or lifecycle steps need independent review, but avoid creating a role for every individual command.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →The standard role directory structure
Ansible recognizes directories and files by convention. The generated skeleton contains more directories than every project needs; retain the ones your role actually uses.
| Path | Purpose | Typical contents |
|---|---|---|
tasks/main.yml |
Role entry point and ordered task flow | Package installation, configuration, service management and imports |
handlers/main.yml |
Deferred actions notified by changed tasks | Service reload or restart handlers |
templates/ |
Jinja templates rendered on managed hosts | Configuration files containing variables and conditionals |
files/ |
Static files copied without templating | Certificates, scripts or fixed configuration fragments |
defaults/main.yml |
Low-precedence, user-overridable defaults | Listen ports, feature switches and conservative paths |
vars/main.yml |
Higher-precedence role variables | Values that should not normally be overridden by inventory |
meta/main.yml |
Dependencies and optional role metadata | Prerequisite roles and Galaxy metadata |
README.md |
Operator and developer documentation | Inputs, examples, platforms, side effects and upgrade notes |
tests/ |
Optional role test scaffolding | Test inventory and a test playbook |
At least one standard role directory is required. If a role has no static files, for example, there is no reason to keep an empty files/ directory.
Keep the main task flow readable
Put the normal entry point in tasks/main.yml. For a small role, a single file is clear. For a larger role, use task includes to separate concerns or platforms:
---
- name: Install packages
ansible.builtin.include_tasks: install.yml
- name: Apply platform-specific settings
ansible.builtin.include_tasks: "{{ ansible_facts.os_family | lower }}.yml"
- name: Configure the service
ansible.builtin.include_tasks: configure.yml
Use stable task names and keep the order intentional. A reader should be able to see prerequisites, installation, configuration and service activation without tracing a maze of includes.
Recommended Free Tools
Create your first role
Use the Galaxy command-line tool to generate a predictable skeleton. The command does not publish anything; it creates a local role directory.
ansible-galaxy role init webserver
The result includes README.md, defaults/, files/, handlers/, meta/, tasks/, templates/, tests/ and vars/. Remove unused directories only after confirming that your tooling does not depend on their presence.
Rank #2
- 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
- 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
- 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
- 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
- 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
Build a minimal web-server role
Define user-facing settings in defaults/main.yml so inventory or a play can override them:
---
webserver_package: nginx
webserver_service: nginx
webserver_listen_port: 8080
webserver_document_root: /var/www/example
Place the implementation in tasks/main.yml:
---
- name: Install the web server package
ansible.builtin.package:
name: "{{ webserver_package }}"
state: present
- name: Create the document root
ansible.builtin.file:
path: "{{ webserver_document_root }}"
state: directory
owner: root
group: root
mode: '0755'
- name: Render the server configuration
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/conf.d/example.conf
owner: root
group: root
mode: '0644'
notify: Reload web server
- name: Enable and start the service
ansible.builtin.service:
name: "{{ webserver_service }}"
enabled: true
state: started
Create the template at templates/nginx.conf.j2:
server {
listen {{ webserver_listen_port }};
root {{ webserver_document_root }};
location / {
try_files $uri $uri/ =404;
}
}
Add the handler in handlers/main.yml:
---
- name: Reload web server
ansible.builtin.service:
name: "{{ webserver_service }}"
state: reloaded
The template task notifies the handler only when its rendered content changes. Ansible runs the handler later in the play, so repeated runs do not restart or reload a service unnecessarily.
Free tools Windows power users keep installed
One-click scans. No signup required.
Call the role from a play
A play can apply the role directly and pass variables at the point of use:
---
- name: Configure web servers
hosts: webservers
become: true
roles:
- role: webserver
webserver_listen_port: 8080
Passing a value this way makes the same role usable with another port or document root elsewhere. Put environment-wide values in inventory group variables when they should apply to every host in a group, and reserve per-role arguments for values that make the invocation self-explanatory.
Design a clear role interface
A role is easier to maintain when its public interface is small. Document each supported input in the README, including its type, default, allowed values, platform limitations and whether changing it can restart a service.
Defaults versus vars
Use defaults/main.yml for values that operators are expected to override. Defaults have low precedence and are therefore suitable for ports, feature flags, paths and other policy choices.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Use vars/main.yml sparingly for values that are implementation details or must win over ordinary inventory variables. Putting every value in vars/main.yml makes the role appear configurable while preventing the overrides users reasonably expect.
Validate strict inputs early
If a role accepts a narrow interface, validate it before making changes. Argument specifications can reject an invalid port, an unsupported mode or a missing required value at the start of execution. Early failure is safer than writing half a configuration and discovering the problem during a service restart.
Rank #3
- [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
- [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
- [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
- [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
- [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
Keep environment data out of the role
Do not embed production hostnames, credentials or environment names in role defaults, templates or tasks. Store environment-specific values in inventory, group variables or host variables, and keep secrets in an approved secret store or encrypted variable mechanism. Plaintext passwords in a role repository can leak through version history even if the file is later removed.
Role dependencies and execution order
Declare prerequisites in meta/main.yml when the role cannot function without them. For example, a web-server role might require a common baseline and firewall rules:
---
dependencies:
- role: common
- role: firewall
vars:
firewall_allowed_ports: [80, 443]
Ansible executes listed dependencies before the role that declares them. It resolves nested dependencies recursively, so a prerequisite can have prerequisites of its own.
Use dependencies for mandatory prerequisites
A dependency belongs in metadata when every invocation needs it. This makes the requirement explicit and ensures that a caller cannot accidentally omit a critical setup step.
Optional capabilities are usually clearer when called directly from the play. If TLS, monitoring or a special firewall policy is optional, list the corresponding role in the play with its own tags and conditions. Operators can then enable or skip that feature without hidden behavior inside another role.
Understand duplicate dependency handling
Ansible normally avoids running an identical dependency more than once. A dependency can execute again when its parameters, tags or conditional expression differ. Set allow_duplicates: true in the dependent role’s metadata when repeated execution is deliberate and safe.
Do not use duplicate execution as a workaround for non-idempotent tasks. First make each task converge to the desired state, then decide whether a second invocation has a legitimate purpose.
Choose between include_role and import_role
Both mechanisms let a task flow invoke a role, but they are evaluated differently.
Rank #4
- Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
- Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
- All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
- Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
- Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
| Mechanism | When Ansible expands it | Best fit |
|---|---|---|
ansible.builtin.import_role |
Statically during playbook parsing | Predictable structure, static analysis and a role that is always part of the task graph |
ansible.builtin.include_role |
Dynamically while tasks run | Conditional selection, looping or insertion at a specific task location |
Use include_role when a role should be selected conditionally or inserted after a particular task. Use import_role when static parsing and predictable expansion matter. If a role is unconditionally applied to a host group, the play-level roles: list is usually the clearest expression.
Install and pin shared roles
External roles should be treated as versioned software, not as anonymous snippets downloaded at deployment time. Put their sources and versions in a repository-level requirements.yml:
---
roles:
- name: example.apache
version: 3.2.0
- name: hardening
source: https://git.example.com/infra/ansible-role-hardening.git
scm: git
version: v1.4
Install the declared content with:
ansible-galaxy install -r requirements.yml
A role can be selected by Galaxy namespace, a Git URL, a semantic-version tag or a commit hash. Pin a release or commit in production so a later upstream change cannot silently alter an infrastructure run.
Control where roles are installed
Use --roles-path on the command line or the ANSIBLE_ROLES_PATH environment variable when roles should be installed somewhere other than the default destination. Keep the chosen location consistent in local development and CI.
ansible-galaxy install -r requirements.yml --roles-path ./roles
Useful installation controls include:
--no-depsskips dependency installation when those dependencies are managed separately.--forceoverwrites an existing role.--force-with-depsoverwrites the role and its dependencies.--serverselects an alternate Galaxy server.--roles-pathchooses the installation directory.
Review a downloaded role’s tasks, variables, templates and dependencies before using it. Record the selected version in code review and update it deliberately; --force is not a substitute for reviewing an upgrade.
Organize an infrastructure repository
A predictable repository makes it obvious where environment selection ends and reusable behavior begins. A practical layout is:
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallansible/
inventories/
production/
staging/
group_vars/
playbooks/
site.yml
roles/
common/
webtier/
monitoring/
requirements.yml
ansible.cfg
Separate environments from role code
Inventory directories describe which hosts belong to each environment. Group and host variables provide environment-specific values. Playbooks compose roles into an operational sequence. Roles remain function-oriented and portable.
For example, production and staging can use the same webtier role while setting different listen ports, upstream addresses or certificate paths in their respective variable files. The role should not contain conditionals such as “if this is production” when an inventory value can express the difference.
Best Value
Configure roles_path when playbooks move
By default, Ansible searches collections, a roles/ directory relative to the playbook, configured roles_path locations and the playbook directory. If playbooks live under playbooks/ while roles remain at the repository root, configure the path explicitly:
[defaults]
roles_path = ./roles
Run commands from the directory where that relative path is meaningful, or use an absolute path in environments where the working directory is not guaranteed.
Local roles, shared Galaxy roles and collection roles
The right location depends on ownership, reuse and release discipline rather than on a universal preference.
| Approach | Ownership and review | Version strategy | When it fits | Main risk |
|---|---|---|---|---|
| Local role in your repository | Full control through your normal code review | Repository commits and release conventions | Organization-specific policy or rapidly evolving infrastructure | Reuse and compatibility can be limited if documentation and tests are weak |
| Role installed from Galaxy or Git | External publisher or shared internal source | Semantic version, tag or commit pin | Established capability used by several projects | Upstream changes, hidden side effects or unclear support matrix |
| Role delivered in a collection | Collection publisher and your dependency review | Collection version and its declared dependencies | Namespaced modules and a broader, versioned automation package | Collection compatibility must match your Ansible and platform versions |
Compare candidates on variable interface, supported operating systems, side effects such as service restarts, dependency transparency, test evidence, release cadence and compatibility with the Ansible version you run.
Make roles idempotent and safe to operate
Prefer state-based modules
Use modules that describe the desired state: package with state: present, file with an explicit state and mode, service with enabled and state, and template for managed configuration. A task should report changed only when it actually changes the host.
Notify handlers only on meaningful changes
Attach a handler notification to the task that changes the configuration. Avoid unconditional restarts after every run; unnecessary restarts increase downtime and can hide a configuration task that is not converging.
Use fully qualified collection names where required
Projects can require names such as ansible.builtin.template instead of the short name template. Follow the repository policy consistently and document any collection requirements alongside requirements.yml.
Use tags as an accelerator, not as a test strategy
Tags are useful for focused operations such as package installation or certificate renewal. A tag-only run can skip a prerequisite or handler path, however. Test the complete role in CI so a convenient operational shortcut does not conceal ordering problems.
Testing and compatibility
Test every operating-system distribution and Ansible version that the role claims to support. The role structure itself does not provide a universal test matrix; your team must choose and document one that reflects the estate you operate.
A practical test sequence
- Run syntax and lint checks against the role and the playbooks that call it.
- Execute the role on a clean test host for each supported platform.
- Run it a second time and confirm that no unintended changes occur.
- Change each documented input at least once, especially paths, ports and feature switches.
- Verify handlers, service health and rendered configuration after a change.
- Exercise dependency installation from a clean checkout using the pinned requirements.
Keep test fixtures separate from production inventories. Do not use real credentials or production endpoints merely because they make a test pass.
Troubleshoot common role failures
“Role was not found”
- Confirm the role directory name matches the name in the play.
- Check whether the role is under the configured
roles_pathor an expected relativeroles/directory. - Install repository dependencies before running the playbook.
- Use verbose output to inspect the inventory, playbook path and effective configuration.
A variable has the wrong value
- Check whether the value is defined in
defaults/main.yml,vars/main.yml, group variables, host variables or the play invocation. - Look for a higher-precedence definition that is overriding the value you changed.
- Confirm the variable name and type match the role documentation.
- Add early argument validation for interfaces that must not accept arbitrary values.
A service restarts on every run
- Inspect the template for unstable data such as a changing timestamp or unordered structure.
- Ensure the task uses a deterministic file mode, owner and content.
- Notify the handler from the configuration task rather than calling a restart unconditionally.
- Run the role twice on the same host and compare the change reports.
A dependency runs more than expected
- Compare the dependency’s parameters, tags and
whenclauses across invocations. - Check for nested dependencies that bring in the same role through different paths.
- Use
allow_duplicates: trueonly when repeated execution is intentional and safe.
An installed role changed unexpectedly
- Check whether
requirements.ymluses a floating version or branch. - Pin a semantic version, release tag or commit hash.
- Review the role’s changes before reinstalling, and avoid using
--forceas an unattended update mechanism.
A repeatable workflow for infrastructure repositories
- Define the capability. Write down what the role owns, which platforms it supports and what it must not change.
- Generate the skeleton. Run
ansible-galaxy role init role_nameand remove unused directories after the interface is clear. - Design defaults first. Put safe, overridable values in
defaults/main.ymland document them. - Implement convergence. Build ordered tasks with state-based modules, templates and handlers.
- Declare only mandatory prerequisites. Put those roles in
meta/main.yml; call optional roles explicitly from the play. - Compose environments. Keep inventories and environment values outside the role.
- Install dependencies reproducibly. Pin shared roles and collections in requirements files, then install them in development and CI.
- Test a clean run and a second run. Check both successful configuration and idempotence.
- Review side effects. Identify service restarts, firewall changes, file ownership changes and any required privileges.
- Upgrade deliberately. Review dependency changes through code review, test supported platforms and record the new version.
Operational checklist
- The role has one clear responsibility.
tasks/main.ymlis an understandable entry point.- Public variables have documented defaults, types and examples.
- Secrets are not stored in plaintext role files.
- Templates and files use explicit ownership and permissions where appropriate.
- Handlers run only after a real change.
- Dependencies in
meta/main.ymlare mandatory rather than merely convenient. - Optional capabilities are visible in the calling play.
- External roles are pinned in
requirements.yml. - The effective
roles_pathworks from developer machines and CI. - Tests cover every claimed distribution and Ansible version.
- A second application produces no unintended changes.
- The README records supported platforms, inputs, side effects and upgrade notes.
Bottom line
Use an Ansible role when a capability needs to be reused, reviewed and applied consistently. Generate the standard structure, keep the main flow in tasks/main.yml, expose a small set of safe defaults, put mandatory prerequisites in meta/main.yml, pin shared content, and keep environment data in inventories. With idempotent tasks, deliberate handlers, explicit dependencies and repeatable tests, the role becomes a dependable unit of infrastructure rather than another layer of hidden playbook complexity.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




