ansible使用file模块管理受控机的目录与文件(ansible2.9.5)

一,ansible的file模块的用途

file 模块实现对文件的基本操作。

例如:

创建文件或目录

删除文件或目录

修改文件权限等

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,file模块的例子:

1,使用file模块创建文件夹:

#state的取值:

        directory 目录

        link 链接

       touch 创建文件

       absent  删除文件或文件夹

[liuhongdi@centos8 work]$ ansible yujian -m file -a "path=/home/webop/ansible/ state=directory mode=0644"
121.122.123.47 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 1000,
    "group": "webop",
    "mode": "0644",
    "owner": "webop",
    "path": "/home/webop/ansible/",
    "size": 6,
    "state": "directory",
    "uid": 1000
}

2,删除一个目录

说明:即使目录非空,也会被删除

[liuhongdi@centos8 work]$ ansible yujian -m file -a "path=/home/webop/ansible/ state=absent"

3,创建一个空文件

[liuhongdi@centos8 work]$ ansible yujian -m file -a "path=/home/webop/ansible.txt state=touch"

4,创建一个符号链接

#src : 源地址

#path :符号链接的地址

[liuhongdi@centos8 work]$ ansible yujian -m file -a "path=/home/webop/ansible_link src=/var/lib state=link"

登录到受控端查看创建的符号链接

[weop@blog ~]$ ll
total 620
lrwxrwxrwx 1 webop webop      8 Apr 20 16:24 ansible_link -> /var/lib

5,修改文件权限

# owner:指定所属用户

#group:指定所属组

#mode:指定权限

[liuhongdi@centos8 work]$ ansible yujian -m file -a "path=/home/webop/ansible.txt owner=root group=root mode=0744" --become  --become-method=sudo --become-user=root

登录到受控端查看文件属性的修改:

[webop@blog ~]$ ll ansible.txt

-rwxr--r-- 1 root root 0 Apr 20 16:23 ansible.txt

修改成功

三,file模块的其他参数:

recurse:当要操作的文件为目录,将recurse设置为yes,

             可以递归的修改目录中文件的属性

force : 当state=link的时候,force参数用来强制创建链接文件

           force=yes时,表示强制创建链接文件

四,查看ansible版本

[root@centos8 liuhongdi]# ansible --version
ansible 2.9.5
原文地址:https://www.cnblogs.com/architectforest/p/12765821.html