【Ansible学习】- 常用文件操作模块之file模块

简介

file模块,文件属性模块,主要用于设置已存在文件、符号链接或者目录的属性,或删除文件/符号链接/目录。

模块参数

名称 必选 默认值 可选值 备注
follow no no yes/no 是否遵循目的机器中的文件系统链接
force no yes yes/no 强制执行
group no 设置文件/目录的所属组
mode no 设置文件权限,模式实际上是八进制数字(如0644),少了前面的零可能会有意想不到的结果。从版本1.8开始,可以将模式指定为符号模式(例如u+rwxu=rw,g=r,o=r
owner no 设置文件/目录的所属用户
path yes 目标文件/目录,也可以用dest,name代替
recurse no no yes/no 是否递归设置属性(仅适用于state=directory
src no 要链接到的文件路径(仅适用于state=link
state no file file/link/directory/hard/touch/absent 若果是directory,所有的子目录将被创建(如果它们不存在);若是file,文件将不会被创建(如果文件不存在);link表示符号链接;若是absent,目录或文件会被递归删除;touch代表生成一个空文件;hard代表硬链接;
unsafe_writes no yes/no 是否以不安全的方式进行,可能导致数据损坏

示例

设置文件权限 - owner\group\mode

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos7 ~]# ansible test -m file -a "path=/root/test.sh owner=liuhao group=liuhao mode=0777"
172.20.21.121 | SUCCESS => {
"changed": true,
"gid": 1000,
"group": "liuhao",
"mode": "0777",
"owner": "liuhao",
"path": "/root/test.sh",
"secontext": "unconfined_u:object_r:admin_home_t:s0",
"size": 23,
"state": "file",
"uid": 1000
}

设置文件权限

创建空文件 - state=touch

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos7 ~]# ansible test -m file -a "path=/tmp/liuhao_testfile state=touch mode=0644"
172.20.21.121 | SUCCESS => {
"changed": true,
"dest": "/tmp/liuhao_testfile",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"secontext": "unconfined_u:object_r:user_tmp_t:s0",
"size": 0,
"state": "file",
"uid": 0
}

创建空文件

创建目录 - state=directory

目录是递归创建的

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos7 ~]# ansible test -m file -a "path=/tmp/liuhao/test/2018 state=directory mode=0644"
172.20.21.121 | SUCCESS => {
"changed": true,
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"path": "/tmp/liuhao/test/2018",
"secontext": "unconfined_u:object_r:user_tmp_t:s0",
"size": 6,
"state": "directory",
"uid": 0
}

创建目录

目标文件不存在

state=file时会报错,但是state=absent不会报错,执行状态也不会变化。

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos7 ~]# ansible test -m file -a "path=/tmp/liuhao/test/2018/1 state=file mode=0644"
172.20.21.121 | FAILED! => {
"changed": false,
"msg": "file (/tmp/liuhao/test/2018/1) is absent, cannot continue",
"path": "/tmp/liuhao/test/2018/1",
"state": "absent"
}
[root@centos7 ~]# ansible test -m file -a "path=/tmp/liuhao/test/2018/1 state=absent mode=0644"
172.20.21.121 | SUCCESS => {
"changed": false,
"path": "/tmp/liuhao/test/2018/1",
"state": "absent"
}

删除文件或者目录 - state=absent

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos7 ~]# ansible test -m file -a "path=/tmp/liuhao state=absent"
172.20.21.121 | SUCCESS => {
"changed": true,
"path": "/tmp/liuhao",
"state": "absent"
}

[root@centos7 ~]# ansible test -m file -a "path=/tmp/liuhao_testfile state=absent"
172.20.21.121 | SUCCESS => {
"changed": true,
"path": "/tmp/liuhao_testfile",
"state": "absent"
}
hoxis wechat
提供 CSDN 资料免费下载服务,欢迎来撩~
赞赏一杯咖啡
0%