How to create multiple resources in a for loop with terraform?

10,622

An example to create AWS VPC subnets then give them to AWS EC2 instances.

resource "aws_subnet" "public" {
  count = length(var.public_subnet_cidr_blocks)
  vpc_id     = var.vpc_id
  cidr_block = var.public_subnet_cidr_blocks[count.index]
}

resource "aws_instance" "public_ec2" {
  count = length(var.public_subnet_ids)
  subnet_id = var.public_subnet_ids[count.index]
  ami           = var.ami_id
  instance_type = "t2.micro"
  tags = {
    Name = "PublicEC2${count.index}}"
  }
  provisioner "local-exec" {
    command = <<EOF
echo "Public EC2 ${count.index} ID is ${self.id}"
EOF
  }
}

There is no syntax like below to create resources.

[ for name in var.names:
 aws_s3_bucket {...} 
 aws_sns_topic {...}
]

For expression is basically for values, not for creating resources.

  • for Expressions

    A for expression creates a complex type value by transforming another complex type value.

To create multiple resources, as below in the document use for_each or count.

Share:
10,622

Related videos on Youtube

Dan
Author by

Dan

Updated on September 25, 2022

Comments

  • Dan
    Dan about 1 year

    I have looked at several bits of documentation as well as a udemy course on terraform and I do not understand how to do the thing that I want to do. I want to create a for loop and in it I want to create an S3 event notification, create an Sns topic that listens to that notification, create an Sqs queue and then subscribe the queue to the sns topic. It seems like for loops in terraform are not advanced enough to do this. Am I wrong, is there any documentation or examples that explain how to use for loops for this use case?

    Thanks in advance.