You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Ansible格式化并挂载未使用的磁盘

如何使用Ansible格式化并挂载未使用的磁盘

嘿,我看你已经成功用Ansible找出了系统里未使用的磁盘,不过卡在格式化和挂载这一步了对吧?别着急,我来帮你把这个playbook补全,一步步搞定它!

首先,你已经通过ansible_devices过滤出了所有未分区的sd开头磁盘,存到了disks列表里,接下来只需要遍历这个列表,对每个磁盘执行格式化和挂载操作就行。

完整的Playbook示例

---
- name: Prepare unformatted disk
  hosts: test_hosts
  gather_facts: true
  remote_user: confmanager
  become: true
  tasks:
      - name: Get unformatted disks
        ansible.builtin.set_fact:
            disks: "{{ disks | default([]) + ['/dev/' + item.key] }}"
        when:
            - not item.value.partitions
            - item.key | regex_search("sd")
        with_dict: "{{ ansible_devices }}"

      - name: Show unformatted disks
        ansible.builtin.debug:
            msg: "Found unformatted disks: {{ disks }}"

      - name: Format disk with Btrfs filesystem
        community.general.filesystem:
            fstype: btrfs
            device: "{{ item }}"
            force: no  # 重要!避免误格式化已有文件系统的磁盘
        loop: "{{ disks }}"
        when: disks is defined and disks | length > 0  # 确保有磁盘才执行

      - name: Create mount point directory
        ansible.builtin.file:
            path: "/mnt/{{ item | basename }}"  # 比如/dev/sdb对应/mnt/sdb
            state: directory
            mode: '0755'
        loop: "{{ disks }}"
        when: disks is defined and disks | length > 0

      - name: Mount disk and update fstab (persistent after reboot)
        ansible.posix.mount:
            path: "/mnt/{{ item | basename }}"
            src: "{{ item }}"
            fstype: btrfs
            state: mounted  # 这个状态会同时完成挂载和写入fstab
        loop: "{{ disks }}"
        when: disks is defined and disks | length > 0

关键部分说明

  • 格式化任务:用loop: "{{ disks }}"遍历你找到的所有未使用磁盘,force: no是安全保障,它会检查设备上是否已有文件系统,如果有就跳过,避免误删已有数据。
  • 创建挂载点:为每个磁盘创建独立的挂载目录,用item | basename提取设备名(比如从/dev/sdb得到sdb),这样挂载点清晰好管理。
  • 持久化挂载:ansible.posix.mount模块的state: mounted非常实用,它不仅会立即挂载磁盘,还会把挂载信息写入/etc/fstab,确保重启后依然生效。

小提醒

  • 如果你只需要临时挂载(重启后失效),可以把mount模块的state改成mounted?不对,应该是state: present只写入fstab不立即挂载,state: mounted是既挂载又写入,要是临时挂载用state: mounted之后再取消的话反而麻烦,其实临时挂载直接用state: mounted之后,要是不想持久化,就把fstab里的条目删掉就行,不过一般都建议配置持久化,避免重启后挂载消失。
  • 要确保目标主机已经安装了community.general和ansible.posix这些集合(Ansible 2.10+版本需要手动装:ansible-galaxy collection install community.general ansible.posix),旧版本Ansible这些模块可能在核心包里,不用额外装。

这样改完之后,你运行这个playbook,它就会自动处理所有你找到的未使用磁盘,从格式化到挂载一步到位啦!

备注:内容来源于stack exchange,提问作者user1051676

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 09:49:33