terraform通过标签值引用新资源

时间:2017-10-25 15:33:15

标签: terraform

努力解决这个问题,下面是我的真实世界的例子,但我想一般的问题是:

如何在模板中创建一组对象,并根据名称标签之类的内容引用ID作为特定对象,以便在另一个资源中使用?

真实世界的例子:

所以我基于作为列表变量提供的子网名称列表动态创建一堆子网

variable "subnet_names" {
description = "subnet list"
default = ["subnet1","subnet2","dmz-a","dmz-b"]
}


resource "aws_subnet" "subnets" {
count = "${length(var.subnet_names)}"  
vpc_id = "${aws_vpc.vpc.id}"
cidr_block = "${cidrsubnet(var.vpc_cidr, 6, count.index)}"
map_public_ip_on_launch = "false"
availability_zone ="${element(slice(data.aws_availability_zones.available.names, 0, 2), count.index)} "
tags = "${merge(var.common_tags, map("Name", "${var.domain_short_name}-${var.subnet_names[count.index]}"))}"
}

这工作正常,但我想说,只将NAT网关连接到某些子网,例如让我们说dmz,但我无法弄清楚如何为上面创建的特定子网引用subnet_id ...我想那里必须是一种构建新子网地图{subnet_ID:tags.name}的方法,并通过查找tags.name选择一个,这将是corp-dmz-a的示例

resource "aws_nat_gateway" "nat" {
allocation_id = "${aws_eip.nat_gw.id}"
subnet_id = ???????????????????????????
tags = "${merge(var.common_tags, map("Name", "${var.vpc_name_prefix}${var.domain_short_name}${var.region_short_name}-NAT" ))}"
depends_on = ["aws_internet_gateway.igw","aws_subnet.subnets"]
}

任何有关如何处理此问题的建议都会受到赞赏,我一直在尝试几种不同的方法,但我认为我缺少一些基本的理解,也许甚至更简单的插值方法和我缺少的其他功能< / p>

1 个答案:

答案 0 :(得分:1)

管理提出似乎有效的解决方案,似乎也是一个非常方便的技术分享,所以我自己回答

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#block1">Block one</a></li>
      <li><a href="#block2">Block two</a></li>
      <li><a href="#block3">Block three</a></li>
    </ul>
  </div>
</nav>

<div id="block1" class="block">
  <div class="container">
    <div class="row-fluid">
      There is block one
    </div>
  </div>
</div>

<div id="block2" class="block">
  <div class="container">
    <div class="row-fluid">
      There is block two
    </div>
  </div>
</div>

<div id="block3" class="block">
  <div class="container">
    <div class="row-fluid">
      There is block three
    </div>
  </div>
</div>