问题描述
我是terraform的新手,我试图分别使用单个代码块为多个子网和实例创建多个资源。 我可以使用以下代码创建子网
# subnets : LoadBalancer
resource "aws_subnet" "lb" {
count = length(var.lb_subnets_cidr)
vpc_id = aws_vpc.terra_vpc.id
cidr_block = element(var.lb_subnets_cidr,count.index)
availability_zone = element(var.azs,count.index)
map_public_ip_on_launch = true
tags = {
Name = "test-lb-subnet-${count.index+1}"
}
}
# subnets : App
resource "aws_subnet" "app" {
count = length(var.app_subnets_cidr)
vpc_id = aws_vpc.terra_vpc.id
cidr_block = element(var.app_subnets_cidr,count.index)
map_public_ip_on_launch = true
tags = {
Name = "test-app-subnet-${count.index+1}"
}
}
# subnets : Databases
resource "aws_subnet" "db" {
count = length(var.db_subnets_cidr)
vpc_id = aws_vpc.terra_vpc.id
cidr_block = element(var.db_subnets_cidr,count.index)
map_public_ip_on_launch = false
tags = {
Name = "test-db-subnet-${count.index+1}"
}
}
我无法使用以下代码创建实例
#key pair
resource "aws_key_pair" "test_key" {
key_name = var.key_name
public_key = file(var.public_key_path)
}
#AWS instances
resource "aws_instance" "servers" {
count = length(var.instance_type)
instance_type = element(var.instance_type,count.index)
ami = var.ami
tags = {
Name = element(var.instance_name,count.index)
}
key_name = aws_key_pair.test_key.id
vpc_security_group_ids = [aws_security_group.jump_sg.id]
subnet_id = element(local.subs,count.index)
private_ip = element(var.private_ip,count.index)
}
下面也是我的variable.tf文件。
variable "instance_type" {
type = list
default = ["t2.micro","c5.xlarge","m5.xlarge","r5.large","r5.large"]
}
variable "instance_name" {
type = list
default = ["jump-server-test","test-app-01","test-mongodb-01","test-mongodb-02","test-mongodb-03","test-redis-01","test-redis-02"]
}
variable "private_ip" {
type = list
default = ["172.17.7.10","172.17.10.10","172.17.4.10","172.17.5.10","172.17.6.10","172.17.4.20","172.17.5.20"]
}
locals {
subs = concat([aws_subnet.jump.id],[aws_subnet.app.id],[aws_subnet.db.id])
}
variable "ami" {
default = "ami-b73b63a0"
}
Error: Missing resource instance key
on variables.tf line 49,in locals:
49: subs = concat([aws_subnet.jump.id],[aws_subnet.db.id])
Because aws_subnet.app has "count" set,its attributes must be accessed on
specific instances.
For example,to correlate with indices of a referring resource,use:
aws_subnet.app[count.index]
Error: Missing resource instance key
on variables.tf line 49,[aws_subnet.db.id])
Because aws_subnet.db has "count" set,use:
aws_subnet.db[count.index]
尝试了不同的解决方案。但似乎我无法抓住。 预先感谢。
解决方法
用以下内容替换variables.tf第49行:
subs = concat([for sn in aws_subnet.jump: sn.id],[for sn in aws_subnet.app: sn.id],[for sn in aws_subnet.db: sn.id])