Minimum viable code to provision EC2 instance? or "default VPC" problems

I’m trying to get more comfortable with TF. While trying to provision an EC2 instance in AWS, I get the following error.

I’ve pasted the code there, as well as the output. This does not make sense to me. There is only one VPC… the one that came with the account.

What is the bare minimum of code required to provision a working EC2 instance in AWS?

Hi @akulbe,

When EC2 first lanched – a long time ago now – Virtual Private Cloud (VPC) did not yet exist and instead EC2 instances had a fixed network configuration decided by the platform.

When introducing VPC, AWS also introduced the idea of a “default VPC” and, for backward compatible, made it valid to launch an EC2 instance without any network configuration and responded by automatically wiring the instance into the default VPC.

However, EC2 phased out that historical shim, now called “EC2-Classic”, and it’s no longer available for newly-created AWS accounts. Unless you are using an account that is old enough to still have the compatibility features enabled, you will need to define the network that your EC2 instance will belong to.

EC2 instances are not actually directly associated with VPCs. Instead, each network interface belongs to a subnet, and then each subnet belongs to a VPC.

The minimum configuration therefore assumes that you have both a VPC and a subnet already created, in which case you can specify the subnet_id argument for your aws_instance.

If you don’t already have a subnet, you would need to also declare one using aws_subnet. That subnet could be associated either with your existing VPC or with a new one declared using aws_vpc. If you intend for your EC2 instance to access the internet then you will need to also ensure your VPC has some kind of gateway that provides internet routing (Internet gateway or NAT gateway).

Another detail that isn’t immediately obvious is that each subnet belongs to one AWS availability zone, and so selecting a subnet also implicitly selects an availability zone. That isn’t super important if you are just experimenting, but I mention it just to try to complete the picture of how all these terms fit together.

Hey @apparentlymart! thank you for taking the time to reply.

I ended up getting this ironed out by deleting the existing VPC (and dependencies) from the console, and then using AWS CLI to create a new default VPC.

Then I couldn’t figure out why newly-provisioned EC2 instances weren’t accessible unless I went to the console and created a security group to allow SSH from my IPs.

Then someone else suggested to me that I should be defining the SG at provisioning time (in the TF code), and that problem would be solved.

This is why you shouldn’t compute when you’re exhausted, I think :joy: