gpt4 book ai didi

amazon-web-services - Terraform JSON 生成

转载 作者:行者123 更新时间:2023-12-05 01:11:36 26 4
gpt4 key购买 nike

我正在尝试创建一个 AWS dashboard using terraform显示 S3 指标。我正在考虑遍历存储在列表变量中的所有 S3 存储桶并生成仪表板 json。

for 循环能够添加指标,但我无法删除尾随的逗号,这会导致错误的 json。

  1. 有没有使用这种方法修复此 json 的简单方法?
  2. 有没有更好的json处理方式?
  3. 我应该为此处理使用 terraform 吗?

代码片段:-

dashboard_body = <<EOF
{
"start":"-P6M",
"widgets": [
{
"type":"metric",
"x":0,
"y":0,
"width":12,
"height":6,
"properties":{
"metrics":[
%{ for bucket in var.buckets }
[
"AWS/S3",
"BucketSizeBytes",
"StorageType",
"StandardStorage",
"BucketName",
"${bucket}"
]
%{ endfor }
],
"period":86400,
"stat":"Average",
"region":"us-east-1",
"title":"Storage usage"
}
}
]
}
EOF

解决方法:-我最终在“指标”数组的末尾硬编码了一个额外的聚合。无论如何我都需要总数,这是一个简单的解决方法。 @kharandziuk 是理想的实现方式,但即便如此,您也可能需要使用此解决方法。

最终代码:-

{
"start":"-P6M",
"widgets": [
{
"type":"metric",
"x":0,
"y":0,
"width":12,
"height":6,
"properties":{
"metrics":[
%{ for bucket in buckets }
[
"AWS/S3",
"BucketSizeBytes",
"StorageType",
"StandardStorage",
"BucketName",
"${bucket}"
],
%{ endfor }
[
{ "expression": "SUM(METRICS())", "label": "Total Storage", "id": "e3" }
]
],
"period":86400,
"stat":"Average",
"region":"us-east-1",
"title":"Storage usage"
}
}
]
}

最佳答案

Is there an easy way to fix this json using this approach?

我会使用 jsonencode在 HCL 中制作 map 并将其转换为 JSON 的函数。

Is there a better way to do json processing?

有。尝试 templatefile功能。您将拥有一个模板并将一些变量插入其中。

Should I be using terraform for this processing?

是的,你应该。 Terraform 提供了执行此操作的工具。代码应类似于下面的示例代码:

variable "buckets" {
default = ["max", "sandeep"]
}

locals{
dashboard_body = templatefile("${path.module}/file.json.tmpl", {
metrics = jsonencode( # we create the list in HCL and transform it into json
[for bucket in var.buckets: [
"AWS/S3",
"BucketSizeBytes",
"StorageType",
"StandardStorage",
"BucketName",
"${bucket}"
]
]
)
})
}

output "result" {
value = local.dashboard_body
}

file.json.tmpl 是:

{
"start":"-P6M",
"widgets": [
{
"type":"metric",
"x":0,
"y":0,
"width":12,
"height":6,
"properties":{
"metrics": ${metrics},
"period":86400,
"stat":"Average",
"region":"us-east-1",
"title":"Storage usage"
}
}
]
}

关于amazon-web-services - Terraform JSON 生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62888707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com