Ansible变量是用于在Ansible playbook中存储和传递数据的工具。变量可以在不同的场景下使用,例如,定义主机、定义任务和处理模板等。
在Ansible中定义变量,可以通过多种方式实现,例如,在主机清单文件或变量文件中定义,或通过在playbook中使用变量声明任务。
代码示例:
在主机清单文件中定义变量:
[webservers]
web1 ansible_host=192.168.1.10 http_port=80
web2 ansible_host=192.168.1.11 http_port=80
在playbook中使用变量:
- name: Install Apache
hosts: webservers
become: yes
vars:
http_port: 80
max_clients: 200
tasks:
- name: Install apache
yum: name=httpd state=latest
- name: Copy main config file
template:
src: /srv/httpd.j2
dest: /etc/httpd.conf
notify:
在变量文件中定义变量:
http_port: 80
max_clients: 200
在playbook中引用变量文件:
- name: Install Apache
hosts: webservers
become: yes
vars_files:
- vars/webserver.yml
tasks:
- name: Install apache
yum: name=httpd state=latest
- name: Copy main config file
template:
src: /srv/httpd.j2
dest: /etc/httpd.conf
notify: