Ansible - when object is or is not a directory (out.stat.isdir)
by
Jeremy Canfield |
Updated: January 09 2021
| Ansible articles
Let's say you have a task that should only be executed when /tmp/foo is or is not a directory. The stat module and the register parameter can be used to store the statistics of /tmp/foo in a variable.
---
- hosts: all
tasks:
- name: "store the statistics of /opt/example.txt in the 'out' variable"
stat:
path: "/tmp/foo.txt"
register: out
The debug module can be used to displays the out variable.
- name: display the 'out' variable
debug:
var: out
Which should return something like this. Notice in this example the "isdir" is true.
TASK [debug]
ok: [server1.example.com] => {
"out": {
"changed": false,
"failed": false,
"stat": {
"atime": 1610186400.7513745,
"attr_flags": "",
"attributes": [],
"block_size": 4096,
"blocks": 8,
"charset": "binary",
"ctime": 1610187202.1764085,
"dev": 64768,
"device_type": 0,
"executable": true,
"exists": true,
"gid": 0,
"gr_name": "root",
"inode": 50331777,
"isblk": false,
"ischr": false,
"isdir": true,
"isfifo": false,
"isgid": false,
"islnk": false,
"isreg": false,
"issock": false,
"isuid": false,
"mimetype": "inode/directory",
"mode": "1777",
"mtime": 1610187202.1764085,
"nlink": 10,
"path": "/tmp/foo",
"pw_name": "root",
"readable": true,
"rgrp": true,
"roth": true,
"rusr": true,
"size": 4096,
"uid": 0,
"version": "1309840072",
"wgrp": true,
"woth": true,
"writeable": true,
"wusr": true,
"xgrp": true,
"xoth": true,
"xusr": true
}
}
}
The fail module and when parameter with out.stat.isdir can now be used to fail if /tmp/foo is or is not a directory.
- name: fail when /tmp/foo is a directory
fail:
msg: /tmp/foo is a directory
when: out.stat.isdir == true
Invoking this playbook should return something like this. The ansible-doc fail command can be used to show the Ansible documention on the fail module.
When fail evaluates to true, all of the subsequent tasks are skipped.
PLAY [all]
TASK [store the statistics of /tmp/foo in the 'out' variable]
ok: [server1.example.com]
TASK [fail when /tmp/foo is a directory]
fatal: [server1.example.com]: FAILED => {"changed": false, "msg": "/tmp/foo is a directory"}
PLAY RECAP
server1.example.com : ok=2 changed=0 unreacable=0 failed=1
Did you find this article helpful?
If so, consider buying me a coffee over at