Mount NFS Using Ansible Playbook Easily

Mount NFS Using Ansible Playbook Easily

When managing Linux servers, automating tasks such as mount NFS using Ansible can save time and reduce errors. In this guide, you will learn how to mount and unmount NFS shares using Ansible playbooks. These automation scripts ensure consistent configuration and simplify the process for multiple servers.

Why Automate NFS Mounts with Ansible?

Manual NFS mounting across many servers can be repetitive and error-prone. However, by using Ansible, you can:

  • Mount NFS shares in one command.

  • Ensure correct permissions and configuration.

  • Easily unmount NFS when it’s no longer needed.

Ansible Playbook to Mount NFS

The following Ansible mount NFS playbook checks the mount point, sets permissions, mounts the share, and adds it to /etc/fstab:

- name: Mount NFS on Remote Servers
  hosts: test
  become: true
  remote_user: testuser
  become_method: sudo
  vars:
     nfs_source: "testserver:/nfsshare"
     mountpoint: "/opt/nfs"
     fstype: "nfs4"

  tasks:

  - name: Check if mount point exists or not
    file:
      path: "{{ mountpoint }}"
      state: directory
      owner: testuser
      group: ipausers
      mode: '755'

  - name: Mount NFS Share and Add in /etc/fstab
    mount:
       path: "{{ mountpoint }}"
       src: "{{ nfs_source }}"
       fstype: "{{ fstype }}"
       opts: "defaults"
       state: mounted

Ansible Playbook to Unmount NFS

Once you no longer need the NFS share, use this NFS unmount playbook:

- name: Umount NFS on Remote Servers
  hosts: test
  become: true
  remote_user: testuser
  become_method: sudo
  vars:
     nfs_source: "testserver:/nfsshare"
     mountpoint: "/opt/nfs"
     fstype: "nfs4"

  tasks:

  - name: Umount NFS Share
    mount:
       path: "{{ mountpoint }}"
       state: unmounted

  - name: Remove entry from /etc/fstab
    mount:
       path: "{{ mountpoint }}"
       src: "{{ nfs_source }}"
       fstype: "{{ fstype }}"
       state: absent

Running the Playbooks

To mount:

ansible-playbook mount-nfs.yml

To unmount:

ansible-playbook umount-nfs.yml

Final Thoughts

By using these mount NFS using Ansible and unmount NFS with Ansible playbooks, you can streamline NFS management across multiple Linux servers. Automation not only improves efficiency but also ensures consistent results every time.

3 thoughts on “Mount NFS Using Ansible Playbook Easily

  • Leave a Reply

    Your email address will not be published. Required fields are marked *