How would I reference the subnet created in the vpc module in the ec2 module?
provider "aws" {
region = "us-east-2"
}
module "myvpc" {
source = "terraform-aws-modules/vpc/aws"
name = "my-vpc"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b", "us-east-1c"]
private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
assign_generated_ipv6_cidr_block = true
enable_nat_gateway = true
single_nat_gateway = true
enable_s3_endpoint = true
enable_dynamodb_endpoint = true
public_subnet_tags = {
Name = "overridden-name-public"
}
tags = {
Owner = "user"
Environment = "dev"
Name = "terraformtestvpc"
}
vpc_tags = {
Name = "vpc-name"
}
}
module "ssh_access_sg" {
source = "terraform-aws-modules/security-group/aws//modules/ssh"
name = "ssh-access"
description = "Security group for ssh access"
vpc_id = "${module.myvpc.vpc_id}"
ingress_cidr_blocks = ["0.0.0.0/0"]
}
data "aws_ami" "amazon_linux" {
most_recent = true
filter {
name = "name"
values = [
"amzn-ami-hvm-*-x86_64-gp2",
]
}
filter {
name = "owner-alias"
values = [
"amazon",
]
}
}
module "ec2" {
source = "terraform-aws-modules/ec2-instance/aws"
instance_count = 2
name = "example-normal"
ami = "${data.aws_ami.amazon_linux.id}"
instance_type = "t2.medium"
subnet_id = "${element(module.myvpc.private_subnets, 0)}"
vpc_security_group_ids = ["${module.ssh_access_sg.this_security_group_id}"]
associate_public_ip_address = true
}
To reference a value created in a module you have to
output
the value with an according statement.Then you can access the value with
${module.NAME.OUTPUT}
.For details see: https://www.terraform.io/intro/getting-started/modules.html
Section
Module Outputs
and: https://www.terraform.io/intro/getting-started/outputs.htmlRefer to the VPC as module.vpc.id
For Public Subnets: refer to a subnet as module.public.subnets[0]
Where [0] is the first subnet and [1] is the second subnet and so on ...
For Private Subnets" refer to a subnet as module.private.subnets[0]
and the same idea, each subnet created will be in a list as either [0],[1],[2]...
Find below a working Instance.tf based on the terraform a module VPC.tf:
You can access the subnet list via it's index. module.myvpc.public_subnets[*] or module.myvpc.private_subnets[0] (for the first subnet)