Ansible: Variables
Variables in Ansible are used to make your playbooks flexible and reusable. Here’s how you start with simple variable definitions.
1. Example: Defining Variables in playbook
- name: Example Playbook with Vars
hosts: webservers
become: yes
vars:
app_port: 80
web_package: apache2
admin_email: [email protected]
tasks:
- name: Install web server package
apt:
name: "{{ web_package }}"
state: present
- name: Show app port
debug:
msg: "Application will run on port {{ app_port }}"
- name: Show admin email
debug:
msg: "Admin email is {{ admin_email }}"
2. Example: Defining Vars in a Separate File
vars.yml:
app_port: 80
web_package: apache2
admin_email: [email protected]
Playbook using vars file:
- name: Use external vars file
hosts: webservers
become: yes
vars_files:
- vars.yml
tasks:
- name: Install web server package
apt:
name: "{{ web_package }}"
state: present