Ansible roles turn repeatable infrastructure work into reusable, reviewable packages. A role gives Ansible a predictable place for tasks, handlers, templates, files, variables, defaults, tests, and metadata. Once a role has a small, documented interface, the same behavior can be applied to development, staging, and production inventories without copying task files or embedding environment-specific values.
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 design a role, generate and call it, declare dependencies, install and pin shared roles, and organize a repository so operators can understand what will run and in what order.
As an Amazon Associate I earn from qualifying purchases.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteWhat an Ansible role is and why it matters
Ansible documentation defines roles as a way to automatically load related variables, files, tasks, handlers, and other Ansible artifacts from a known file structure. That convention is the important feature: a play does not need a long list of paths to find a role’s main task file, templates, or handlers.
A role should own one coherent capability. Examples include configuring a web server, applying a baseline hardening policy, installing a monitoring agent, or preparing an application runtime. It is not merely a folder for miscellaneous tasks. Keeping the boundary narrow makes inputs, supported platforms, side effects, and tests easier to explain.
#1 Best Overall
- BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
- EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
- COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
- LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
- WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
Roles also separate behavior from environment data. The role can provide safe defaults and portable tasks, while inventories and group or host variables supply production addresses, ports, credentials references, and other values that differ between environments.
Role anatomy: the directories Ansible understands
A role may contain only the directories it actually uses. The generated skeleton includes more directories, but unused ones can be removed. The conventional structure is:
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →| Path | Purpose | Typical contents |
|---|---|---|
tasks/main.yml |
Entry point and ordered task flow | Packages, configuration, service state, includes |
handlers/main.yml |
Actions notified after a change | Service reloads or restarts |
templates/ |
Jinja templates rendered by the template module |
Configuration files with variables and conditionals |
files/ |
Static files copied to managed hosts | Certificates, scripts, or fixed configuration fragments |
defaults/main.yml |
Low-precedence, user-overridable values | Ports, package names, feature switches |
vars/main.yml |
Role variables with higher precedence than defaults | Values that should not normally be overridden |
meta/main.yml |
Dependencies and optional Galaxy metadata | Prerequisite roles and supported metadata |
tests/ |
Role-level test scaffolding | Test inventory, test playbook, or framework configuration |
README.md |
Human-facing interface documentation | Inputs, examples, platforms, side effects, and limitations |
The required minimum is one standard role directory; a role containing only tasks can omit templates, files, handlers, or variables. Keep the main flow in tasks/main.yml. If it becomes difficult to review, split platform-specific or lifecycle sections with task includes while retaining a clear entry point.
Create a role from a predictable skeleton
Use the Galaxy command-line tool to create the standard layout:
ansible-galaxy role init webserver
The command creates a role named webserver with directories such as defaults/, files/, handlers/, meta/, tasks/, templates/, tests/, and vars/, plus a README. Start by removing directories that the role will never use, then define its interface before filling in implementation details.
Define defaults first
Put safe, commonly overridden values in defaults/main.yml. For a web server, that might include a listen port or a package name. Defaults have low precedence so an inventory, play, or role invocation can change them. Avoid putting passwords, private keys, production hostnames, or environment-specific addresses in the role.
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 →Implement the ordered flow
Write the main behavior in tasks/main.yml. A typical sequence installs packages, renders configuration, notifies a handler when configuration changes, and enables the service. Use idempotent modules and meaningful task names so a check-mode run explains what Ansible intends to change.
Add handlers only for state changes
Handlers run when notified by a changed task. A template task should notify a reload or restart only when its rendered content differs. Do not notify a handler from every invocation: unnecessary restarts create avoidable downtime and make later troubleshooting harder.
Rank #2
- WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
- AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
- PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
- ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
- COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
Document the contract
In the role README, list required variables, defaults, supported operating systems, the Ansible and collection versions you test, files or services changed, ports opened, and whether a run can restart a service. Include a minimal play example and explain any variables whose values are mutually dependent.
Call a role from a play
The roles section applies a role to the hosts selected by the play:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows 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 reinstall- hosts: webservers
roles:
- role: webserver
webserver_listen_port: 8080
Variables placed on the role entry customize that invocation. This is useful when the same role is used for multiple groups with different ports or feature settings. Keep the interface small: every exposed variable should have a documented purpose and a safe behavior.
Ansible can run the same role more than once when parameters differ. Metadata can explicitly allow duplicate execution with allow_duplicates: true; otherwise Ansible normally avoids repeating an identical role invocation. If a role relies on duplicate execution, document why, because ordering and side effects become part of its contract.
Choose between roles, include_role, and import_role
Use the play-level roles list for the normal, declarative case. Use include_role when a role must be selected conditionally or inserted at a specific task location; its inclusion is evaluated during execution. Use import_role when static parsing and predictable expansion are more important. Static imports make task discovery and some validation easier, while dynamic inclusion is better for runtime decisions.
Do not hide optional capabilities in mandatory dependencies. If monitoring, backups, or a diagnostic agent is optional, call its role explicitly from the play so operators can control conditions and tags.
Recommended Free Tools
Declare role dependencies and understand execution order
Prerequisites belong in meta/main.yml. For example:
---
dependencies:
- role: common
- role: firewall
vars:
firewall_allowed_ports: [80, 443]
Ansible runs each listed dependency before the role that declares it and resolves nested dependencies recursively. A role depending on common, which itself depends on base, causes base to run before common, followed by the declaring role. These are prerequisites, not an ownership hierarchy; the play still decides which top-level roles are used.
Rank #3
- Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
- Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
- Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
- ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
- Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
Use a dependency only when every invocation genuinely requires it. A dependency that opens ports, changes repositories, or restarts services can surprise users who expected a focused role. Put optional behavior in the play instead, where tags, conditions, and ordering are visible.
Duplicate dependencies normally execute once. Ansible may treat invocations as distinct when parameters, tags, or when conditions differ. Set allow_duplicates: true in role metadata when deliberate repeated execution is required, and explain the expected result in the README.
Free tools Windows power users keep installed
One-click scans. No signup required.
Install and pin shared roles
External role content should be treated like application code. Record its source and an immutable or deliberately selected version in requirements.yml:
---
roles:
- name: apache_role
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
Requirements can identify Galaxy content by namespace, a Git URL, a semantic-version tag, or a commit hash. Pin a release or commit in production instead of installing an unconstrained latest version. Review upgrades in code review, record the selected version, and run the complete role test suite before rollout.
Useful installation controls
--roles-pathselects the destination directory. TheANSIBLE_ROLES_PATHenvironment variable provides another way to configure it.--no-depsskips dependency installation when dependencies are intentionally managed elsewhere.--forceoverwrites an existing role.--force-with-depsoverwrites the role and its dependencies.--serverselects an alternate Galaxy server.
Use overwrite options sparingly. They can conceal an accidental version change or make a workstation differ from a clean CI checkout. A controlled process removes or replaces the selected version deliberately, then verifies the resulting dependency graph.
Review downloaded content
Inspect tasks, templates, variables, handlers, and metadata before allowing a shared role into an infrastructure run. Check which distributions and Ansible versions it supports, whether it changes repositories or firewall rules, which services it restarts, and whether its defaults conflict with your organization. Treat a role update as a code change, not as a package refresh with no operational impact.
Organize an infrastructure repository
A predictable repository keeps environment selection separate from reusable behavior. One practical layout is:
ansible/
inventories/
production/
staging/
group_vars/
playbooks/
site.yml
roles/
common/
webtier/
monitoring/
Inventories and variables
Put host and group membership in the environment inventory. Keep environment-specific values in inventory, group_vars, or host_vars. The role should expose documented defaults and consume variables rather than embedding production names, addresses, or credentials.
Rank #4
- Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
- Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
- 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
- Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
- USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
Role discovery and roles_path
Ansible searches collections, a roles/ directory relative to the playbook, configured roles_path locations, and the playbook directory. If playbooks live in playbooks/ while roles remain at repository root, configure the path explicitly:
[defaults]
roles_path = ./roles
Use the same configuration in local development and CI. A role that works only because a developer has a personal search path is not reproducible.
Separate function-oriented roles
A common role can establish shared prerequisites, while webtier and monitoring own their respective capabilities. Avoid one giant role containing every service in the estate. Smaller roles make dependency order, ownership, and rollback decisions visible.
Design variables, precedence, and secrets carefully
Defaults are intended for consumers to override. Variables in vars/main.yml have higher precedence and should be reserved for values that are part of the role’s implementation contract. Do not use vars merely to make a value convenient to find; doing so can prevent an inventory from changing it as intended.
Validate strict inputs early with argument specifications where supported by your Ansible version. Fail with a clear message when a port is outside its valid range, a required path is missing, or two feature switches are incompatible. Early validation is safer than allowing a malformed template or package command to fail halfway through a deployment.
Keep secrets in an approved secret store or encrypted variable mechanism. Never commit plaintext credentials to defaults, templates, test fixtures, or example inventories. Templates should receive secret values at execution time and should set appropriate file permissions when writing sensitive material.
Tags, task includes, and operational control
Tags can provide focused runs, such as applying only configuration or only package installation. They are useful during maintenance, but a tag-selected run may skip a prerequisite task and leave the host in an unexpected state. Test the complete role path in CI and document which tags are safe independently.
Use task includes to keep platform-specific or lifecycle sections readable:
Best Value
- Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
- Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
- Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
- Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
- Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
- name: Load distribution-specific tasks
include_tasks: "{{ ansible_facts.os_family | lower }}.yml"
when: ansible_facts.os_family in ['Debian', 'RedHat']
Keep the dispatch logic in tasks/main.yml and make unsupported platforms fail explicitly rather than silently doing nothing. This makes the role’s support boundary clear.
Testing and release discipline
Test every operating-system distribution and Ansible version that the role claims to support. The official role documentation defines structure and installation, but it does not prescribe a universal test matrix; choose one that reflects your estate and document it in the README and CI configuration.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
- Run syntax and lint checks on every change.
- Exercise a clean installation and a second run to verify idempotence.
- Test changed templates and handlers, including the no-change path where no restart should occur.
- Run supported-platform jobs rather than testing only the developer’s distribution.
- Test dependency installation from a clean checkout using the pinned requirements file.
- Review generated files, permissions, enabled services, and firewall effects.
Release a role only after its interface, supported versions, dependency pins, and known side effects are recorded. Consumers can then upgrade deliberately instead of discovering behavior changes during a production run.
Local, shared, and collection-based roles: choosing an approach
| Approach | Ownership and review | Version strategy | Best fit | Risks to check |
|---|---|---|---|---|
| Local role in the repository | Full control by the infrastructure team | Repository revision and code review | Organization-specific provisioning and policy | Duplicated work if interfaces are not documented |
| Shared role installed from Galaxy or Git | External publisher plus internal review | Semantic version, tag, or commit pin | Common capabilities that benefit from reuse | Unreviewed changes, hidden dependencies, platform mismatch |
| Role delivered in a collection | Collection publisher and your dependency policy | Collection version and its requirements | Related modules, plugins, and roles released together | Collection compatibility and larger upgrade surface |
Compare ownership, update cadence, dependency transparency, supported operating systems, variable interfaces, service side effects, and test evidence. A popular role is not automatically suitable for your estate; compatibility and reviewability matter more than name recognition.
Troubleshoot common role failures
“Role not found”
Check the role directory name, the playbook’s working directory, and the configured roles_path. If the role is external, verify that ansible-galaxy install -r requirements.yml completed into the path Ansible searches. In CI, print the effective configuration and install dependencies from a clean workspace.
Variables appear to be ignored
Confirm the variable name and scope, then inspect whether a value in vars/main.yml or another higher-precedence source is overriding your default. Keep role defaults low-precedence and avoid redefining the same setting in several inventory layers.
A handler never runs
A handler runs only after a notifying task reports a change. Verify that the task uses notify, that the rendered content actually differs, and that tags or conditions did not skip the task. If an immediate action is required at a particular point, use an explicit flush only when the ordering requirement is understood.
A dependency runs unexpectedly
Read the declaring role’s meta/main.yml and follow nested dependencies. Remove optional capabilities from metadata and call them explicitly from the play. Check whether differing parameters, tags, or conditions are causing what looks like a duplicate execution.
The role works on one distribution only
Separate platform-specific tasks, use facts to select supported implementations, and fail clearly for unsupported families. Add the missing distribution to the documented test matrix before claiming support.
A shared-role upgrade changes hosts
Compare the old and new task, template, default, and dependency content. Confirm the version or commit in requirements.yml, test in a non-production inventory, and review service, repository, firewall, and permission changes before rollout. Do not resolve drift by repeatedly using --force without recording which version was selected.
Quick Recap
A repeatable workflow
- Define one capability and list its supported platforms, required inputs, defaults, and side effects.
- Generate the skeleton with
ansible-galaxy role init role_name. - Remove unused directories and implement the ordered flow in
tasks/main.yml. - Add templates, static files, handlers, defaults, and validation only where the capability needs them.
- Declare only mandatory prerequisites in
meta/main.yml. - Write a README with invocation examples, variable descriptions, platform support, and operational warnings.
- Call the role from a play and keep environment values in inventories and variable files.
- Pin external roles and collections in requirements files, then install them in local and CI environments.
- Run syntax, lint, idempotence, dependency, and supported-platform tests.
- Promote the same reviewed commit through staging and production rather than copying or editing role tasks per environment.
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.




