【问题标题】:Terraform - Extract a value based on text from outputTerraform - 根据输出中的文本提取值
【发布时间】:2019-10-28 10:23:35
【问题描述】:

我有以下在 GCP 上创建子网的模块:

/******************************************
    Subnet configuration
 *****************************************/
resource "google_compute_subnetwork" "subnetwork" {
  count = "${length(var.subnets)}"

  name                     = "${lookup(var.subnets[count.index], "subnet_name")}"
  ip_cidr_range            = "${lookup(var.subnets[count.index], "subnet_ip")}"
  region                   = "${lookup(var.subnets[count.index], "subnet_region")}"
  private_ip_google_access = "${lookup(var.subnets[count.index], "subnet_private_access", "false")}"
  enable_flow_logs         = "${lookup(var.subnets[count.index], "subnet_flow_logs", "false")}"
  network                  = "${google_compute_network.network.name}"
  project                  = "${var.project_id}"

  secondary_ip_range = "${var.secondary_ranges[lookup(var.subnets[count.index], "subnet_name")]}"
}

data "google_compute_subnetwork" "created_subnets" {
  count = "${length(var.subnets)}"

  name    = "${element(google_compute_subnetwork.subnetwork.*.name, count.index)}"
  region  = "${element(google_compute_subnetwork.subnetwork.*.region, count.index)}"
  project = "${var.project_id}"
}

我的输出如下所示:

output "subnets_self_links" {
  value       = "${google_compute_subnetwork.subnetwork.*.self_link}"
  description = "The self-links of subnets being created"
}

此输出生成子网列表。

我需要能够通过搜索子网名称来提取以下内容。在这种情况下,它是“subnet-01”:

subnetwork = "https://www.googleapis.com/compute/v1/projects/abc-network-hub/regions/us-central1/subnetworks/subnet-01"

如何构建查找以按文本搜索?

subnetwork = "${module.test-vpc.subnets_self_links}"

以上返回:

"module.compute-o057qdb2-l30.var.subnetwork: 变量子网在 模块 compute-o057qdb2-l30 应该是字符串类型,得到列表”

subnetwork = "${lookup(module.test-vpc.subnets_self_links, "subnet-01, 0")}"

以上回报:

  • module.compute-o057qdb2-l30.var.subnetwork:在第 3 列第 1 行:查找:参数 1 应该是类型映射,类型列表位于:

${lookup(module.test-vpc.subnets_self_links, "subnet-01, 0")}

subnetwork = "${module.test-vpc.subnets_self_links[0]}"

上述方法有效,因为只创建了一个子网,我可以通过列表索引进行引用。我需要能够按子网名称搜索。我觉得我应该能够从“数据”中提取值。

这是我正在使用的模块:https://github.com/terraform-google-modules/terraform-google-network

【问题讨论】:

    标签: google-cloud-platform terraform


    【解决方案1】:

    Terraform 0.12 让这一切变得简单:

    variable "subnets" {
        default = [
            {
                name = "subnet-01"
                id = 1
            },
            {
                name = "subnet-02"
                id = 2
            }
        ]
    }
    
    output "subnet-one" {
        value = [
            for subnet in var.subnets:
                subnet.id if subnet.name == "subnet-01"
        ][0]
    }
    

    在 HCL 2 之前,这种东西非常麻烦。

    【讨论】:

    • 谢谢!我真的应该开始跳到 0.12
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2021-10-05
    • 2022-01-18
    • 2019-08-26
    • 2023-01-18
    • 1970-01-01
    相关资源
    最近更新 更多