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

如何永久设置Vagrant环境日期时间 启动时自动生效

Vagrant环境固定指定日期时间的实现方法

问题现象

通过Vagrantfile的shell provisioner执行date -s设置指定时间,启动日志显示命令执行成功:

default: Running: inline script
default: Wed Jun 29 12:34:56 UTC 2022

但SSH登录虚拟机后执行date仍显示当前实际时间;手动在SSH内执行时间修改命令可临时生效,退出重连后时间再次复原。
手动执行VirtualBox命令关闭宿主机时间同步、设置BIOS时间偏移可实现固定时间,但无法通过Vagrant流程自动完成配置。

失效原因

  • VirtualBox默认启用宿主机到虚拟机的时间同步机制,虚拟机运行过程中会定期拉取宿主机时间覆盖手动修改的系统时间
  • Ubuntu Focal64镜像默认开启systemd-timesyncd NTP时间同步服务,检测到系统时间与公共时间服务器偏差时会自动校准
  • VirtualBox Guest Additions自带的服务组件也会在SSH连接、会话恢复等节点触发时间同步

推荐方案:VirtualBox层自动配置(永久生效)

直接把VirtualBox时间相关配置写入Vagrantfile的provider块,启动时自动执行,支持自动计算目标时间的偏移量,无需手动换算毫秒差值,重启、重连、恢复快照都不会重置时间。
完整可用的Vagrantfile配置如下:

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/focal64"  

  config.vm.provider "virtualbox" do |vb|
    # 禁用VirtualBox宿主机时间同步
    vb.customize ["setextradata", :id, "VBoxInternal/Devices/VMMDev/0/Config/GetHostTimeDisabled", "1"]
    # 按需修改为需要设置的目标时间:年/月/日/时/分/秒
    target_datetime = Time.new(2022, 6, 29, 12, 34, 56)
    # 自动计算BIOS时间偏移(单位:毫秒,早于当前时间为负值)
    offset_ms = ((target_datetime - Time.now) * 1000).to_i
    vb.customize ["modifyvm", :id, "--biossystemtimeoffset", offset_ms.to_s]
  end

  # 关闭虚拟机内部时间同步服务,避免内部校准
  config.vm.provision :shell, inline: <<-SHELL
    timedatectl set-ntp false
    systemctl disable --now systemd-timesyncd 2>/dev/null
    hwclock --systohc
  SHELL, run: "always"
end

配置说明:

  • :id是Vagrant内置占位符,会自动替换为当前启动的虚拟机实际名称,不需要手动填VM名
  • 仅需修改target_datetime参数即可调整目标时间,偏移量自动计算
  • 配置完成后执行vagrant reload生效,后续所有vagrant up启动都会自动保持配置的固定时间

备选方案:虚拟机内部配置(无VirtualBox层修改权限时使用)

如果无法调整VirtualBox底层配置,可通过关闭所有时间同步服务、添加开机自启任务的方式实现启动自动设时,配置如下:

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/focal64"  

  config.vm.provision :shell, inline: <<-SHELL
    # 禁用所有系统级时间同步服务
    systemctl mask --now systemd-timesyncd 2>/dev/null
    timedatectl set-ntp false
    # 禁用VirtualBox Guest Additions的时间同步能力
    VBoxService --disable-timesync 2>/dev/null
    systemctl mask --now vboxadd-service 2>/dev/null
    # 写入rc.local实现开机强制设置时间
    cat > /etc/rc.local << EOF
#!/bin/bash
date -s '2022-06-29 12:34:56'
hwclock --systohc
exit 0
EOF
    chmod +x /etc/rc.local
    # 立即生效
    date -s '2022-06-29 12:34:56'
    hwclock --systohc
  SHELL, run: "once"
end

注意:该方案未关闭VirtualBox层的时间同步通道,在虚拟机挂起恢复、快照回滚等场景下可能出现时间被重置的问题,稳定性弱于VirtualBox层配置方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 22:51:26