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

如何用Packer在Azure创建含大文件的Windows Server 2019镜像并执行脚本?

在Azure上构建Windows Server 2019镜像的大文件传输最佳方案

针对你遇到的WinRM复制大文件速度过慢的问题,以下是几个高效可行的解决方案,按推荐优先级排序:

1. 使用Azure文件共享传输文件

Azure文件共享是Azure原生服务,可直接挂载到Windows VM,操作简单且传输稳定,适配Packer构建流程:

  • 提前在Azure创建存储账户和文件共享,将200MB工件文件上传至共享。
  • 在Packer的WinRM provisioner中添加PowerShell脚本,完成挂载、复制、卸载流程:
    # 挂载Azure文件共享
    $storageAccountName = "你的存储账户名"
    $fileShareName = "你的文件共享名"
    $storageAccountKey = "你的存储账户密钥"
    $mountPoint = "Z:"
    New-PSDrive -Name ($mountPoint.TrimEnd(':')) -PSProvider FileSystem -Root "\\$storageAccountName.file.core.windows.net\$fileShareName" -Credential (New-Object System.Management.Automation.PSCredential "Azure\$storageAccountName", (ConvertTo-SecureString $storageAccountKey -AsPlainText -Force))
    
    # 复制文件到VM本地
    Copy-Item -Path "$mountPoint\你的工件文件名" -Destination "C:\构建目录\" -Force
    
    # 卸载共享
    Remove-PSDrive -Name ($mountPoint.TrimEnd(':'))
    
  • 优势:无需额外安装工具,传输稳定,适合大文件场景,维护成本低。

2. 启用OpenSSH服务器,全程使用SSH provisioner

Windows Server 2019原生支持OpenSSH服务器,可直接在Packer中配置启用,全程用SSH完成文件上传和脚本执行,避开WinRM限制:

  • 在Packer的azure-arm builder中添加自定义数据启用OpenSSH:
    "custom_data": "#ps1\nAdd-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0\nStart-Service sshd\nSet-Service -Name sshd -StartupType 'Automatic'\n"
    
  • 配置Packer的SSH连接参数:
    "ssh_username": "你的VM用户名",
    "ssh_password": "你的VM密码",
    "ssh_port": 22
    
  • 使用SSH provisioner上传文件(scp速度远快于WinRM):
    {
      "type": "file",
      "source": "./本地工件文件路径",
      "destination": "C:\\构建目录\\你的工件文件名"
    }
    
  • 使用SSH provisioner执行PowerShell脚本:
    {
      "type": "shell",
      "inline": [
        "powershell -ExecutionPolicy Bypass -File C:\\构建目录\\你的脚本.ps1"
      ]
    }
    
  • 优势:传输速度快,全程单provisioner完成,无需切换,流程简洁高效。

3. 优化WinRM配置提升传输速度

如果坚持使用WinRM,可通过调整核心参数提升传输效率:

  • 在Packer的WinRM provisioner中添加初始化脚本修改WinRM设置:
    # 增大WinRM envelope大小
    Set-Item -Path WSMan:\localhost\MaxEnvelopeSizeKB -Value 10240
    # 启用HTTP压缩
    Set-Item -Path WSMan:\localhost\Service\EnableCompatibilityHttpListener -Value true
    Set-Item -Path WSMan:\localhost\Service\EnableCompatibilityHttpsListener -Value true
    Restart-Service WinRM
    
  • 同时在Packer配置中调整WinRM超时和块大小:
    "winrm_timeout": "30m",
    "winrm_max_envelope_size_bytes": 10485760
    
  • 优势:无需额外依赖,仅需调整配置,但速度提升幅度有限,适合对现有流程改动最小的场景。

内容的提问来源于stack exchange,提问作者Alex G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:30:57