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 thedns_server variable is specified only for host web2:
dns_server variable for all hosts:
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 variablentp_server in one play but not in another:
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:ntp_server variable is set globally:
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
| Scope Type | Description | Example Usage |
|---|---|---|
| Host Scope | Variables defined for a specific host are available only when tasks are executed on that host. | Inventory file entries like dns_server=10.5.5.4 on web2 |
| Play Scope | Variables set within a play are confined to that play and do not persist to subsequent plays. | Defined with vars: in a play block |
| Global Variables | Variables passed via command-line extra-vars or defined globally, accessible across all plays. | ansible-playbook playbook.yml --extra-vars "ntp_server=10.1.1.1" |