stat主要用于查看文件目录属性,包括创建时间、访问时间、修改时间、存在状态、路径位置、文件大小 等等

参数 必填 默认值 注解
path yes 文件目录的路径

Ansible技术问答:http://linux.xyz/topic/Ansible

执行:ansible all -m stat -a "path=/data/lipeibin",返回结果如下:

"stat": {
		"atime": 1459386908.4750736,
		"ctime": 1459386908.4740734,
		"dev": 20,
		"exists": true,
		"gid": 99,
		"gr_name": "nobody",
		"inode": 655266,
		"isblk": false, 
		"ischr": false,
		"isdir": true,
		"isfifo": false,
		"isgid": false,
		"islnk": false,
		"isreg": false,
		"issock": false,
		"isuid": false,
		"mode": "0757",
		"mtime": 1459386845.7500744,
		"nlink": 2,
		"path": "/data/lipeibin",
		"pw_name": "nobody",
		"rgrp": true,
		"roth": true,
		"rusr": true,
		"size": 4096,
		"uid": 99,
		"wgrp": false,
		"woth": true,
		"wusr": true,
		"xgrp": true,
		"xoth": true,
		"xusr": true
	}
}

可以根据上面文件目录属性输出的结果可以在后面的 task 中引入,如:

# 判断一个路径是存在,且是一个目录
- stat: path=/path/to/something
 register: reg
- debug: msg="Path exists and is a directory"
 when: reg.stat.isdir is defined and p.stat.isdir

# 判断文件属主是否发生改变
- stat: path=/etc/foo.conf
 register: reg
- fail: msg="Oh,file ownership has changed"
 when: re.stat.pw_name != "root"

# 判断文件是否存
- stat: path=/path/to/something
 register: reg
- debug: msg="file doesn't exist"
 when: not reg.stat.exists
- debug: msg="file is exist"
 when: reg.stat.exists