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

如何使用Ansible将/opt目录迁移至新建的独立分区

CentOS7下基于Ansible的/opt独立分区幂等迁移流程

核心逻辑说明

整个流程严格匹配手动操作的安全路径,实现全环节幂等:仅当检测到/opt仍挂载在根分区上时,才执行后续迁移操作;只要/opt已正确挂载到预先准备的新分区,所有任务自动跳过,重复运行Playbook无任何副作用。
幂等判断的核心逻辑:通过Ansible内置采集的挂载信息,对比/opt与根分区/的挂载设备,若设备完全一致则判定为未迁移状态,触发后续流程。

分步实现流程

1. 前置准备

  • 确认新分区已完成文件系统创建(你已完成该步骤)
  • 收集新分区的UUID,避免AWS环境块设备重启后名称漂移导致挂载失败,可手动执行blkid /dev/你的新分区设备获取对应值
  • 所有Ansible任务需以root权限执行,否则无权限读取系统目录、写入块设备

2. 核心任务配置

所有任务均挂载/opt仍在根分区的判断条件,保证幂等性:

- name: 采集系统挂载信息
  ansible.builtin.setup:
    filter: ansible_mounts

- name: 判定/opt是否仍挂载在根分区
  ansible.builtin.set_fact:
    opt_on_root: >-
      {{ ansible_mounts | selectattr('mount', 'equalto', '/opt') | map(attribute='device') | first ==
         ansible_mounts | selectattr('mount', 'equalto', '/') | map(attribute='device') | first }}

- name: 安装rsync用于全属性目录迁移
  ansible.builtin.yum:
    name: rsync
    state: present
  when: opt_on_root | bool

- name: 临时挂载新分区到独立暂存路径
  ansible.builtin.mount:
    path: /mnt/opt_migrate
    src: "UUID=你的新分区UUID"
    fstype: xfs
    state: mounted
  when: opt_on_root | bool

- name: 带全属性同步原/opt内容到临时挂载点
  # 参数说明:-a归档保留权限/属主/时间戳,-H保留硬链接,-A保留ACL,-X保留扩展属性,--numeric-ids保持原UID/GID映射
  ansible.builtin.command: >-
    rsync -aHAX --numeric-ids /opt/ /mnt/opt_migrate/
  changed_when: true
  when: opt_on_root | bool

- name: 同步校验(dry-run检查文件差异)
  ansible.builtin.command: >-
    rsync -aHAXn --numeric-ids /opt/ /mnt/opt_migrate/
  register: sync_check
  changed_when: false
  failed_when: sync_check.stdout | length > 0
  when: opt_on_root | bool

- name: 卸载临时暂存路径的挂载
  ansible.builtin.mount:
    path: /mnt/opt_migrate
    state: unmounted
  when: opt_on_root | bool

- name: 将根分区上原/opt目录重命名为备份目录
  ansible.builtin.command: mv /opt /opt_old_backup
  when: opt_on_root | bool

- name: 创建空的/opt挂载目录
  ansible.builtin.file:
    path: /opt
    state: directory
    owner: root
    group: root
    mode: "0755"
  when: opt_on_root | bool

- name: 配置新分区为/opt的永久挂载点
  ansible.builtin.mount:
    path: /opt
    src: "UUID=你的新分区UUID"
    fstype: xfs
    opts: defaults,noatime
    state: mounted
  when: opt_on_root | bool

- name: 刷新挂载事实,验证迁移结果
  ansible.builtin.setup:
    filter: ansible_mounts
  when: opt_on_root | bool

关键注意事项

  • 严格执行步骤顺序:必须先将根分区上的原/opt目录重命名为备份目录,再挂载新分区到/opt路径,避免挂载点遮挡原目录内容、导致迁移数据丢失
  • 同步路径必须带末尾斜杠:/opt/ 而非 /opt,否则会在新分区中生成嵌套的opt子目录,导致应用路径错误
  • 迁移完成后不要立即删除/opt_old_backup备份目录,等待所有依赖/opt路径的应用运行72小时以上、确认无异常后再手动清理
  • 不要使用Ansible原生的copy模块做目录迁移,该模块不支持硬链接、ACL、扩展属性的保留,容易导致应用权限异常

内容的提问来源于stack exchange,提问作者dsollen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 13:15:00