Terraform count:
- count is meta arugment to create multiple resources with single block
basic count
## variables
variable "vpc_name" {
type = string
default = "mynetwork"
description = "name of the vpc"
sensitive = true
}
variable "subnet_cidrs" {
type = list(string)
default = [ "10.2.1.0/24", "10.2.2.0/24", "10.2.3.0/24"]
}
variable "az-range" {
type = list(string)
default = [ "us-east-1a", "us-east-1b", "us-east-1c"]
}
################################ resources #########################
resource "aws_vpc" "qt-demo-vpc" {
cidr_block = "10.2.0.0/16"
tags = {
Name = var.vpc_name
env = "dev"
}
}
resource "aws_subnet" "mysubnets" {
count = length(var.subnet_cidrs)
vpc_id = aws_vpc.qt-demo-vpc.id
cidr_block = var.subnet_cidrs[count.index]
availability_zone = var.az-range[count.index]
tags = {
Name = "app1"
}
}
count with if conditions
Ex: create_instance is true create 1 ec2 instance
Task
- create vpc & 4 public subnets and 4 pravite subnets
- myvpc – name vpc 10.5.0.0/16
- public subnets – pub-sub1, pub-sub2, pub-sub3, pub-sub4
- pravite subnets – pvsubnet1, pvsubnet2, pvsubnet3, pvsubnet4
- create 2 route table pubroute & pvroute
- IGW
- NAT
- create route in pub route table attach IGW
- create route in pv route table attach NAT
- ass subnets pv and pub route tables
