遍历密钥名称更改的yaml文件



我尝试了几种方法来迭代yaml中的映射,但每次结果都会出现错误,例如:local.settings是具有#属性的对象。

首先是我的yaml和本地人设置

config:
params:
server:
host: 127.0.0.1
port: 8080
media:
name: foobar
type: html
s3:
bucket: foobarbucket
uploadFolder: folderfoobar
type:
public: false
email:
to: noreply@foobar.com


locals {
settings = yamldecode(file("test.yaml"))
}
module "store_write" {
source  = "cloudposse/ssm-parameter-store/aws"
for_each = local.settings.variables
parameter_write = [
{
name        = "/settings/${each.key}(i need each param key name ex: server)/${each.key.NEXTKET}(then the following key name after ex:host)"
value       = "${each.key.value}(that keys value, ex: 127.0.0.1)"
type        = "String"
overwrite   = "true"
description = "Terraform deployed param: ${local.app_name} ${each.key}"
}
]
}

现在,我当然可以从yaml文件中得到解码内容的输出,但我尝试的每个for循环都不起作用。在这一点上,我甚至找不到一个足够干净的粘贴在这里。我不认为我能达到我需要的,如果有时关键名称(例如:s3或电子邮件(会随着时间的推移而改变,对吗?

还注意到有时我可能会得到3个级别,

config:
params:
s3:
bucket: foobarbucket
uploadFolder: folderfoobar
type:
public: false

我在尝试以下内容时做得更进一步,不得不对yaml文件进行一点编辑。但现在我得到了重复的

locals {
params = yamldecode(file("./test.yaml"))["app"]
folder_project_apis = flatten([
for fk, param in local.params : [
for pk, config in param.params : [
for lk, name in config  : [
for vk, value in config : {
key1  = fk
key2 = pk
key3 = lk
value = value
}
]
]
]
])
}

使用新的yaml结构

app:
testing: #fk
display_name: "Folder A"
parent: 
params: 
server: #pk
host:
- 127.0.0.1
port:
- 3000
s3:
layout:
- "uploads"
image:
- "total"

输出

> local.folder_project_apis
[
{
"key1" = "testing"
"key2" = "s3"
"key3" = "image"
"value" = [
"total",
]
},
{
"key1" = "testing"
"key2" = "s3"
"key3" = "image"
"value" = [
"uploads",
]
},
{
"key1" = "testing"
"key2" = "s3"
"key3" = "layout"
"value" = [
"total",
]
},
{
"key1" = "testing"
"key2" = "s3"
"key3" = "layout"
"value" = [
"uploads",
]
},
{
"key1" = "testing"
"key2" = "server"
"key3" = "host"
"value" = [
"127.0.0.1",
]
},
{
"key1" = "testing"
"key2" = "server"
"key3" = "host"
"value" = [
3000,
]
},
{
"key1" = "testing"
"key2" = "server"
"key3" = "port"
"value" = [
"127.0.0.1",
]
},
{
"key1" = "testing"
"key2" = "server"
"key3" = "port"
"value" = [
3000,
]
},
]

如果我理解正确,您想遍历文件"test.yaml"中的映射并访问对象吗?您可以执行以下操作。

输出。tf

output host{
value = local.settings.params.server.host
}
output email {
value = local.settings.params.email
}

地形输出

email = {
"to" = "noreply@foobar.com"
}
host = "127.0.0.1"

您还担心,若键值被更改,那个么您就无法访问上面对yaml对象的解析,是的,这是正确的。

例如,如果我将给定文件中的"s3"更改为"s4",则应用地形。

  • s3的整个键值被移除并插入s4
~ params = {
- s3     = {
- bucket       = "foobarbucket"
- uploadFolder = "folderfoobar"
} -> null
+ s4     = {
+ bucket       = "foobarbucket"
+ uploadFolder = "folderfoobar"
}
# (3 unchanged elements hidden)
}
}

最新更新