一、with_file
假设你的ansible主机中有几个文件(注意:是ansible主机中的文件,不是远程目标主机中的文件),你想要获取到这些文件的内容,那么可以借助"with_file"关键字,循环的获取到这些文件的内容,示例如下:
[root@server4 ~]# vim xh23.yml
[root@server4 ~]# cat xh23.yml
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{item}}"
with_file:
- /testdir/pp
- /opt/test
如上例所示,我们定义了一个列表,这个列表中有两个文件路径,分别是"/testdir/testdir/a.log"和"/opt/testfile",这两个文件都是ansible主机中的文件,我们通过"with_file"关键字处理了这个列表,那么我们执行一下上例playbook,看看能不能获取到对应的文件内容,执行上例后debug模块输出信息如下:
如上所示,上例 playbook成功的获取到了文件列表中每个文件的内容,而且我们可以发现,上例playbook的目标主机是testB,testB并非是ansible主机,而是一个远程目标主机,我的测试环境中,server4才是ansible主机,所以,可以发现,无论目标主机是谁,我们都可以通过"with_file"关键字获取到ansible主机中的文件内容。
二、with_fileglob
了解完"with_file"关键字,再来聊聊另外一个关键字,它就是"with_fileglob"
"with_file"是用来获取文件内容的,而"with_fileglob"是用来匹配文件名称的,我们可以通过"with_fileglob"关键字,在指定的目录中匹配符合模式的文件名,"with_file"与"with_fileglob"也有相同的地方,它们都是针对ansible主机的文件进行操作的,而不是目标主机,那么,我们来看一个"with_fileglob"小示例,示例如下:
[root@server4 ~]# vim xh23.yml
[root@server4 ~]# cat xh23.yml
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{item}}"
with_fileglob:
- /testdir/*
从返回信息可以看出,上例playbook中的”/testdir/“一共匹配到了5个文件,那么,”/testdir"目录中只有这5个文件么,我们来确认一下,查看"/testdir"目录中的文件,如下:
从上述信息可以看出,"/testdir"目录中一共有六项,两项是目录,四项是文件,而之前playbook匹配到的只有文件,并不包含目录,所以,我们需要注意的是,"with_fileglob"只会匹配指定目录中的文件,而不会匹配指定目录中的目录。
上例的playbook中,我们只指定了一个路径,当然,我们也可以指定多个路径,示例playbook如下:
[root@server4 ~]# vim xh23.yml
[root@server4 ~]# cat xh23.yml
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{item}}"
with_fileglob:
- /testdir/*
- /opt/test*.???
可以看出不符合通配规则的不会被返回。