利用ansible检测未挂载的磁盘并批量格式化、挂载
时间: 2023-10-18 08:02:56 浏览: 180
可以使用ansible的disk module来检测未挂载的磁盘,并使用mount和filesystem modules来格式化和挂载磁盘。以下是一个基本的ansible playbook示例:
```
- name: Check and format new disks
hosts: all
tasks:
- name: Get list of disks
shell: "lsblk -lpd -n -o NAME,TYPE | awk '$2 == \"disk\" {print $1}'"
register: disk_list
- name: Check if disks are mounted
mount:
path: "{{ item }}"
state: mounted
register: mounted_disks
with_items: "{{ disk_list.stdout_lines }}"
- name: Format disks
filesystem:
fstype: ext4
dev: "{{ item }}"
with_items: "{{ disk_list.stdout_lines }}"
when: item not in mounted_disks.mounted | map(attribute='path') | list
- name: Mount disks
mount:
path: "/mnt/{{ item.split('/')[-1] }}"
src: "{{ item }}"
fstype: ext4
state: mounted
with_items: "{{ disk_list.stdout_lines }}"
when: item not in mounted_disks.mounted | map(attribute='path') | list
```
这个playbook会在所有的主机上执行。它首先使用lsblk命令获取所有磁盘的列表,然后使用mount module检查哪些磁盘已经挂载。接着,使用filesystem module格式化未挂载的磁盘,并使用mount module将其挂载到/mnt目录下。注意,为了避免重复格式化或挂载,我们使用when条件语句来检查磁盘是否已经挂载。
阅读全文