【问题标题】:How to fetch id of a variable using name in terraform?如何在 terraform 中使用名称获取变量的 id?
【发布时间】:2021-11-10 17:38:54
【问题描述】:

我有一个 terraform 资源,我试图在其中使 subnet_id 变量动态化。所以我在下面定义了变量subnet_id = "worker-subnet-1"。我想传递子网的名称并获取子网 ID,因为我有多个子网。我该怎么做。

resource "oci_containerengine_node_pool" "node_pool" {
  for_each       = var.nodepools
  cluster_id     = oci_containerengine_cluster.cluster[0].id
  compartment_id = var.compartment_id
  depends_on     = [oci_containerengine_cluster.cluster]

  kubernetes_version = var.cluster_kubernetes_version
  name               = each.value["name"]

  node_config_details {
    placement_configs {
      availability_domain = var.availability_domain
      subnet_id           = oci_core_subnet.each.value["subnet_name"].id
    }
    size = each.value["size"]
  }

  node_shape = each.value["node_shape"]

  node_shape_config {

    #Optional
    memory_in_gbs = each.value["memory"]
    ocpus         = each.value["ocpus"]
  }

  node_source_details {
    image_id    = each.value["image_id"]
    source_type = "IMAGE"

  }
  ssh_public_key = file(var.ssh_public_key_path)
}

这些是我的变量:

nodepools = {
  np1 = {
    name       = "np1"
    size       = 3
    ocpus      = 8
    memory     = 120
    image_id   = "test"
    node_shape = "VM.Standard2.8"
    subnet_name  = "worker-subnet-1"
  }
  np2 = {
    name       = "np2"
    size       = 2
    ocpus      = 8
    memory     = 120
    image_id   = "test"
    node_shape = "VM.Standard2.8"
    subnet_name  = "worker-subnet-1"
  }
}

有什么建议吗?

resource "oci_core_subnet" "snet-workers" {
  cidr_block                 = lookup(var.subnets["snet-workers"], "subnet_cidr")
  compartment_id             = var.compartment_id
  vcn_id                     = oci_core_virtual_network.base_vcn.id
  display_name               = lookup(var.subnets["snet-workers"], "display_name")
  dns_label                  = lookup(var.subnets["snet-workers"], "dns_label")
  prohibit_public_ip_on_vnic = true
  security_list_ids          = [oci_core_security_list.private_worker_nodes.id]
  route_table_id             = oci_core_route_table.rt-nat.id
}

【问题讨论】:

    标签: terraform


    【解决方案1】:

    您必须像下面这样使用,将<local resource name> 更改为您为资源指定的名称

    subnet_id = oci_core_subnet.<local resource name>[each.value.subnet_id].id
    

    【讨论】:

    • 本地资源名取什么值以及如何声明?
    • 我也想从变量中读取值并获取 id。
    • 我想从变量中读取名称,这就是重点
    • 得到错误:An attribute name is required after a dot.我的声明是subnet_id = oci_core_subnet.test-workers.[each.value.subnet_id].id
    • 原始问题已解决。为此,您应该提出新问题并提供带有输入变量的完整代码
    猜你喜欢
    • 2022-06-27
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    相关资源
    最近更新 更多