Stale file handles for mounted drives on Linux

August 1, 2024

Troubleshooting:

  • stale file handle
    • when the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid
    • when the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes
    • the only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to)
    • if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.
    • https://stackoverflow.com/questions/20105260/what-does-stale-file-handle-in-linux-mean
    • https://en.wikipedia.org/wiki/Inode

Solutions:

Check which mounts exist:

  • mount | awk '{if ($3 == "/share") { exit 0}} ENDFILE{exit -1}'

Mount facts from ansible:

Playbook example:

- name: Gather mount information
  ansible.builtin.setup:
    gather_subset: mounts
  register: mount_info
 
- name: Unmount shares which exist
  ansible.posix.mount:
    path: '{{ item.point }}'
    state: unmounted
  loop: "{{ mounts }}"
  when: item.point in mount_info.ansible_facts.ansible_mounts | map(attribute='mount') | list