Ansible - mount module (mount and unmount partition /etc/fstab)

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

The mount module is used to either:

  • add or remove an entry from /etc/fstab on a managed node
  • temporarily mount, remount or unmount a directory from a partition, like using the mount command or umount command on Linux

Let's say /etc/fstab on one of your managed nodes contains the follow.

UUID=7a8e7883-e6ee-4482-a7ca-665bfe94eaa8 /var  ext4  defaults    1 2

 

Here is how you would remove this entry from /etc/fstab.

---
- hosts: all
  remote_user: root
  tasks:
    - name: remove /var entry from /etc/fstab
      mount:
        path: /var
        state: absent
...

 

Let's say the follow fatal error is returned.

fatal: [server1.example.com]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "changed": false, "msg": "Error unmounting /var: umount: /var: target is busy.\n"}

 

To address this, you can first use the shell module to unmount.

---
- hosts: all
  remote_user: root
  tasks:
    - name: unmount /var
      shell: "umount --lazy /var"
...

 

And here is how you would add the entry back into /etc/fstab.

---
- hosts: all
  remote_user: root
  tasks:
    - name: add /var entry to /etc/fstab
      mount:
        path: /var
        src: UUID=7a8e7883-e6ee-4482-a7ca-665bfe94eaa8
        fstype: ext4
        opts: defaults
        dump: '1'
        state: present
...

 

You probably do not want to hard code in the UUID of each device into your playbook. Instead, the gather_facts plugin can be used to get the UUID.

---
- hosts: all
  remote_user: root
  tasks:
    - name: add /var entry to /etc/fstab
      mount:
        path: /var
        src: UUID="{{ ansible_devices.sda.partitions.sda1.uuid }}"
        fstype: ext4
        opts: defaults
        dump: '1'
        state: present
    when: ansible_devices.sda.partitions.sda1 is defined
...

 



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 3130c in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |