簡體   English   中英

Terraform - 如何將列表轉換為 map(如何使用 terraform 獲取 AMI 標簽)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM