2
votes

I am using the tf_aws_vpc and tf_aws_ec2 Terraform community modules butnI am struggling to get the subnet_id which I should use to create an EC2 instance within an AWS VPC.

In the tf_aws_ec2 module docs they say to define it in a variable but I can't get it from a variable because I don't know its id until I have created the subnet.

I am trying to use Terraform modules. I know how to do it when not using Terraform modules.

How am I supposed to create an EC2 instance in a VPC?

1
Are you using both of those modules in the same directory? So do you apply Terraform a single time to create both or are you applying Terraform to multiple directories?ydaetskcoR
I am downloading it from github.. Using their modules in my main.tfWeslley Camilo

1 Answers

1
votes

I'm going to preface this by saying I'm not too convinced on what those modules are really offering over simply using the resources yourself as they don't really make any useful decisions for you and so I'd recommend not using them at all.

However, if you do want to use them and you're using them at the same "level" (meaning that a single terraform apply creates both the VPC and the instances) then you can simply use the module outputs and pass them to the EC2 instance.

Something like this should work:

module "vpc" {
  source = "github.com/terraform-community-modules/tf_aws_vpc"

  name = "my-vpc"

  cidr = "10.0.0.0/16"
  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"]

  enable_nat_gateway = "true"

  azs      = ["us-west-2a", "us-west-2b", "us-west-2c"]

  tags {
    "Terraform" = "true"
    "Environment" = "${var.environment}"
  }
}

module "ec2_instance" {
  source = "github.com/terraform-community-modules/tf_aws_ec2_instance"
  instance_type = "${var.instance_type}"
  instance_name = "${var.instance_name}"
  ami_id = "${var.ami_id}"
  aws_access_key = "${var.aws_access_key}"
  aws_secret_key = "${var.aws_secret_key}"
  aws_region = "${var.aws_region}"
  subnet_id = "${element(module.vpc.private_subnets, 0)}"
  number_of_instances = "${var.number_of_instances}"
  user_data = "${var.user_data}"
}

This uses the private_subnets output from the VPC module which returns a list of all of the private subnet ids in the VPC and then uses element to select the first one. If the instance module took a list of subnet ids to put instances in (round robining through them all to spread instances across AZs) then you could drop the element function.

If you had your Terraform in different directories (so you apply once for your VPC and again in another directory to create your EC2 instance) you'd need to access the output of the VPC using the remote_state data source.