0

我需要使用 terraform api 将数组和地图值传递给 terraform 工作区

试着打电话

{
    "data": {
      "id":"",
      "attributes": {
        "key":"PREFIXES",
        "value":'{a="b"}',
        "description":"some description",
        "category":"terraform",
        "hcl": false,
        "sensitive": false
      },
      "type":"vars"
    }
  }

卷曲电话是

curl \
  --header "Authorization: Bearer $TOKEN" \
  --header "Content-Type: application/vnd.api+json" \
  --request PATCH \
  --data @payload.json \
  https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/vars/$PREFIXES_ID

以错误告终

{"errors":[{"status":"400","title":"JSON body is invalid","detail":"784: unexpected token at '{    \"data\": {      \"id\":\"\",      \"attributes\": {        \"key\":\"PREFIXES\",        \"value\":'{a=\"b\"}',        \"description\":\"some description\",        \"category\":\"terraform\",        \"hcl\": false,        \"sensitive\": false      },      \"type\":\"vars\"    }  }'"}]}

我尝试使用 python 实现相同的功能。我的 terraform 如何给出错误:

错误:for_each 参数无效

在 main.tf 第 18 行,在资源“aws_s3_bucket_object”“obj”中:18:for_each = var.prefixes

python3
def update_workspace_vars(workspace_vars, var_values, params):
    headers = {"Authorization": "Bearer " + params["TOKEN"],
               "Content-Type": "application/vnd.api+json"}
    for k in var_values:
        payload = {
            "data": {
                "id": workspace_vars[k],
                "attributes": {
                    "key": k,
                    "value": var_values[k],
                    "category": "terraform"
                },
                "type": "vars"
            }
        }
        patch_params = dict((k, params[k]) for k in ("workspace_id", "tfe_host"))
        patch_params.update({"var_id": workspace_vars[k]})
        url = "https://{tfe_host}/api/v2/workspaces/{workspace_id}/vars/{var_id}".format(**patch_params)
        response = http.request("PATCH", url, headers=headers, body=json.dumps(payload)).data


var_variables = {"prefixes": {"a": ["a1", "a2", "a3"], "b": ["b1", "b2", "b3"]}}

和我的地形代码:


resource "aws_s3_bucket" "b" {
  bucket = "my-tf-test-bucket-pinnaka"
  acl    = "private"
}

resource "aws_s3_bucket_object" "obj" {
  for_each = var.prefixes
  bucket = aws_s3_bucket.b.id
  key = each.key
  content = each.value
}```
4

2 回答 2

1

您的 JSON 似乎无效。

{
    "data": {
      "id":"",
      "attributes": {
        "key":"PREFIXES",
        "value":'{a="b"}',
        "description":"some description",
        "category":"terraform",
        "hcl": false,
        "sensitive": false
      },
      "type":"vars"
    }
  }

"value":'{a="b"}'是无效的 JSON 语法。

用作"value": { "a" : "b"}JSON 或以其他方式"value":\"{a=\'b\'}\"转义单引号以防止 {"a"="b"} 被解析为 JSON。

于 2020-12-26T08:19:16.420 回答
0

我创建了一个局部变量名称 local_prefix 并将 var.prefixes 传递给 jsoncode。

这行得通。

locals{
 local_prefix = jsoncode(var.prefix)
}

在 local_prefix 上申请 for_each

于 2021-01-01T12:42:15.103 回答