Search⌘ K
AI Features

Basics of Variables

Explore the fundamentals of using variables in Ansible to create dynamic and reusable configurations. Understand variable naming rules, different scopes such as global, play, and host, and how variable precedence impacts configurations. Learn best practices to organize variables for efficient and maintainable Ansible playbooks.

Overview

Using variables gives us the flexibility required in configuration management projects. Variables are essential components of Ansible playbooks and roles that enable us to parameterize our tasks, creating a dynamic, flexible, and reusable configuration.

We can parameterize tasks through variables, which in turn leaves us with playbooks and roles that are not only adaptable but also easier to maintain. Instead of hardcoding values directly into our tasks, we use variables to centrally manage the part of our configuration that’s bound to constantly change.

Here’s an example that shows a virtual host configuration in Apache with the use of relevant variables, such as web_server_port, web_server_document_root, APACHE_LOG_DIR, and web_server_index_file to keep the configuration dynamic:

Shell
# apache.conf
<VirtualHost *:{{ web_server_port }}>
DocumentRoot {{ web_server_document_root }}
<Directory {{ web_server_document_root }}>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
DirectoryIndex {{ web_server_index_file }}
</VirtualHost>

The variables within the apache.conf configuration file are ...