Chapter 5. Variables and Facts
Ansible is not a full-fledged programming language, but it does have several features of one, and one of the most important of these is variable substitution, or using the values of variables in strings or in other variables. This chapter presents Ansible’s support for variables in more detail, including a certain type of variable that Ansible calls a fact.
Defining Variables in Playbooks
The simplest way to define variables is to put a vars
section in your playbook with the names and values of your variables. Recall from Example 3-9 that we used this approach to define several configuration-related variables, like this:
vars: tls_dir: /etc/nginx/ssl/ key_file: nginx.key cert_file: nginx.crt conf_file: /etc/nginx/sites-available/default server_name: localhost
Defining Variables in Separate Files
Ansible also allows you to put variables into one or more files, which are then referenced in the playbook using a section called vars_files
. Let’s say you want to take the preceding example and put the variables in a file named nginx.yml instead of putting them right in the playbook. You would replace the vars
section with a vars_files
that looks like this:
vars_files: - nginx.yml
The nginx.yml file would look like Example 5-1.
Example 5-1. nginx.yml
key_file: nginx.key cert_file: nginx.crt conf_file: /etc/nginx/sites-available/default server_name: localhost
You’ll see an example of vars_files
in action in Chapter 6 when we use it to separate out ...
Get Ansible: Up and Running, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.