尝试使用 terraform 输出 csv 文件的内容时遇到错误

问题描述

我正在尝试使用 terraform 变量数据(CSV 文件)创建资源组,并将资源组的名称添加到 CSV 文件中。我目前遇到以下错误

错误不支持属性 │ │ 在 testtf.tf 第 11 行,在资源“azurerm_resource_group”“Main”中: │ 11: name = local.resource_groupname[count.index].groupname │ ├────────────────── │ │ count.index 是一个数字,只有apply才知道 │ │ local.resource_groupname 是包含 3 个元素的对象列表 │ │ 这个对象没有名为“groupname”的属性

代码

provider "azurerm" {
    features{}
}

locals {
      resource_groupname = csvdecode(file("./test.csv"))
    }

    resource "azurerm_resource_group" "Main" {
      count    = length(local.resource_groupname)
      name     =  local.resource_groupname[count.index].groupname   
      location = "north europe"
    }

./test.csv 内容

https://drive.google.com/file/d/1ituKDzaMVXnyynkjLBZRzMdWK9tnkL14/view?usp=sharing

解决方法

我认为您提供的文件具有 UTF BOM(字节顺序标记)字节,会导致 TF 和/或 Azure 阻塞。

我将 csv 文件重新创建为纯 ascii,您的 HCL 工作正常

我通过使用 terraform console 发现了额外的字符。这是排查 TF 错误的一种非常简单快捷的方法。

我使用这个非常基本的 .tf 文件来检查 cvsdecode() 行为。 (下面的 test0.csv 是您的原始文件,而 test.csv 是我从头开始创建的文本文件):

locals {
      resource_groupname0 = csvdecode(file("./test0.csv"))
      resource_groupname = csvdecode(file("./test.csv"))
 }

运行 terraform 控制台并检查局部变量。请注意“groupname”(test0.csv)之前的 BOM 字符:

$ terraform console
> local.resource_groupname0
tolist([
  {
    "\ufeffgroupname" = "test11"
  },{
    "\ufeffgroupname" = "test12"
  },{
    "\ufeffgroupname" = "test13"
  },])
> local.resource_groupname
tolist([
  {
    "groupname" = "test11"
  },{
    "groupname" = "test12"
  },{
    "groupname" = "test13"
  },])

同样使用 unix file 命令:

## Your file
$ file test0.csv
test0.csv: UTF-8 Unicode (with BOM) text,with CRLF line terminators

## Created by hand with text editor
$ file test.csv
test.csv: ASCII text