先看看debug模块的使用:
msg:输出调试信息
var:将某个任务执行的输出作为变量传给debug模块,debug模块将其打印输出
verbosity:debug的任务级别
1:在playbook中直接使用
--- - hosts: db vars: vvv: china tasks: - name: test var debug: msg="The variable 'vvv' is {{ vvv }}"
输出结果:
2:在文件中定义
--- - hosts: db vars_files: - vars.yml tasks: - name: test var in file debug: msg="The variable 'kk' is {{ kk }}"
变量文件:
---
kk: lile
执行结果:
3:在hosts文件中定义
/etc/ansible/hosts 中定义组变量或者单个主机的变量
[db] 10.0.0.147 pp=ppppppp [db:vars] mm=heiheihei
--- - hosts: db tasks: - name: test hosts group var debug: msg="The Variable 'mm' is {{ mm }}" - name: test singer var debug: msg="The Variable 'pp' is {{ pp }}"
执行结果:
4:在/etc/ansible目录下创建group_vars与hosts_vars
mkdir /etc/ansible/group_vars
mkdir /etc/ansible/hosts_vars
想定义组变量时,以组的名字命名创建一个文件,然后把变量写在里面
如:定义db组的变量 在/etc/ansible/group_vars这里创建db文件 vim db
---
tt: yyyyyyyyyyyyy
--- - hosts: db tasks: - name: test /etc/ansible/group_vars debug: msg="The variable 'tt' is {{ tt }}"
执行结果:
5:在host_vars中是同样的,只有一需要定义变量的那台主机命名就可以。
6:hostvars从一台远程主机获取另一台远程主机的变量
方式一:
--- - hosts: db tasks: - debug: msg="Variable 'tt' is set to {{ hostvars['10.0.0.146']['ttt'] }}"
输出结果:
方式二:
--- - hosts: db tasks: - name: test hostvars debug: var=hostvars['10.0.0.146']['ttt']
输出结果: