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

存在/var/run/reboot-required文件时Ansible无法重启Ubuntu服务器

问题分析与解决方案

核心错误:任务区块嵌套错误

你的原始剧本中,tasks被错误地放在了vars区块内部,导致Ansible根本没有加载执行后续的检查和重启任务——这就是为什么执行结果只有Gathering Facts,没有其他任务记录。

同时,become和become_user是Play级别的配置项,不属于vars变量,需要移到与hosts、vars同级的位置。

修正后的剧本

---
- hosts: server
  vars:
    ansible_user: sudo_user
    ansible_password: "password"
  become: yes
  become_user: root  # 重启需要root权限,sudo_user本身权限不足
  tasks:
    - name: Check if reboot required
      stat:
        path: /var/run/reboot-required
      register: reboot_required_file

    - name: Reboot if required
      reboot:
        msg: "Rebooting due to pending system updates"
        connect_timeout: 5
        reboot_timeout: 600
        pre_reboot_delay: 0
        post_reboot_delay: 30
      when: reboot_required_file.stat.exists

关键说明

  1. 权限修正:重启操作需要root权限,所以become_user要设置为root,而不是sudo_user——即使你的用户有sudo权限,直接切换到root才能确保重启命令被正确执行。
  2. reboot模块参数:添加必要的超时和延迟参数,适配Ubuntu服务器的重启流程,避免Ansible因连接中断误判失败。
  3. 条件判断简化:when: reboot_required_file.stat.exists等价于判断== true,写法更简洁。

关于shell命令失败的原因

你尝试的shell命令失败有两个主要原因:

  • 代码中name字段为空,且缩进可能存在问题,导致任务未被正确识别
  • init 6需要root权限,若未正确切换到root,该命令会被系统拒绝执行
  • Ansible执行远程shell命令时会保持连接,而init 6会直接断开连接,即使添加ignore_errors: true,也可能因权限问题根本无法触发重启

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:11:16