Ansible does support passing the variables through files. The variable files can be created in JSON and YAML format.
We have covered Ansible Variables, and the Ansible Data Types in our earlier post,
Example of Ansible YAML variable file,
# variables in yaml
---
number: 10
str_ex: "john"
lists_ex:
- "new york"
- "london"
- "sydney"
- "mumbai"
map_ex:
- "name": "john"
- "address": "Chicago"
- "country": "US"
map_ex_2: {"os": "windows", "patch": "2.5", "version": 10}
Example of Ansible JSON variable file,
{
"number": 6,
"name": "Mike",
"list": [1, "apple", 5, "fruit"],
"map": {"os": "Ubuntu", "patch": "2.5", "version": 18.10}
}
Ansible playbook supports both single variable files as well multiple variable files.
Ansible playbook with single variable file,
---
# ansible play for variable through file
- name: Ansible supports variables from json and yaml files
hosts: localhost
vars_files: variable.yml
tasks:
- name: Lets print vales from single variable file
debug:
msg:
- "Printing value form variable file {{map_ex_2}}"
- "printing the secong map example {{map_ex}}"
Ansible playbook with multiple variable files,
# Ansible play to read variable through multiple files
- name: ansible playbook from multiple files
hosts: localhost
vars_files:
- variable.yml
- variable.json
tasks:
- name: Lets print the variables from two different files
debug:
msg:
- "Reading variable through json {{map}}"
- "Reading variable through YAML {{map_ex_2}}"
Summary:
Ansible variable files help in organizing variables in a single YAML/JSON file. That allows ease in the modification of the variables.
We don’t need to define the variables in each playbook. Instead, the variables can be defined in a file and called in all playbooks as per the requirements.
More details on Ansible Variables can be found on Ansible Official Documents