loops - Terraform - 循环
问题描述
是否可以创建一个循环来创建这些资源?相同的资源有很多重复。我尝试使用地图创建一个循环,但地图不接受任何其他默认块。
或者手动创建所有4个资源是否正常?只是一些建议作为答案就足够了,我正在尝试自己学习。
resource "aws_subnet" "public-test-a" {
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.16/28"
map_public_ip_on_launch = true
availability_zone = var.AZ[1]
tags = {
Name = var.subnets_names[index]
}
}
resource "aws_subnet" "public-test-b" {
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.16/28"
map_public_ip_on_launch = true
availability_zone = var.AZ[1]
tags = {
Name = "public-test-b"
}
}
resource "aws_subnet" "private-test-a" {
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.32/28"
availability_zone = var.AZ[0]
tags = {
Name = "private-test-a"
}
}
resource "aws_subnet" "private-test-b" {
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.48/28"
availability_zone = var.AZ[1]
tags = {
Name = "private-test-b"
}
}
我正在尝试这样的事情,但它似乎无效。
我们也不能aws_vpc.vpc-test-02.id
在变量内部使用,因为它是另一个 tf.
variable "subnets" {
type = map
default = {
vpc_id = aws_vpc.vpc-test-02.id
}
public-test-a = {
map_public_ip_on_launch = true
availability_zone = var.AZ[0]
}
public-test-b = {
map_public_ip_on_launch = true
availability_zone = var.AZ[1]
}
private-test-a = {
availability_zone = var.AZ[0]
}
private-test-b = {
availability_zone = var.AZ[1]
}
}
variable "AZ" {
type = list
default = ["ap-south-1a", "ap-south-1b", "ap-south-1c"]
}
variable "subnets_cird" {
type = list
default = ["10.0.0.0/28", "10.0.0.16/26", "10.0.0.32/28", "10.0.0.48/28"]
}
variable "subnets_names" {
type = list
default = ["public-test-a", "public-test-b", "private-test-a", "private-test-b"]
}
解决方案
对于 terraform 文档中的此搜索计数和 for_each。下面是一个示例,您可以如何将 public-test-a 和 public-test-b 替换为一个 public-test:
variable "number_of_subnets" {
default = 2
}
resource "aws_subnet" "public-test" {
count = var.number_of_subnets
vpc_id = aws_vpc.vpc-test-02.id
cidr_block = "10.0.0.16/28"
map_public_ip_on_launch = true
availability_zone = var.AZ[1]
tags = {
# here you pick the right name according to the subnet index, where e.g subnets_names = ["public-test-a","public-test-b"]
Name = var.subnets_names[count.index]
}
}
对 private_test 也可以这样做。
关于你尝试过的事情。变量不能被分配另一个变量。要实现此功能,请使用 locals:
locals {
x = aws_vpc.vpc-test-02.id
}
然后访问像
local.x
推荐阅读
- vba - PL/SQL 数据库值未正确反映到 SSIS 脚本
- mysql - 如何将我的 Android 应用程序连接到存储在服务器中的 MySQL 数据库?
- go - 如何根据请求 URL 使用 golang GIN 路由 HTTP 请求
- angular - Rxjs:被困在返回一个参数数组
- react-native - 未定义不是函数(评估'object.getOwnPropertyDescriptors(arguments [i])')
- excel - 如何创建一个删除包含先前日期的行的循环
- python - 每当我运行此代码时,Spider Kernel 都会死机
- python - 模型覆盖另一个模型
- python - 不同形状的列表
- python - 安装后无法运行matplotlib库的功能