Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Ansible variables let one playbook deploy different hosts, environments and releases without copying tasks. Define values in playbooks, inventory files, role files or at runtime, then reference them with Jinja expressions such as {{ app_port }}. The important discipline is knowing where a value is defined, which definition wins when names collide, and how to inspect the value Ansible is actually using.

What an Ansible variable is

A variable is a named value that Ansible makes available while it parses or runs a playbook. The value can be a string, number, Boolean, list, dictionary, discovered fact, command result or a value calculated during the run. Tasks consume variables to choose packages, build configuration files, set service options and target different hosts with the same automation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A variable reference is normally written as a Jinja expression:

server_name: "{{ inventory_hostname }}"
listen_port: "{{ app_port }}"

Use a variable in a module argument, a template, a condition or a loop. Keep the variable name itself free of spaces and punctuation that would make it difficult to read. Names such as app_port, database_host and tls_enabled communicate intent better than single letters.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application:Upgraded attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Warranty & Support: Our Electric air duster comes with 5 years warranty and 24/7 customer service. During this period, if you have any questions,pls kindly feel free to contact us.

Choose the right place to define a value

Ansible reads variables from several sources. The best source depends on who owns the value and whether it should change between hosts, groups, environments or runs.

Play variables for values local to one play

Use a play’s vars section for constants that belong to that play and are unlikely to be shared elsewhere.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
- name: Configure the web tier
  hosts: web
  vars:
    app_name: catalog
    app_port: 8080
    app_user: catalog
  tasks:
    - name: Show the selected port
      ansible.builtin.debug:
        msg: "{{ app_name }} listens on {{ app_port }}"

This keeps a small play self-contained. If several plays or roles need the same setting, move it to inventory variables or a role-specific variable file rather than duplicating it.

Inventory group_vars for shared group settings

Put values shared by all members of an inventory group in group_vars. A common layout is:

inventory/
├── hosts.yml
group_vars/
├── all.yml
└── web.yml

group_vars/all.yml can hold organization-wide defaults, while group_vars/web.yml can hold settings for hosts in the web group.

# group_vars/web.yml
app_port: 8080
app_workers: 4
log_format: json

Group variables are a good fit for environment-wide or tier-wide configuration because adding a host to the group automatically gives it the group’s values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Inventory host_vars for per-host exceptions

Use host_vars when one host needs a different value from the rest of its group:

host_vars/web-03.yml
---
app_port: 8081
app_workers: 2

In the usual inventory model, host-specific data is more specific than group data. The official ansible-core 2.15 precedence documentation places host_vars above group_vars; use that relationship for deliberate exceptions, and verify the exact ordering for the ansible-core version you run.

vars_files for separate configuration sets

A play can load variables from one or more files. This is useful when development, staging and production values should be kept in separate files or maintained by different teams.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth
- name: Deploy the application
  hosts: app
  vars_files:
    - vars/common.yml
    - vars/staging.yml
  tasks:
    - name: Render application configuration
      ansible.builtin.template:
        src: app.conf.j2
        dest: /etc/catalog/app.conf
        mode: "0644"

Keep the file names and selection logic explicit. A variable file should contain data, not tasks.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Role defaults and role variables

Roles commonly expose safe, overridable defaults and keep implementation details inside the role. A role’s default values are intended to be changed by the caller; role-internal variables are more restrictive. Because the exact precedence of role defaults and other role variables is version-dependent, document which settings are public inputs and test overrides on the ansible-core version used in your automation.

set_fact for values calculated during a run

ansible.builtin.set_fact creates a variable while a play is running. Use it after a task has gathered or transformed information.

- name: Select the release directory
  ansible.builtin.set_fact:
    release_path: "/opt/{{ app_name }}/releases/{{ release_id }}"

- name: Create the release directory
  ansible.builtin.file:
    path: "{{ release_path }}"
    state: directory
    owner: "{{ app_user }}"
    mode: "0755"

A fact created this way can persist in fact-cache configurations when caching is enabled. That persistence is useful for expensive calculations but can also leave an old value hiding a corrected inventory value. Clear or recalculate the fact when changing the source data.

register for a task’s result

register stores the result returned by a task. Registered data is a dictionary that can include fields such as stdout, rc, changed and status information, depending on the module.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
- name: Check whether the marker exists
  ansible.builtin.stat:
    path: /etc/catalog/installed
  register: marker

- name: Install the marker
  ansible.builtin.file:
    path: /etc/catalog/installed
    state: touch
  when: not marker.stat.exists

Register only the result you need and give it a descriptive name. A registered variable exists after its task executes; design conditions so they do not assume a result that was skipped or never reached.

Reference variables safely in tasks and templates

Module arguments

Put the Jinja expression where the module expects a value. Quoting the complete expression is the safest style for strings and paths:

- name: Install the selected package
  ansible.builtin.package:
    name: "{{ package_name }}"
    state: present

For a list or dictionary that must remain a native data structure, define it as YAML data and pass the variable without converting it to a string:

allowed_ports:
  - 80
  - 443

- name: Allow application ports
  ansible.posix.firewalld:
    port: "{{ item }}/tcp"
    permanent: true
    state: enabled
  loop: "{{ allowed_ports }}"

Templates

Jinja templates use the same expression syntax. Keep configuration data in variables and formatting in the template:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
# templates/catalog.conf.j2
server_name={{ server_name }}
port={{ app_port }}
workers={{ app_workers }}

Render it with the template module:

- name: Write catalog configuration
  ansible.builtin.template:
    src: catalog.conf.j2
    dest: /etc/catalog/catalog.conf
    owner: root
    group: root
    mode: "0644"
  notify: Restart catalog

Conditionals

Conditions are expressions, so do not wrap the entire when value in Jinja delimiters:

- name: Install TLS support
  ansible.builtin.package:
    name: openssl
    state: present
  when: tls_enabled | bool

Use explicit type conversions such as | bool when a value may arrive as a string from inventory or an extra variable. This prevents a textual value such as "false" from being treated as an unintended truthy value.

Defaults for optional data

Use the default filter when a variable is optional:

environment_name: "{{ deploy_environment | default('development') }}"

Decide whether an empty value should also trigger the default. If so, pass the filter’s second argument as true:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
effective_region: "{{ region | default('us-east', true) }}"

For required inputs, fail early rather than silently selecting an unsafe value:

- name: Require an application version
  ansible.builtin.assert:
    that:
      - app_version is defined
      - app_version | length > 0
    fail_msg: "Set app_version in inventory or with --extra-vars."

Use lists and dictionaries for structured configuration

Lists and loops

Represent repeated items as a YAML list and iterate over it:

packages:
  - nginx
  - curl
  - ca-certificates

- name: Install required packages
  ansible.builtin.package:
    name: "{{ item }}"
    state: present
  loop: "{{ packages }}"

For related attributes, use a list of dictionaries:

listeners:
  - name: http
    port: 80
    protocol: tcp
  - name: https
    port: 443
    protocol: tcp

- name: Configure listeners
  ansible.builtin.debug:
    msg: "{{ item.name }} uses {{ item.protocol }} port {{ item.port }}"
  loop: "{{ listeners }}"

Dictionaries and nested values

Dictionaries group settings under one variable and can be accessed with either bracket notation or, when unambiguous, dot notation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
database:
  host: db.internal
  port: 5432
  name: catalog

- name: Display the database endpoint
  ansible.builtin.debug:
    msg: "{{ database['host'] }}:{{ database['port'] }}/{{ database['name'] }}"

Bracket notation is safer when a key contains punctuation or could collide with a dictionary method.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Understand variable precedence before overriding a value

If the same variable name is defined in several places, Ansible loads all definitions and chooses one according to its precedence rules. The practical consequence is that a correct value in group_vars may not be the value a task receives if a more specific source defines the same name.

What the official documentation establishes

The exact stack is tied to the Ansible release. The ansible-core 2.15 documentation describes a 13-step ordering that includes command-line values, role defaults, inventory and playbook group variables, host variables, facts and cached facts, play variables and prompted variables. Ansible 7 documentation describes a longer 22-step ordering that additionally distinguishes sources such as vars_files, role variables, block variables, task variables, include_vars, set_fact, registered variables and role or include parameters.

Both documented versions put extra variables supplied with --extra-vars (or -e) at the top. Exact placement of set_fact, registered results, include parameters and some role-related sources differs between versions and is not interchangeable. Use the precedence page for the ansible-core version installed in your execution environment when an exact numeric order matters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical override hierarchy

Source Best use Typical override expectation
Role defaults Safe, documented inputs to a reusable role Designed to be overridden
group_vars Shared values for an inventory group More general than host-specific data
host_vars One-host exceptions More specific than group data in the documented model
Play vars and vars_files Values owned by a play or deployment configuration Can override lower inventory sources, subject to version rules
set_fact and registered results Values produced during execution Can take precedence over file-based values; verify exact placement for your version
Extra variables (-e) Intentional run-specific override Highest precedence in the documented models

Prevent accidental collisions

Use role- or application-specific prefixes such as catalog_app_port instead of generic names such as port. Keep one authoritative definition for each setting, and reserve -e for deliberate overrides such as a release identifier or emergency feature flag.

A common failure pattern is a stale set_fact: inventory is corrected, but the already-created fact remains the value consumed by later tasks. Recompute the fact, remove the cached value when applicable, or rename the calculated variable so its lifecycle is obvious.

Duplicate definitions inside one vars section

The official ansible-core 2.15 documentation states that when a variable is defined twice in the same play’s vars section, the later definition wins. Do not rely on that behavior for readability; remove duplicates and keep one declaration.

Groups that define the same variable

When multiple groups provide the same variable, the latest-loaded definition wins according to the current “Using variables” documentation. Inventory composition and load order therefore matter. Make the value explicit in a more specific host or environment file instead of depending on an incidental group order.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Pass values at runtime with extra variables

Extra variables are useful for a value that changes from one invocation to the next:

ansible-playbook deploy.yml -e "app_version=2026.10.14" -e "deploy_environment=staging"

Because extra variables have the highest precedence in the documented models, they are an effective emergency override. They can also mask mistakes: a value passed by a wrapper script or CI job may silently defeat the inventory value you are editing. Log the selected deployment inputs and remove temporary overrides after the run.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

For structured data, pass valid YAML or JSON and quote the shell argument so the shell does not reinterpret spaces or special characters:

ansible-playbook deploy.yml -e '{"feature_flags":{"new_ui":true},"replicas":3}'

Do not put passwords or tokens directly in a process command line where other users or monitoring systems may see them. Use an appropriate secret-management method and limit which variables are printed by debugging tasks.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Inspect the value Ansible will use

Print a variable during a run

The debug module is the quickest check inside a play:

- name: Inspect deployment inputs
  ansible.builtin.debug:
    msg:
      - "host={{ inventory_hostname }}"
      - "environment={{ deploy_environment | default('unset') }}"
      - "port={{ app_port | default('unset') }}"

Use var when you want Ansible to display a variable and its structure:

- name: Inspect the database object
  ansible.builtin.debug:
    var: database

Remove or protect verbose debugging before sharing logs, especially when a dictionary may contain credentials.

Check inventory data before running a play

The ansible-inventory command can render the inventory Ansible has parsed. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ansible-inventory -i inventory/hosts.yml --list
ansible-inventory -i inventory/hosts.yml --host web-03

These checks help detect a misspelled host name, a host in the wrong group or a variable file in an unexpected location. Compare the parsed data with the files you intended to load.

Trace a collision

  1. Search the project for every definition of the variable name, including group_vars, host_vars, role files, play files and wrapper scripts.
  2. Run the play with a debug task that prints the effective value and the host receiving it.
  3. Check whether a previous task creates the same name with set_fact or register.
  4. Inspect the command line and CI job for -e arguments.
  5. Confirm the precedence documentation for the installed ansible-core version before changing file order or relying on a numeric rank.

Design variables that remain maintainable

Separate data from tasks

Tasks should describe actions; variable files should describe environment and application data. This makes a role reusable and lets reviewers change a port, package list or endpoint without editing task logic.

Document units and acceptable values

Name variables so units are obvious: timeout_seconds, memory_mb and retention_days. Add assertions for ranges and enumerated choices:

- name: Validate deployment environment
  ansible.builtin.assert:
    that:
      - deploy_environment in ['development', 'staging', 'production']
      - app_port | int > 0
      - app_port | int < 65536
    fail_msg: "Set a valid environment and TCP port."

Keep types consistent

Choose one representation for each setting. A port should be numeric data, not sometimes 8080 and sometimes the string "8080". Convert at boundaries with filters when input sources cannot be standardized.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use safe names for registered results

Registered results are dictionaries, so names such as package_check and service_status make their purpose clear. Avoid reusing a registered name for a different module later in the same play; the changed structure can make later conditions fail.

Keep secrets out of ordinary variables

Variables are convenient, but values can appear in task output, fact caches, generated files or command-line process lists. Mark secret-consuming tasks with appropriate no-log protection, avoid printing secret dictionaries, and store sensitive values in a mechanism intended for secrets rather than ordinary inventory files.

Troubleshoot common variable errors

“Variable is undefined”

  • Check spelling and capitalization; variable names are case-sensitive.
  • Confirm the host belongs to the inventory group whose group_vars file you expect.
  • Verify that the play loads the intended vars_files entry.
  • Check whether a task that creates the value was skipped or has not run yet.
  • Use default for genuinely optional values, or an assertion for required inputs.

The value is defined but the wrong one is used

  • Search for duplicate definitions across all variable sources.
  • Check for a host-specific exception overriding a group value.
  • Look for set_fact, cached facts, registered data or -e on the command line.
  • Check group load order when several groups define the same name.
  • Verify precedence against the installed ansible-core documentation rather than a guide written for another release.

A condition behaves unexpectedly

  • Inspect the value and its type with debug.
  • Convert textual booleans with | bool.
  • Use parentheses when combining and and or.
  • Guard nested data with is defined before accessing it.

A template renders an empty or literal expression

  • Confirm the file is processed by the template module and has a .j2 source.
  • Check that the expression uses matching {{ and }} delimiters.
  • Quote strings that contain YAML characters or leading special characters.
  • Print the source variable before rendering to distinguish a template typo from missing data.

A repeatable workflow for variable-driven playbooks

  1. List the inputs the playbook needs: hosts, package names, ports, paths, feature flags and credentials.
  2. Choose an owner for each input: role default, group variable, host variable, play variable, variable file or runtime value.
  3. Define structured data with stable names and documented units.
  4. Add assertions for required values, ranges and allowed choices.
  5. Reference values in tasks and templates with explicit quoting and type conversion where needed.
  6. Run an inventory inspection and a safe debug check against a non-production host.
  7. Test one intentional override with --extra-vars, then confirm that the resulting value is the one the task receives.
  8. Remove temporary debug output and review logs for exposed secrets.
  9. When upgrading Ansible, recheck precedence-sensitive behavior against the documentation for that ansible-core release.

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.