Passing Variables to Ansible Playbooks
Now that you have a basic understanding of Ansible variables, let's explore how to pass variables to your Ansible playbooks. There are several ways to do this:
Command-line Arguments
You can pass variables to your playbook using the -e
or --extra-vars
option when running the ansible-playbook
command.
ansible-playbook site.yml -e "app_version=2.2 db_host=10.0.0.60"
Variable Files
You can define variables in separate YAML files and pass them to your playbook using the --extra-vars
option.
ansible-playbook site.yml --extra-vars "@vars.yml"
## vars.yml
app_name: MyApp
app_version: 2.2
db_host: 10.0.0.60
Inventory Variables
As mentioned in the previous section, you can define variables in your inventory file and they will be available to your playbook.
## inventory.yml
all:
hosts:
webserver1:
ansible_host: 192.168.1.100
app_version: 2.0
webserver2:
ansible_host: 192.168.1.101
app_version: 2.1
Playbook Variables
You can also define variables within your playbook using the vars
keyword.
- hosts: webservers
vars:
app_name: MyApp
app_version: 2.2
db_host: 10.0.0.60
tasks:
- name: Print variables
debug:
msg: "App name: {{ app_name }}, App version: {{ app_version }}, DB host: {{ db_host }}"
By understanding these different ways of passing variables to your Ansible playbooks, you can make your automation more flexible and adaptable to different environments and requirements.