In Ansible, you can define variables in several ways. Here are the most common methods:
In the Playbook: You can define variables directly within your playbook using the
varssection.- hosts: all vars: http_port: 80 db_port: 3306 tasks: - name: Print HTTP port debug: msg: "HTTP port is {{ http_port }}"In Inventory Files: You can define host or group variables in your inventory file.
[web] localhost http_port=80 [db] localhost db_port=3306In Variable Files: You can create separate YAML files to store variables and include them in your playbook. For example, create a file named
vars.yml:http_port: 80 db_port: 3306Then include it in your playbook:
- hosts: all vars_files: - vars.yml tasks: - name: Print HTTP port debug: msg: "HTTP port is {{ http_port }}"As Facts: Ansible automatically gathers facts about the managed nodes, which can be used as variables. You can access these facts using the
ansible_factsvariable.- hosts: all tasks: - name: Print OS version debug: msg: "Operating System is {{ ansible_facts['os'] }}"Using Command Line: You can also pass variables at runtime using the
-eoption with theansible-playbookcommand.ansible-playbook my-playbook.yml -e "http_port=80 db_port=3306"
These methods allow you to define and manage variables effectively in your Ansible automation tasks.
