使用Lookup 查询节点数据
lookup()是Ansible的一个插件,可用于从外部读取数据,这里的”外部”含义非常广泛,比如:
(1).从磁盘文件读取(file插件)
(2).从redis中读取(redis插件)
(3).从etcd中读取(etcd插件)
(4).从命令执行结果读取(pipe插件)
(5).从Ansible变量中读取(vars插件)
(6).从Ansible列表中读取(list插件)
(7).从Ansible字典中读取(dict插件)
下面是lookup()的语法:
lookup('<plugin_name>', 'plugin_argument')
首先介绍fileglob插件,它使用通配符来通配Ansible本地端的文件名。
需注意的是,fileglob查询的是Ansible端文件,且只能通配文件而不能通配目录,且不会递归通配。如果想要查询目标主机上的文件,可以使用find模块。
---
- name: play1
hosts: new
gather_facts: false
tasks:
- name: task1
debug:
msg: "filenames: {{lookup('fileglob','/etc/*.conf')}}"
再介绍file插件,这个插件用的应该是最多的,它用来读取Ansible本地端文件(这里本地端貌似不准确)。例如:
读取/etc/hosts 中的内容
---
- name: play1
hosts: new
gather_facts: false
tasks:
- name: task1
debug:
msg: "file content: {{lookup('file','/etc/hosts')}}"
再者需要说明的是,如果lookup()查询出来的结果包含多项,则默认以逗号分隔各项的字符串方式返回,如果想要以列表方式返回,则传递一个lookup的参数wantlist=True。例如,fileglob通配出来的文件如果有多个,加上wantlist=True:
在Ansible 2.5中添加了一个新的功能query()或q(),后者是前者的等价缩写形式。query()在写法和功能上和lookup一致,其实它会自动调用lookup插件,并且总是以列表方式返回,而不需要手动加上wantlist=True参数。例如:
- name: task1
debug:
msg: "{{q('fileglob','/etc/*.conf')}}"