Guest User

Untitled

a guest
Jul 20th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. # network.tf
  2.  
  3. # Fetch AZs in the current region
  4. data "aws_availability_zones" "available" {}
  5.  
  6. resource "aws_vpc" "main" {
  7. cidr_block = "172.17.0.0/16"
  8. }
  9.  
  10. # Create var.az_count private subnets, each in a different AZ
  11. resource "aws_subnet" "private" {
  12. count = "${var.az_count}"
  13. cidr_block = "${cidrsubnet(aws_vpc.main.cidr_block, 8, count.index)}"
  14. availability_zone = "${data.aws_availability_zones.available.names[count.index]}"
  15. vpc_id = "${aws_vpc.main.id}"
  16. }
  17.  
  18. # Create var.az_count public subnets, each in a different AZ
  19. resource "aws_subnet" "public" {
  20. count = "${var.az_count}"
  21. cidr_block = "${cidrsubnet(aws_vpc.main.cidr_block, 8, var.az_count + count.index)}"
  22. availability_zone = "${data.aws_availability_zones.available.names[count.index]}"
  23. vpc_id = "${aws_vpc.main.id}"
  24. map_public_ip_on_launch = true
  25. }
  26.  
  27. # IGW for the public subnet
  28. resource "aws_internet_gateway" "gw" {
  29. vpc_id = "${aws_vpc.main.id}"
  30. }
  31.  
  32. # Route the public subnet trafic through the IGW
  33. resource "aws_route" "internet_access" {
  34. route_table_id = "${aws_vpc.main.main_route_table_id}"
  35. destination_cidr_block = "0.0.0.0/0"
  36. gateway_id = "${aws_internet_gateway.gw.id}"
  37. }
  38.  
  39. # Create a NAT gateway with an EIP for each private subnet to get internet connectivity
  40. resource "aws_eip" "gw" {
  41. count = "${var.az_count}"
  42. vpc = true
  43. depends_on = ["aws_internet_gateway.gw"]
  44. }
  45.  
  46. resource "aws_nat_gateway" "gw" {
  47. count = "${var.az_count}"
  48. subnet_id = "${element(aws_subnet.public.*.id, count.index)}"
  49. allocation_id = "${element(aws_eip.gw.*.id, count.index)}"
  50. }
  51.  
  52. # Create a new route table for the private subnets, make it route non-local traffic through the NAT gateway to the internet
  53. resource "aws_route_table" "private" {
  54. count = "${var.az_count}"
  55. vpc_id = "${aws_vpc.main.id}"
  56.  
  57. route {
  58. cidr_block = "0.0.0.0/0"
  59. nat_gateway_id = "${element(aws_nat_gateway.gw.*.id, count.index)}"
  60. }
  61. }
  62.  
  63. # Explicitly associate the newly created route tables to the private subnets (so they don't default to the main route table)
  64. resource "aws_route_table_association" "private" {
  65. count = "${var.az_count}"
  66. subnet_id = "${element(aws_subnet.private.*.id, count.index)}"
  67. route_table_id = "${element(aws_route_table.private.*.id, count.index)}"
  68. }
Add Comment
Please, Sign In to add comment