Search code examples
amazon-web-servicesterraformterraform-provider-aws

Terraform: Get id associated to each subnet


I have a list of subnets (1 public and 2 private) and I want to get id associated to each subnet.

My code structure is :

-- Dev
  -- main.tf
  -- vars.tf
-- modules
  -- sn
    -- ressources.tf
    -- vars.tf

This is my main.tf

# Create Public Subnet
module "public-sn" {
  source            = "../modules/sn"
  vpc_id            = module.vpc.vpcId 
  sn_az             = [ "********-3a" ]
  sn_cidr           = [ "********.0/24" ]
  sn_tags           = [ "********-sn-a" ] 
  sn_id             = module.sn.snId
}

# Create Private Subnets
module "private-sn" {
  source            = "../modules/sn"
  vpc_id            = module.vpc.vpcId 
  sn_az             = [ "eu-west-3a", "eu-west-3b" ]
  sn_cidr           = [ "********.0/24", "********.0/24" ]
  sn_tags           = [ "********-sn-a", "********-sn-b" ] 
}

This is my ressources.tf in ../sn

resource "aws_subnet" "sn" {
  count                   = length(var.sn_cidr)
  vpc_id                  = var.vpc_id
  cidr_block              = var.sn_cidr[count.index]
  availability_zone       = var.sn_az  [count.index]
  tags                    = { Name = var.sn_tags[count.index] }
}

This is my output.tf in ../sn as of now is empty. Please, help to get subnets IDs under those conditions.

Thanks in advance.


Solution

  • If you want to get the list of the subnet ids, your output in ../modules/sn/output.tf should be:

    output "subnet_ids" {
      value = aws_subnet.sn[*].id
    }