前言
Ansible Playbook 允许用户使用自定义的变量,不过变量过大,或者太复杂时,无论是在Playbook中通过vars定义,还是在单独的变量文件中定义,可读性都比较差,而且不够灵活。
但是lookup就能够解决这类难题,lookup即能够读取节点上文件系统的文件内容到ansible变量,也可以读取数据库中的内容
提示:本篇文章所使用的环境为centos-8.2基于ansible-2.8.0 搭建
具体环境搭建,请参考:ansible-2.8.0 搭建链接
lookup访问外部数据或数据库中的数据
1、lookup 读取文件
“{{ lookup(‘file’, ‘files/test.txt’) }}”
[root@node1 ansible]# cat lookup1.yml
---
- hosts: localhost
vars:
info: "{{ lookup('file', 'files/test.txt') }}"
tasks:
- name: dis var info
debug:
var: info
2、lookup 生成随机密码
“{{ lookup(‘password’, ‘files/pwd.txt length=6’) }}”
[root@node1 ansible]# cat lookup2.yml
---
- hosts: localhost
vars:
info: "{{ lookup('password', 'files/pwd.txt length=10') }}"
tasks:
- name: dis var info
debug:
var: info
3、lookup 读取环境变量
env
[root@node1 ansible]# cat lookup3.yml
---
- hosts: localhost
tasks:
- debug:
msg: "{{ lookup('env', 'USER') }}"
4、lookup 执行Linux命令
pipe
示例:
[root@node1 ansible]# cat lookup4.yml
---
- hosts: localhost
tasks:
- debug:
msg: "{{ lookup('pipe', 'whoami') }}"
5、lookup 读取 template 变量替换后的文件
template
示例:
# echo I am the template for test lookup template , and my name is {{ name }} > templates/test.j2
[root@node1 ansible]# cat lookup5.yml
---
- hosts: localhost
vars:
name: student
tasks:
- debug:
msg: "{{ lookup('template', 'templates/test.j2') }}"
6、lookup 读取 DNS 解析的值
dig
示例:
[root@node1 ansible]# cat lookup6.yml
---
- hosts: localhost
tasks:
- debug:
msg: "{{ lookup('dig', 'www.12306.cn') }}"
运行该模块编辑的playbook时,需要安装相应的软件
[root@node1 ansible]# yum install python3-dns