[英]How to convert the aws secret manager string to map in terraform (0.11.13)
[英]Terraform - How to convert lists into map (How to fetch AMI tags using terraform)
我正在尝试使用 AWS CLI 获取 AMI 的标签,并希望重用 output 中的值。我下面有一个 terraform 代码,它以字符串格式(可能不确定格式)返回输出,我想将其转换为 map object。
variable "ami" {
default = "ami-xxxx"
}
locals {
tags = {
"platform" = lookup(data.local_file.read_tags.content, "platform", "") #Expecting to get platform from Map of read_tags
}
}
data "template_file" "log_name" {
template = "${path.module}/output.log"
}
resource "null_resource" "ami_tags" {
provisioner "local-exec" {
command = "aws ec2 describe-tags --filters Name=resource-id,Values=${var.ami} --query Tags[*].[Key,Value] > ${data.template_file.log_name.rendered}"
}
}
data "local_file" "read_tags" {
filename = "${data.template_file.log_name.rendered}"
depends_on = ["null_resource.ami_tags"]
}
output "tags" {
value = local.tags
}
output "cli-output-tags" {
value = "${concat(data.local_file.read_tags.content)}"
}
cli-output-tags的 output 如下:
[
[
"ENV",
"DEV"
],
[
"Name",
"Base-AMI"
],
[
"platform",
"Linux"
]
]
我如何使用 terraform/(jq 命令)将此 output 转换为 Map,或者是否有任何其他方法直接从cli-output-tags output 获取所需的值:
{
ENV = "DEV",
Name = "Base-AMI",
platform = "Linux"
}
我也试过像下面那样更改 CLI 命令,但仍然无法按预期获取值:
'Tags[].{Key:Key,Value:Value}'
结果如下 output:
[
{
"Key": "ENV",
"Value": "DEV"
},
{
"Key": "Name",
"Value": "Base-AMI"
},
{
"Key": "platform",
"Value": "Linux"
}
]
你可以使用zipmap :
output "cli-output-tags" {
value = zipmap(
jsondecode(data.local_file.read_tags.content)[*][0],
jsondecode(data.local_file.read_tags.content)[*][1]
)
}
该代码首先将文件中的字符串数据更改为 json,然后获取所有第一个元素[*][0]
(第二个元素[*][1]
相同),并将它们压缩到 map。
我怎样才能将这个 output 转换成 Map 如下
一种方法是按如下方式使用 jq(假设cli-output-tags
是保存 JSON 数组的文件的名称):
jq -r -f '"{", (.[] | "\(.[0]) = \"\(.[1])\""), "}"' cli-output-tags
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.