Ansible is an open source automated configuration management and deployment tool that helps administrators automate tasks on multiple servers.
In Ansible, Playbook is a YAML file used to describe automation tasks.
Using variables (variables) is an important part of Playbook functionality, which can make your Playbook more flexible, reusable and easy to maintain.
Variables can be defined in Playbooks, inventory files, vars files, or on the command line using the -e
parameter.
example:
Define variables in Playbook:
--- - name: Set up web server hosts: webservers vars: http_port: 80 max_clients: 200
Define variables in the inventory file:
[webservers] web1.example.com http_port=80 max_clients=200 web2.example.com http_port=8080 max_clients=100
Variables can be used in tasks, templates, conditional statements, etc.
example:
- name: Ensure Apache is running ansible.builtin.service: name: httpd state: started enabled: yes when: http_port == 80
After a task is executed, the result can be saved to a variable through the register
keyword.
example:
- name: Check if package is installed ansible.builtin.package_facts: register: package_info - name: Display package information ansible.builtin.debug: var: package_info
Ansible provides some built-in special variables, such as inventory_hostname
, ansible_facts
, etc.
example:
- name: Display the current host's name ansible.builtin.debug: var: inventory_hostname
In Ansible, the priority of variables from low to high is: default value, variables defined in the inventory file, variables in the Playbook, and command line parameters. Variable values with higher priority override variable values with lower priority.
After understanding the basic concepts and usage of Ansible Playbook variables, you can flexibly use variables according to actual needs to optimize your automation tasks.
The above is the detailed content of Ansible playbook variables (basic usage of variables). For more information, please follow other related articles on the PHP Chinese website!