Terraform使用yamlencode生成YAML顺序反向问题如何解决
问题根因
Terraform 中的对象(map)类型本质是无序集合,yamlencode 函数官方默认会按照键的字典序对输出的YAML键进行排序,和你在local块中定义的顺序没有关联,reverse函数仅适用于有序的列表/元组类型,自然无法作用于对象。
可行解决方案
方案1:使用多行字符串模板直接生成YAML(最直接可控)
放弃使用yamlencode,直接通过HCL的heredoc字符串定义YAML内容,顺序完全由你自己控制,示例配置如下:
locals { yaml_content = <<-EOT version: 1 service: name: ${var.service_name} description: ${var.description} product: ${var.product_name} aliases: ${jsonencode(var.aliases)} owner: ${var.organization} lifecycle: ${var.service_lifecycle} tier: ${var.tier} language: ${var.language} framework: ${var.framework} repositories: name: ${var.organization}/${var.name} path: "/" provider: "github" display_name: ${var.service_name} EOT }
修改github_repository_file的content字段即可:
content = local.yaml_content
注意:如果是字符串以外的变量类型(比如列表、数字),可以用
jsonencode处理后插入,避免YAML格式错误;另外你的配置中存在拼写错误serivce,建议统一修正为service避免后续调用出错。
方案2:使用templatefile渲染外部YAML模板
如果YAML结构比较复杂,可以单独存为模板文件,比如yaml.tpl,在文件中写好固定顺序的YAML结构和插值占位符,然后用templatefile函数渲染:
- 新建
yaml.tpl文件:
version: 1 service: name: ${service_name} description: ${description} product: ${product_name} aliases: ${aliases} owner: ${organization} lifecycle: ${service_lifecycle} tier: ${tier} language: ${language} framework: ${framework} repositories: name: ${organization}/${name} path: "/" provider: "github" display_name: ${service_name}
- 修改配置调用templatefile:
content = templatefile("${path.module}/yaml.tpl", { service_name = var.service_name description = var.description product_name = var.product_name aliases = jsonencode(var.aliases) organization = var.organization service_lifecycle = var.service_lifecycle tier = var.tier language = var.language framework = var.framework name = var.name })
内容的提问来源于stack exchange,提问作者sd-gallowaystorm
相关产品推荐
相关产品推荐

