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
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!