ansible模块之file

file模块的使用

可以帮助我们完成一些对文件操作,创建文件或目录、删除文件或目录、修改文件权限。。。

参数:

path:要操作的文件或目录。

state:此参数非常灵活,此参数对应的值需要根据情况设定,比如,当我们需要在远程主机中创建一个目录的时候,我们需要使用path参数指定对应的目录路径,假设,我想要在远程主机上创建/testdir/a/b目录,那么我则需要设置path=/testdir/a/b,但是,我们无法从"/testdir/a/b"这个路径看出b是一个文件还是一个目录,ansible也同样无法单单从一个字符串就知道你要创建文件还是目录,所以,我们需要通过state参数进行说明,当我们想要创建的/testdir/a/b是一个目录时,需要将state的值设置为directory,"directory"为目录之意,当它与path结合,ansible就能知道我们要操作的目标是一个目录,同理,当我们想要操作的/testdir/a/b是一个文件时,则需要将state的值设置为touch,当我们想要创建软链接文件时,需将state设置为link,想要创建硬链接文件时,需要将state设置为hard,当我们想要删除一个文件时(删除时不用区分目标是文件、目录、还是链接),则需要将state的值设置为absent,"absent"为缺席之意,当我们想让操作的目标"缺席"时,就表示我们想要删除目标。

src:当state设置为link或者hard时,表示我们想要创建一个软链或者硬链,所以,我们必须指明软链或硬链链接的哪个文件,通过src参数即可指定链接源。

force  :  当state=link的时候,可配合此参数强制创建链接文件,当force=yes时,表示强制创建链接文件,不过强制创建链接文件分为两种情况,情况一:当你要创建的链接文件指向的源文件并不存在时,使用此参数,可以先强制创建出链接文件。情况二:当你要创建链接文件的目录中已经存在与链接文件同名的文件时,将force设置为yes,回将同名文件覆盖为链接文件,相当于删除同名文件,创建链接文件。情况三:当你要创建链接文件的目录中已经存在与链接文件同名的文件,并且链接文件指向的源文件也不存在,这时会强制替换同名文件为链接文件。

owner :用于指定被操作文件的属主,属主对应的用户必须在远程主机中存在,否则会报错。

group :用于指定被操作文件的属组,属组对应的组必须在远程主机中存在,否则会报错。

mode:用于指定被操作文件的权限,比如,如果想要将文件权限设置为"rw-r-x---",则可以使用mode=650进行设置,或者使用mode=0650,效果也是相同的,如果你想要设置特殊权限,比如为二进制文件设置suid,则可以使用mode=4700,很方便吧。

recurse:当要操作的文件为目录,将recurse设置为yes,可以递归的修改目录中文件的属性。

举例子:

 touch参数

[root@ansible ~]# ansible webs -m file -a "path=/tmp/h1 state=touch"
[root@ansible ~]# ansible webs -m command -a "ls -l /tmp/h1"
webs | SUCCESS | rc=0 >>
-rwxr-xr-x 1 t1 root 612 Jun 3 19:51 /tmp/h1

创建文件
[root@ansible ~]# ansible webs -m file -a "path=/tmp/hehe state=touch" 
[root@ansible ~]# ansible webs -m command -a "ls -l /tmp/hehe"

创建目录
[root@ansible ~]# ansible webs -m file -a "path=/tmp/test state=directory"
[root@ansible ~]# ansible webs -m command -a "ls /tmp"

删除目录
[root@ansible ~]# ansible webs -m file -a "path=/tmp/test state=absent"
[root@ansible ~]# ansible webs -m command -a "ls /tmp"

修改属性 (如权限、所有者等)
[root@ansible ~]# ansible webs -m file -a "path=/tmp/test state=directory"
[root@ansible ~]# ansible webs -m file -a "path=/tmp/test/t1 state=touch"

[root@ansible ~]# ansible webs -m file -a "path=/tmp/test mode=777"
[root@ansible ~]# ansible webs -m command -a "ls -ld /tmp/test"
[root@ansible ~]# ansible webs -m command -a "ls -l /tmp/test"

递归修改属性
[root@ansible ~]# ansible test -m file -a "path=/tmp/test recurse=yes mode=755"
[root@ansible ~]# ansible test -m command -a "ls -ld /tmp/test"
[root@ansible ~]# ansible test -m command -a "ls -l /tmp/test"

原文地址:https://www.cnblogs.com/5444de/p/12463094.html