πŸ“¦ Contributor Guide: Mounting Disks Using fstab Using Ansible

The fstab role provides a declarative, idempotent, and state-aware way to manage filesystem mounts via /etc/fstab. Unlike traditional approaches that only append entries, this role ensures the system’s mount configuration matches your desired state exactlyβ€”adding new mounts and removing those no longer defined.

πŸ”— Source repository: πŸ‘‰ https://github.com/t3knoid/ansible/tree/main/roles/fstab

Unlike autofs, which performs on-demand NFS automounting, this role uses static /etc/fstab entries, making it suitable for both NFS and local disk mounts.


✨ Key Features


🧰 Prerequisites


βš™οΈ Variables

πŸ”΄ Required

fstab_mounts (list): Array of mount configurations. Each entry must include:

πŸ“ Optional

Parameter Type Default Description
fstype string ext4 Filesystem type (nfs, ext4, xfs, etc.)
opts string defaults Mount options (comma-separated)
boot boolean true Mount at system startup

🧠 How It Works

The role maintains declarative state by tracking which mounts it manages.

πŸ” Role Execution Flow

  1. Initialize β€” Load defaults and prepare variables
  2. Calculate changes β€” Compare defined mounts vs. previously managed ones
  3. Remove old mounts

    • Check if mounted
    • Unmount
    • Remove /etc/fstab entry
    • Delete mount directory
  4. Add/update mounts

    • Create mount directory
    • Add/update /etc/fstab entry
    • Mount the filesystem

🧠 State Tracking

The role uses the fact fstab_mounts_managed to ensure:


πŸš€ Usage Examples

🟒 Basic NFS Mounts

- hosts: media_servers
  become: true
  roles:
    - fstab
  vars:
    fstab_mounts:
      - device: "192.168.2.240:/volume1/Photos"
        mount_point: "/nfs/photos"
        fstype: "nfs"
        opts: "rw,relatime,hard,rsize=1048576,wsize=1048576,proto=tcp,timeo=600,retrans=2,sec=sys"
      - device: "192.168.2.250:/mnt/Data/music"
        mount_point: "/nfs/music"
        fstype: "nfs"
        opts: "rw,relatime,hard,rsize=1048576,wsize=1048576,proto=tcp,timeo=600,retrans=2,sec=sys"

πŸ—ƒ Local Disk Mounts

fstab_mounts:
  - device: "/dev/sdb1"
    mount_point: "/data"
    fstype: "ext4"
    opts: "defaults,nofail"
  - device: "/dev/sdc1"
    mount_point: "/backup"
    fstype: "ext4"
    opts: "defaults,noatime"

πŸ—‚ Mixed Mount Types

fstab_mounts:
  - device: "/dev/sdb1"
    mount_point: "/local-storage"
    fstype: "ext4"
  - device: "nfs-server:/export"
    mount_point: "/remote-storage"
    fstype: "nfs"
    opts: "rw,sync,hard,intr"
  - device: "/dev/sdc1"
    mount_point: "/backup"
    fstype: "xfs"
    opts: "defaults"

πŸ” Idempotent Changes Example


πŸ“ Configuration Files

/etc/fstab

Managed declaratively via ansible.posix.mount.


🧩 Task Breakdown

1️⃣ Initialize & Calculate

2️⃣ Remove Old Mounts

3️⃣ Add/Update Mounts


πŸ“š Ansible Module References