Terraform plan指定for_each资源时双引号被忽略报索引错误
报错原因
这个报错由命令行Shell的引号解析机制触发,和Terraform本身的资源地址语法无关。
当你直接输入原始命令时,当前使用的终端Shell会自动识别、解析参数里的双引号,把双引号作为Shell语法符号吞掉,最终传递给Terraform程序的target参数值实际为module.virtualmachinescaleset.azurerm_linux_virtual_machine_scale_set.this[x]。方括号内的键值x没有被字符串字面量包裹,不符合Terraform资源索引的语法要求,就会抛出Index brackets must contain either a literal number or a literal string错误。
解决方法
根据你使用的终端环境,选择对应的写法,保证传入Terraform的参数里完整保留索引外的双引号即可:
- 类Unix环境(Linux、macOS默认的Bash/Zsh终端):用单引号把整个
-target的参数值包裹起来,让Shell不解析内部的双引号:
terraform plan -target='module.virtualmachinescaleset.azurerm_linux_virtual_machine_scale_set.this["x"]'
- Windows Cmd终端:用反斜杠转义索引位置的双引号:
terraform plan -target=module.virtualmachinescaleset.azurerm_linux_virtual_machine_scale_set.this[\"x\"]
- Windows PowerShell终端:优先用单引号包裹整个target参数值,写法和类Unix环境一致;也可以用PowerShell专用的转义符反引号转义内部双引号:
# 推荐写法 terraform plan -target='module.virtualmachinescaleset.azurerm_linux_virtual_machine_scale_set.this["x"]' # 转义写法 terraform plan -target=module.virtualmachinescaleset.azurerm_linux_virtual_machine_scale_set.this`"x`"
通用提示:针对for_each生成的带字符串索引的资源,优先使用单引号整段包裹target参数值的写法,兼容性最高,能规避绝大多数Shell解析导致的参数传递错误。
内容的提问来源于stack exchange,提问作者ch shaik
相关产品推荐
相关产品推荐

