I am new to ansible and try to detect a filesystem and than mount if present. I have gone through below links :-
1. https://docs.ansible.com/ansible/latest/modules/filesystem_module.html
2. https://docs.ansible.com/ansible/latest/modules/mount_module.html
I have attached a hard drive manually which is detected by command fdisk -l as "/dev/sdb". I want ansible code to detect and mount this filesystem on some location. While running the code "df -h" is not showing the mounted filesystem and not failing also. And even if I am listing all filesystem or mount point through ansible code, this filesystem (/dev/sdb) is not listing.
Code Snippet:
- name: Create File System
filesystem:
fstype: ext4
dev: "{{ mount_src }}"
- name: Mount File System
mount:
path: "{{ mount_path }}"
src: "{{ mount_src }}"
fstype: ext4
state: mounted
Thanks in advance and any help would be appreciated.
The play below creates a list of mounted devices. When mount_src is not mounted, the filesystem is created, and mount_src is mounted to mount_path.
- hosts: localhost
vars:
mount_src: /dev/sdb
mount_path: /export
mounted_devices: "{{ ansible_mounts | map(attribute='device') }}"
tasks:
- name: Create File System
filesystem:
fstype: ext4
dev: "{{ mount_src }}"
when: mount_src not in mounted_devices
- name: Mount File System
mount:
path: "{{ mount_path }}"
src: "{{ mount_src }}"
fstype: ext4
state: mounted
when: mount_src not in mounted_devices
(not tested)
Ansible does not gather facts about the block devices. In Linux, it's possible to use the command lsblk instead. For example,
- hosts: localhost
vars:
block_devices: "{{ results.stdout_lines }}"
tasks:
- name: Get list of block devices
command: 'lsblk -lno NAME'
register: results
- debug:
var: block_devices
gives
ok: [127.0.0.1] =>
block_devices:
- sda
- sda1
- sda2
- sda3
- sda5
- sdb
- sdb1
- sdb9
- mmcblk0
- mmcblk0p1
Update
You can test mounted partitions in addition to testing that a device is not among mounted devices. The test match:
match succeeds if it finds the pattern at the beginning of the string
- hosts: localhost
vars:
mount_src: /dev/sdb
mount_path: /export
mounted_devices: "{{ ansible_mounts | map(attribute='device') }}"
mounted_partitions: "{{ mounted_devices | select('match', mount_src) }}"
tasks:
- name: Get mounted devices
setup:
gather_subset: mounts
- debug:
var: mounted_devices
- debug:
var: mounted_partitions
- name: Create and mount files system
when:
- mount_src not in mounted_devices
- mounted_partitions | length == 0
block:
- name: Create File System
filesystem:
dev: "{{ mount_src }}"
fstype: ext4
- name: Mount File System
mount:
src: "{{ mount_src }}"
path: "{{ mount_path }}"
fstype: ext4
state: mounted
(not tested)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With