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

使用Terraform创建Azure VM时从私有存储账户执行PowerShell脚本遇403错误

问题描述

我正在编写Terraform代码,希望在创建Azure VM时从已禁用Blob公共访问的存储账户读取并执行PowerShell脚本。最初尝试直接使用Blob公共URL的方案报错冲突,修改为在protected_settings中传入存储账户密钥后,现在出现403禁止访问错误,且已确认存储账户密钥正确。

首次尝试代码

resource "azurerm_virtual_machine_extension" "powershell" {
  count = length(var.instances)
  name = "runpowershell"
  virtual_machine_id = azurerm_windows_virtual_machine.vm.*.id[count.index]
    depends_on           = [azurerm_windows_virtual_machine.vm]
    publisher            = "Microsoft.Compute"
    type                 = "CustomScriptExtension"
    type_handler_version = "1.9"
settings             = <<SETTINGS
      {
          "fileUris": ["https://test.blob.core.windows.net/scripts/deployment.ps1"],
          "commandToExecute": "powershell -ExecutionPolicy Unrestricted -file deployment.ps1"
                
      }
  SETTINGS
}

修改后代码

resource "azurerm_virtual_machine_extension" "powershell" {
  count = length(var.instances)
  name = "runpowershell"
  virtual_machine_id = azurerm_windows_virtual_machine.vm.*.id[count.index]
  depends_on           = [azurerm_windows_virtual_machine.vm]
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.9"

  settings             = <<SETTINGS
      {
          "fileUris": ["https://test.blob.core.windows.net/scripts/deployment.ps1"]                          
      }
  SETTINGS

  protected_settings = <<PROTECTED_SETTINGS
       {
           "storageAccountKey": "Vg/4BBah3......ASt2sbGww==",
            "storageAccountName": "test",
            "commandToExecute": "powershell -ExecutionPolicy Unrestricted -File deployment.ps1"
       }
   PROTECTED_SETTINGS
}

报错信息

Error: Code="VMExtensionProvisioningError" Message="VM has reported a failure when processing extension 'runpowershell'. Error message: "Failed to download all specified files. Exiting. Error Message: The remote server returned an error: (403) Forbidden."\r\n\r\nMore information on troubleshooting is available at https://aka.ms/VMExtensionCSEWindowsTroubleshoot "

解决方案
  • 检查存储账户网络防火墙配置:
    如果存储账户设置了"允许选定的网络"访问,必须将VM所在的虚拟网络或公网IP添加到存储账户的允许列表中。若使用存储专用端点,需确保VM所在VNet已配置对应端点,且DNS解析正常。

  • 升级CustomScriptExtension版本:
    版本1.9过于老旧,存在潜在的兼容性问题。建议升级到最新稳定版本(如1.14),新版本对存储账户密钥验证、网络访问逻辑有优化。

  • 验证Blob路径与容器权限:
    确认fileUris中的容器名、Blob文件名完全正确,存储容器访问级别设为私有即可,账户密钥默认拥有私有Blob的读取权限。

  • 检查JSON格式:
    确保settings和protected_settings中的JSON语法无错误,比如引号配对、逗号位置正确,格式错误会导致扩展无法正确读取存储账户密钥。

  • 重新生成存储账户密钥:
    即使确认密钥正确,也可尝试重新生成存储账户的主/辅助密钥并替换到代码中,排除密钥过期、复制错误的可能性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 11:24:23