1、Variables Defined In Inventory
[webservers] app1_server http_port=8080 #app1_server的主机变量 [websevers:vars] #webservers组的变量 one=hello two=world /etc/ansible/host_vars/app_server #app_server主机变量 /etc/ansible/group_vars/webservers #webservers主机组变量
2、Variables Defined In Playbook
#定义单个变量 vars: - name: dxx - age: 14 #定义变量文件 vars_files: - variables.yml #定义变量交互赋值 vars_prompt: - name: version prompt: please input version private: no
3、Variables Defined In Command
ansible-playbook main.yml -e 'init="begin" final="end"' #变量赋值 ansible-playbook main.yml -e '{"init":"begin","final":"end"}' #json字符串 ansible-playbook main.yml -e '@test.json' #json文件
4、Variables Defined In Register
- hosts: mfs_node task: - shell: echo "5" register: result #注册result变量即shell命令执行的结果状态 ignore_errors: True #忽略错误 - debug: msg="it failed" when: result|failed #如果结果为失败输出debug信息,有success、failed状态 - debug: msg="{{result.stdout}}" #输出shell命令执行的结果 - shell: /usr/bin/foo when: result.rc == 0 #执行错误,rc返回非0值
5、Variables Defined In Roles
6、Using Variables: About Jinja2
(1)template模板中变量的替换
(2)template模板中使用jinja2的循环语句
7、Facts
(1)System facts
hostvars 记录主机的变量 #ns1_ip="{{hostvars.ns1.ansible_default_ipv4.address}}" ns1为主机名
groups 资源清单中的所有组 # 打印所有主机的ip {% for host in groups %} {{hostvar[host].ansible_default_ipv4.address}} {% endfor %}
group_names 当前主机所在的主机组名
inventory_hosts 主控端的主机名
inventory_hosts_short 主控端的主机名前缀
inventory_dir 设备清单文件的目录
inventory_file 设备清单文件的名字
(2)Local Facts
将fact文件放在远程主机的 /etc/ansible/facts.d目录
- hosts: webservers tasks: - name: Create diretory for ansible custom facts file: path=/etc/ansible/facts.d state=directory recurse=yes - name: Install custom immyfactsi fact copy: src=myfacts.fact dest=/etc/ansible/facts.d - name: re-read facts after add custom fact setup: filter=ansible=local cat myfacts.fact [general] ad=1 bar=2
8、Omitting Underfined Variable
- name: touch file with a optional mode file: dest={{item.path}} state=touch mode={{item.mode|default("0755")}} with_items: - path: /tmp/foo - path: /tmp/boo - path: /tmp/coo mode: "0444"