gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:25:35 25 4
gpt4 key购买 nike

我是 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

在此先致谢,如有任何帮助,我们将不胜感激。

最佳答案

下面的代码创建了一个已安装设备的列表。如果 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

(未测试)

Ansible 不收集有关 block 设备的信息。在 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

关于ubuntu - 在 Ansible 中检测并挂载文件系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55511770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com