main.tf 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. locals {
  2. name = "${var.layer}-${var.region}-vpc"
  3. }
  4. # On AWS the VPC is only an address space. A machine reaches the internet only
  5. # when a gateway, a route to it and an association with the subnet all exist,
  6. # so each is a resource here, not a default the module hopes for.
  7. resource "aws_vpc" "this" {
  8. cidr_block = var.ip_range
  9. # Both are the AWS defaults, written out so the plan shows the choice.
  10. # IPv6 stays off: the egress rules and the cost gate assume IPv4 only.
  11. assign_generated_ipv6_cidr_block = false
  12. enable_dns_support = true
  13. enable_dns_hostnames = false
  14. tags = { Name = local.name }
  15. }
  16. resource "aws_subnet" "public" {
  17. vpc_id = aws_vpc.this.id
  18. cidr_block = var.ip_range
  19. availability_zone = var.availability_zone
  20. # Off on purpose: a machine asks for its public address itself
  21. # (associate_public_ip_address in the connector module), so no other machine
  22. # ever gets one by accident, and the cost gate can see every address.
  23. map_public_ip_on_launch = false
  24. tags = { Name = "${var.layer}-${var.region}-public" }
  25. }
  26. # Free. This is what makes a subnet public rather than private.
  27. resource "aws_internet_gateway" "this" {
  28. vpc_id = aws_vpc.this.id
  29. tags = { Name = "${var.layer}-${var.region}-igw" }
  30. }
  31. # An explicit route table instead of editing the VPC's main one: the route to
  32. # the internet is visible here and attached to exactly one subnet.
  33. resource "aws_route_table" "public" {
  34. vpc_id = aws_vpc.this.id
  35. tags = { Name = "${var.layer}-${var.region}-public" }
  36. }
  37. resource "aws_route" "internet" {
  38. route_table_id = aws_route_table.public.id
  39. destination_cidr_block = "0.0.0.0/0"
  40. gateway_id = aws_internet_gateway.this.id
  41. }
  42. resource "aws_route_table_association" "public" {
  43. subnet_id = aws_subnet.public.id
  44. route_table_id = aws_route_table.public.id
  45. }
  46. # Every VPC comes with a default security group that allows all traffic between
  47. # its own members and all outbound. Declaring it with no rules empties it, so
  48. # nothing can rely on it by accident (the connector module never uses it).
  49. # The VPC's default network ACL is left as AWS made it (allow all, both ways):
  50. # a custom ACL is stateless and needs return-path ephemeral-port rules, and
  51. # the security group is this project's filter.
  52. resource "aws_default_security_group" "this" {
  53. vpc_id = aws_vpc.this.id
  54. tags = { Name = "${var.layer}-${var.region}-default-unused" }
  55. }