Ansible - when file or directory is writeable (out.stat.writeable)

Let's say you have a task that should only be executed when /tmp/foo is writeable. The stat module and the register parameter can be used to store the statistics of /tmp/foo in a variable.

- hosts: all
    - name: "store the statistics of /opt/example.txt in the 'out' variable"
        path: "/tmp/foo.txt"
      register: out


The debug module can be used to displays the out variable.

- name: display the 'out' variable
    var: out


Which should return something like this. Notice in this example the "writeable" is true.

TASK [debug] 
ok: [] => {
    "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.writeable can now be used to fail if /tmp/foo is or is not writeable.

- name: fail when /tmp/foo is not writeable
   msg: /tmp/foo is not writeable
  when: out.stat.writeable == false


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: []

TASK [fail when /tmp/foo is not writeable]
fatal: []: FAILED => {"changed": false, "msg": "/tmp/foo is not writeable"}

PLAY RECAP : ok=2  changed=0  unreacable=0  failed=1



Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 0538c in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |