Pull Available AZs and assign subnets

I have a few things going on in my code that I would like to know more about how to use them, fix them, and better them.

Here are some things I need to achieve:

  1. I need to pull AZs before I create subnets, I do not want to define the AZs manually.

  2. Once AZs are queried, I need to assign subnets to a set number of AZs, so if I have 3 subnets I need to define for 3 tier app then I need to assign to 3 AZs and no more.

  3. I need to create public and private subnets, the code I have now seems to use the same exact subnets for each private and public subnets.

  4. I need to use /24 subnets, but would like to use odd numbers in the third octet for public and even ones for private.

    /* Public subnet /
    resource “aws_subnet” “public_subnet” {
    count = length(data.aws_availability_zones.available.names)
    cidr_block = cidrsubnet(aws_vpc.vpc.cidr_block, 4, count.index)
    availability_zone = data.aws_availability_zones.available.names[count.index]
    vpc_id = aws_vpc.vpc.id
    map_public_ip_on_launch = true
    #tags = {
    #Name = var.environment-element(var.availability_zones, count index)-private-subnet
    #Environment = var.environment
    #}
    }
    /
    Private subnet */
    resource “aws_subnet” “private_subnet” {
    count = length(data.aws_availability_zones.available.names)
    cidr_block = cidrsubnet(aws_vpc.vpc.cidr_block, 4, count.index)
    availability_zone = data.aws_availability_zones.available.names[count.index]
    vpc_id = aws_vpc.vpc.id
    map_public_ip_on_launch = false

I actually struggle to understand how to use the count function. I have yet to find documentation that will help me understand so any explanation would help.

I suggest starting with the articles on HashiCorp learn. You can use count and for_each on data, resource and module statement to get there. I think you will have a better result with for_each in your case.

If you need to deliver quickly or find more advanced HCL examples, you can look at modules from the registry. This one might be of interest: https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/latest

1 Like