ubuntu 在Ansible中检测和挂载文件系统

mbskvtky  于 2023-03-22  发布在  其他
关注(0)|答案(2)|浏览(161)

我是新的ansible和尝试检测一个文件系统,然后挂载如果存在.我已经通过下面的链接:-

1. https://docs.ansible.com/ansible/latest/modules/filesystem_module.html
2. https://docs.ansible.com/ansible/latest/modules/mount_module.html

我已经手动连接了一个硬盘驱动器,它被命令fdisk -l检测为“/dev/sdb”。我想让ansible代码检测并在某个位置挂载这个文件系统。当运行代码“df -h”时,没有显示挂载的文件系统,也没有失败。即使我通过ansible代码列出所有文件系统或挂载点,这个文件系统(/dev/sdb)也没有列出。
代码片段:

- 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

提前感谢,任何帮助都将不胜感激。

owfi6suc

owfi6suc1#

下面的步骤创建了一个已挂载设备的列表。如果 mount_src 没有挂载,则创建文件系统,并将 mount_src 挂载到 mount_path

- hosts: localhost
      vars:
        mount_src: /dev/sdb
        mount_path: /export
      tasks:
        - name: Create list of mounted devices
          set_fact:
            mounted_devices: "{{ ansible_mounts|json_query('[].device') }}"
        - 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测试)
Ansible不会收集关于块设备的事实。在Linux中,可以使用命令lsblk代替,例如。

- hosts: localhost
      tasks:
        - name: Get list of block devices
          command: 'lsblk -lno NAME'
          register: results
        - name: Create variable block_devices
          set_fact:
            block_devices: "{{ results.stdout_lines }}"
        - debug:
            var: block_devices

给予

ok: [127.0.0.1] => 
      block_devices:
      - sda
      - sda1
      - sda2
      - sda3
      - sda5
      - sdb
      - sdb1
      - sdb9
      - mmcblk0
      - mmcblk0p1
roqulrg3

roqulrg32#

我的ansible脚本挂载磁盘上localhost.我已经在挂载部分添加路径作为早期版本没有这个作为必需的参数现在它是强制性的,脚本在挂载失败,如果不添加

---
- name: Create and mount new storage
  hosts: localhost
  tasks:
          - name: create new partition
            parted:
                    name: files
                    label: gpt
                    device: /dev/sdb
                    number: 1
                    state: present
                    part_start: 1MiB
                    part_end: 1GiB
          - name: Create xfs filesystem
            filesystem:
                    dev: /dev/sdb1
                    fstype: xfs
          - name: Create mount directory
            file:
                    path: /data
                    state: directory
          - name: mount the filesystem
            mount:
                    path: /data
                    src: /dev/sdb1
                    fstype: xfs
                    state: mounted

相关问题