Skip to main content
Understanding variable scope in Ansible is essential for effective configuration management. In this guide, we explore three primary scopes: Host Scope, Play Scope, and Global Variables. Mastering these concepts will help you write cleaner, more modular playbooks and troubleshoot variable-related issues more efficiently.

Host Scope

Host-specific variables are defined directly in the inventory file or host-specific configurations. These variables are available only when tasks are executed on that host. Consider the following inventory file where the dns_server variable is specified only for host web2:
When executing a playbook that prints the dns_server variable for all hosts:
The play output is as follows:
In this case, the dns_server variable is only defined for web2, so it is accessible solely in the host scope for that specific host.

Play Scope

Variables defined within a play are confined to that play’s context. They do not persist into subsequent plays unless declared globally. This helps maintain clear boundaries for variable lifecycles within your playbook. Consider the following playbook that uses the variable ntp_server in one play but not in another:
The output for this playbook is:
Variables set within a play are only available in that play. In the example above, ntp_server is defined in the first play and is not accessible in the second play.

Global Variables

Global variables are accessible across all plays and tasks within a playbook. A common method to define global variables is by passing them as extra variables using the command line. Consider a playbook without explicit variable definition in any play:
When you run the playbook with the following command, the ntp_server variable is set globally:
The output will show that ntp_server is available in both plays:
Passing ntp_server as an extra variable sets it as a global variable, making it accessible to every play and task in the playbook.

Summary of Variable Scopes

Having a solid grasp of these scopes will not only help in writing efficient and modular playbooks but also in troubleshooting and managing Ansible configurations effectively. Thank you for reading this article. Happy automating, and see you in the next guide!

Watch Video