Terraform上传PowerShell脚本至存储容器时索引错误求助
场景与问题
你通过for_each基于local.sta_ctn配置创建存储容器,尝试将PowerShell脚本上传到名为exploitation的容器时,使用数字索引[0]引用容器出现错误。
相关配置代码
locals定义(var.tf):
locals { sta_ctn = { "exploitation" = { sta = azurerm_storage_account.terra_sta[0].name, access_type = "private" } }
存储容器与Blob配置(storage_account.tf):
resource "azurerm_storage_container" "terra_sta_ctn" { for_each = local.sta_ctn name = each.key storage_account_name = each.value.sta container_access_type = each.value.access_type } resource "azurerm_storage_blob" "terra_sta_ctn_ansible" { name = "ConfigureRemotingForAnsible.ps1" storage_account_name = azurerm_storage_account.terra_sta[0].name storage_container_name = azurerm_storage_container.terra_sta_ctn[0].name type = "Block" source = "${path.root}/_scripts/ansible/ConfigureRemotingForAnsible.ps1" }
错误信息
│ Error: Invalid index
│
│ on storage_account.tf line 26, in resource "azurerm_storage_blob" "terra_sta_ctn_ansible":
│ 26: storage_container_name = azurerm_storage_container.terra_sta_ctn[0].name
│ ├────────────────
│ │ azurerm_storage_container.terra_sta_ctn is object with 1 attribute "exploitation"
│
│ The given key does not identify an element in this collection value. An object only supports looking up attributes by name, not by numeric index.
错误原因
使用for_each创建的资源实例集合是键值对对象,而非列表,因此无法通过数字索引(如[0])访问,必须通过对应的键名(如"exploitation")来引用。
解决方案
方案1:直接通过键名引用目标容器(当前需求首选)
修改azurerm_storage_blob中的storage_container_name字段,明确指定容器的键名:
resource "azurerm_storage_blob" "terra_sta_ctn_ansible" { name = "ConfigureRemotingForAnsible.ps1" storage_account_name = azurerm_storage_account.terra_sta[0].name storage_container_name = azurerm_storage_container.terra_sta_ctn["exploitation"].name type = "Block" source = "${path.root}/_scripts/ansible/ConfigureRemotingForAnsible.ps1" }
这种方式直接精准指向你需要的exploitation容器,符合当前的需求场景。
方案2:扩展兼容多容器场景(未来复用)
如果后续计划在local.sta_ctn中添加更多容器,且每个容器都需要上传该脚本,可以将Blob资源也改为for_each配置,复用本地映射:
resource "azurerm_storage_blob" "terra_sta_ctn_ansible" { for_each = local.sta_ctn name = "ConfigureRemotingForAnsible.ps1" storage_account_name = each.value.sta storage_container_name = each.key type = "Block" source = "${path.root}/_scripts/ansible/ConfigureRemotingForAnsible.ps1" }
此配置会自动为每个新增的容器上传脚本,无需手动修改Blob资源代码。
内容的提问来源于stack exchange,提问作者Cookies

