Skip to Content
Ansible: Up and Running, 3rd Edition
book

Ansible: Up and Running, 3rd Edition

by Bas Meijer, Lorin Hochstein, René Moser
July 2022
Intermediate to advanced
470 pages
10h 22m
English
O'Reilly Media, Inc.
Book available
Content preview from Ansible: Up and Running, 3rd Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Kubernetes: Up and Running, 3rd Edition

Kubernetes: Up and Running, 3rd Edition

Brendan Burns, Joe Beda, Kelsey Hightower, Lachlan Evenson
Dive Into Ansible - From Beginner to Expert in Ansible

Dive Into Ansible - From Beginner to Expert in Ansible

James Spurin - Docker Captain, CNCF Ambassador, and Kubestronaut
Docker: Up & Running, 3rd Edition

Docker: Up & Running, 3rd Edition

Sean P. Kane, Karl Matthias

Publisher Resources

ISBN: 9781098109141Errata PageSupplemental Content