AWS with Terraform Tutorial: AWS Internet Gateway (6)

· Updated · 10 min read · Terraform & OpenTofu Tutorials

How to Create, and Manage AWS Internet Gateway with Terraform #

How to configure and use the Terraform aws_internet_gateway resource block to create and manage AWS Internet Gateway inside a VPC to enable Internet access to and from instances.

Welcome to our tutorial series where we dive into cloud infrastructure deployment using Terraform or OpenTofu on AWS. In this series, the fundamentals are shown, guiding you through the process of minimizing resource usage and simplifying the deployment complexities associated with cloud infrastructure.

This comprehensive OpenTofu and Terraform tutorial guides you step-by-step through creating infrastructure in AWS using Terraform.

Terraform is an Infrastructure as Code (IaC) tool used to provision and manage infrastructure. It helps define and deploy resources across various cloud providers using code, making it easier to maintain and scale infrastructure.Terraform is an Infrastructure as Code (IaC) tool used to provision and manage infrastructure. It helps define and deploy resources across various cloud providers using code, making it easier to maintain and scale infrastructure.
Terraform
Basics
Terraform...
AWS is the world’s leading cloud platform, it is used by a wide range of organizations, from startups to large enterprises, to power their online businesses. AWS offers a wide range of services, including computing, storage, database, networking, analytics, machine learning, and artificial intelligence.AWS is the world’s leading cloud platform, it is used by a wide range of organizations, from startups to large enterprises, to power their online businesses. AWS offers a wide range of services, including computing, storage, database, networking, analytics, machine learning, and artificial intelligence.
AWS
Basics
AWS...
The Terraform official AWS provider acts as an abstraction layer that lets Terraform configurations written in HCL define AWS services and infrastructure using code (IaC). Internally Terraform and the AWS provider handle authentication, and make the necessary AWS API calls to query, create, modify, and destroy the resources.The Terraform official AWS provider acts as an abstraction layer that lets Terraform configurations written in HCL define AWS services and infrastructure using code (IaC). Internally Terraform and the AWS provider handle authentication, and make the necessary AWS API calls to query, create, modify, and destroy the resources.
Terraform
AWS Provider
Terraform...
How to Create, and Manage AWS VPCs with TerraformHow to Create, and Manage AWS VPCs with Terraform
AWS VPC
AWS VPC
How to configure and use the Terraform aws_subnet resource block to create and manage AWS Subnets inside a VPC.How to configure and use the Terraform aws_subnet resource block to create and manage AWS Subnets inside a VPC.
AWS Subnets
AWS Subnets
How to configure and use the Terraform aws_internet_gateway resource block to create and manage AWS Internet Gateway inside a VPC to enable Internet access to and from instances. How to configure and use the Terraform aws_internet_gateway resource block to create and manage AWS Internet Gateway inside a VPC to enable Internet access to and from instances.
AWS Internet
Gateway
AWS Internet...
How to configure and use the Terraform aws_nat_gateway and aws_eip resource blocks to create and manage AWS NAT Gateway and its corresponding Public IPs inside each availability zone to enable Internet access from instances in private subnets.How to configure and use the Terraform aws_nat_gateway and aws_eip resource blocks to create and manage AWS NAT Gateway and its corresponding Public IPs inside each availability zone to enable Internet access from instances in private subnets.
AWS NAT
Gateway
AWS NAT...
How to configure and use the Terraform aws_route_table, aws_route, and aws_main_route_table_association resource blocks to create and manage AWS Routing Tables.How to configure and use the Terraform aws_route_table, aws_route, and aws_main_route_table_association resource blocks to create and manage AWS Routing Tables.
AWS Routing
Tables
AWS Routing...
How to configure and use the Terraform aws_security_group and aws_security_group_rule resource blocks to create and manage AWS Security Groups and secure the infrastructure.How to configure and use the Terraform aws_security_group and aws_security_group_rule resource blocks to create and manage AWS Security Groups and secure the infrastructure.
AWS Security
Groups
AWS Security...
How to configure and use the Terraform aws_key_pair resource block to create and manage AWS Key Pairs for performing SSH Public Key Authentication into EC2 instances.How to configure and use the Terraform aws_key_pair resource block to create and manage AWS Key Pairs for performing SSH Public Key Authentication into EC2 instances.
AWS Key
Pairs
AWS Key...
How to configure and use the Terraform aws_ami data source block to find and use AWS AMIs as templates (root volume snapshot with operating system and applications) for EC2 instances.How to configure and use the Terraform aws_ami data source block to find and use AWS AMIs as templates (root volume snapshot with operating system and applications) for EC2 instances.
AWS AMIs
AWS AMIs
Using the Terraform aws_instance resource block to configure, launch, and secure EC2 instances.Using the Terraform aws_instance resource block to configure, launch, and secure EC2 instances.
AWS EC2
Instances
AWS EC2...
AWS RDS
AWS RDS
Using the Terraform aws_route53_delegation_set, aws_route53_zone, and aws_route53_record resource blocks to configure DNS in AWS. Using the Terraform aws_route53_delegation_set, aws_route53_zone, and aws_route53_record resource blocks to configure DNS in AWS.
AWS Route 53
(DNS)
AWS Route 53...
Amazon EC2 Auto Scaling groups keep the right number of instances running, replace failed ones and scale with the load.Amazon EC2 Auto Scaling groups keep the right number of instances running, replace failed ones and scale with the load.
AWS Auto
Scaling
AWS Auto...
Elastic Load Balancing distributes the traffic between healthy instances. The tutorial creates an Application Load Balancer with HTTPS.Elastic Load Balancing distributes the traffic between healthy instances. The tutorial creates an Application Load Balancer with HTTPS.
AWS Load
Balancers
AWS Load...
This tutorial shows how to create infrastructure in AWS using Terraform and configure the operating system and applications using Ansible.This tutorial shows how to create infrastructure in AWS using Terraform and configure the operating system and applications using Ansible.
Terraform,
AWS & Ansible
Terraform,...
Modules package resources behind variables and outputs so they can be reused. The tutorial refactors the network into a module.Modules package resources behind variables and outputs so they can be reused. The tutorial refactors the network into a module.
Terraform
Modules
Terraform...
A backend stores the Terraform state. The tutorial uses an encrypted, versioned S3 bucket with state locking.A backend stores the Terraform state. The tutorial uses an encrypted, versioned S3 bucket with state locking.
Terraform
Backends
Terraform...
fmt, validate, TFLint, Trivy, Checkov, terraform-docs, Infracost and pre-commit: check the code before it reaches AWS.fmt, validate, TFLint, Trivy, Checkov, terraform-docs, Infracost and pre-commit: check the code before it reaches AWS.
Terraform
Tools
Terraform...
Run checks, plans and approved applies automatically with GitHub Actions and OIDC, without access keys.Run checks, plans and approved applies automatically with GitHub Actions and OIDC, without access keys.
Terraform
CI/CD
Terraform...
Select a tutorial section 
Select a tutorial sectio...

Infrastructure as Code (IaC) helps maintain consistency, enables version control, enhances collaboration among teams, allows for easier replication of environments, streamlines the deployment and management of infrastructure boosting efficiency, and reducing errors in managing complex systems.

Prerequisites #

Read the previous sections of the tutorial, listed in the series index at the end of this page.

AWS Internet Gateway #

AWS Internet Gateway

An AWS Internet Gateway is a component that facilitates communication between instances that have a public IP address within an Amazon Virtual Private Cloud (VPC) and the Internet. It acts as a gateway for internet-bound traffic, allowing resources within a VPC, like EC2 instances, to access the Internet and receive responses from Internet resources.

AWS Instances that have been assigned a public IP are only aware of their private IP and require the Internet Gateway to do one-to-one NAT in case of IPV4 IPs. For IPV6, NAT is not needed but the Internet Gateway is still required.

The Internet Gateway is assigned at the VPC level and AWS takes care of providing redundancy across availability zones.

Region
Region
Availability Zone
Availability Zone
VPC
VPC
ditlw-vpc
ditlw-vpc
Public subnet
Public subnet
us-east-1a
us-east-1a
Availability Zone
Availability Zone
us-east-1b
us-east-1b
Public subnet
Public subnet
Public IPs
Public IPs
Private subnet
Private subnet
No Public IPs
No Public IPs
ditwl-sn-zb-pro-pri-06
ditwl-sn-zb-pro-pri-06
Public IPs
Public IPs
ditwl-sn-za-pro-pub-00
ditwl-sn-za-pro-pub-00
ditwl-sn-zb-pro-pub-04
ditwl-sn-zb-pro-pub-04
Private subnet
Private subnet
No Public IPs
No Public IPs
us-east-1
us-east-1
ditlw-ig
ditlw-ig
ditwl-sn-za-pro-pri-02
ditwl-sn-za-pro-pri-02
Internet
Internet
Users & Servers
Users & Servers
Text is not SVG - cannot display

Terraform AWS Configuration Plan Definition #

Previous sections of this AWS with Terraform guide have covered basic information about Terraform and AWS and have configured and used the AWS Terraform provider to create a VPC and four subnets.

It is time to create the Internet Gateway. Keep adding Terraform blocks to the terraform-aws-tutorial.tf created in previous sections.

How to Create an AWS Internet Gateway with Terraform #

Internet Gateway definition using Terraform, add the following block to the file terraform-aws-tutorial.tf:

# Internet Gateway
resource "aws_internet_gateway" "ditwl-ig" {
  vpc_id = aws_vpc.ditlw-vpc.id
  tags = {
    Name = "ditwl-ig"
  }
}

The Terraform aws_internet_gateway resource block creates an Internet Gateway, named ditwl-ig, inside the VPC created in the previous tutorial, using its Terraform reference aws_vpc.ditlw-vpc.id.

The aws_internet_gateway will be used as a target for the traffic leaving the VPC private network in the routing table for the Subnets.

Run the Terraform Plan #

Open a command line shell in the directory where the file terraform-aws-tutorial.tf is located, and run the Terraform or OpenTofu plan and apply commands.

Plan using OpenTofu #

Run tofu plan to generate and review the execution plan. Check each line and value to make sure that it corresponds to the desired change.

The VPC and the Subnets were already created in the previous Terraform execution so now only the new Internet Gateway will be created. Terraform or OpenTofu show Refreshing state for each of the existing elements and the planned actions for the changes.

$ tofu plan
aws_vpc.ditlw-vpc: Refreshing state... [id=vpc-0bed1f6c715e9a909]
aws_subnet.ditwl-sn-za-pro-pri-02: Refreshing state... [id=subnet-096bf79e4bab2e1c4]
aws_subnet.ditwl-sn-zb-pro-pub-04: Refreshing state... [id=subnet-0d34cee7300e9fa45]
aws_subnet.ditwl-sn-za-pro-pub-00: Refreshing state... [id=subnet-07753bf540026684d]
aws_subnet.ditwl-sn-zb-pro-pri-06: Refreshing state... [id=subnet-0f5662bd40a070e55]

OpenTofu used the selected providers to generate the following execution plan. Resource actions are indicated with the following
symbols:
  + create

OpenTofu will perform the following actions:

  # aws_internet_gateway.ditwl-ig will be created
  + resource "aws_internet_gateway" "ditwl-ig" {
      + arn      = (known after apply)
      + id       = (known after apply)
      + owner_id = (known after apply)
      + tags     = {
          + "Name" = "ditwl-ig"
        }
      + tags_all = {
          + "Name"        = "ditwl-ig"
          + "cost_center" = "marketing-department"
          + "environment" = "pro"
          + "owner"       = "IT Wonder Lab"
        }
      + vpc_id   = "vpc-0bed1f6c715e9a909"
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Apply the changes using OpenTofu #

Run tofu apply to generate and apply the execution plan. OpenTofu will generate a new plan and ask for confirmation before applying the changes. Review again the changes and answer yes or no to apply the changes in AWS.

$ tofu apply
aws_vpc.ditlw-vpc: Refreshing state... [id=vpc-0bed1f6c715e9a909]
aws_subnet.ditwl-sn-zb-pro-pub-04: Refreshing state... [id=subnet-0d34cee7300e9fa45]
aws_subnet.ditwl-sn-zb-pro-pri-06: Refreshing state... [id=subnet-0f5662bd40a070e55]
aws_subnet.ditwl-sn-za-pro-pub-00: Refreshing state... [id=subnet-07753bf540026684d]
aws_subnet.ditwl-sn-za-pro-pri-02: Refreshing state... [id=subnet-096bf79e4bab2e1c4]

OpenTofu used the selected providers to generate the following execution plan. Resource actions are indicated with the following
symbols:
  + create

OpenTofu will perform the following actions:

  # aws_internet_gateway.ditwl-ig will be created
  + resource "aws_internet_gateway" "ditwl-ig" {
      + arn      = (known after apply)
      + id       = (known after apply)
      + owner_id = (known after apply)
      + tags     = {
          + "Name" = "ditwl-ig"
        }
      + tags_all = {
          + "Name"        = "ditwl-ig"
          + "cost_center" = "marketing-department"
          + "environment" = "pro"
          + "owner"       = "IT Wonder Lab"
        }
      + vpc_id   = "vpc-0bed1f6c715e9a909"
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  OpenTofu will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_internet_gateway.ditwl-ig: Creating...
aws_internet_gateway.ditwl-ig: Creation complete after 3s [id=igw-033b206763b59357e]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Review the result, it should be 1 (resource) added, 0 changed, 0 destroyed.

You can now run tofu plan or tofu apply again to check that OpenTofu has not found any new changes to apply.

Check using the AWS web Console that the Internet Gateway has been created:

If you don’t see the Internet gateway check on the right top corner that the Region is N. Virginia that corresponds to us-east-1.

Common Questions About AWS Internet Gateways #

How many Internet Gateways should be created in each VPC? #

One, having one internet gateway per Virtual Private Cloud (VPC) is a common and effective setup. This design simplifies network management and ensures a clear point of entry and exit for Internet traffic.

What are the Alternatives to the Internet Gateway for EC2 instances? #

The internet gateway is only needed to allow access in these scenarios:

  • Public Instances that require access from the instance to the Internet
  • Private Instances that require access from the instance to the Internet (an additional NAT Gateway is needed).
  • Public Instances that require to be accessed from the Internet directly (without using an Application Load Balancer).

Other network topology options are available including hybrid cloud setups using VPNs or hub-and-spoke architecture for Internet access.

Should Servers be directly exposed to the Internet using an Internet Gateway? #

Directly exposing servers, such as EC2 instances, to the internet poses several security risks:

  • Security Vulnerabilities: Exposed servers may have vulnerabilities that could be exploited by attackers. Without proper security measures, malicious actors can target these vulnerabilities to gain unauthorized access, potentially leading to data breaches or service disruptions.
  • Increased Attack Surface: Direct exposure expands the attack surface of your servers. Any service, application, or open port becomes a potential entry point for attackers. This increases the likelihood of successful attacks and compromises the overall security posture.
  • Brute Force Attacks: Exposed servers are susceptible to brute force attacks where attackers repeatedly attempt to guess usernames and passwords. If strong authentication measures are not in place, this can lead to unauthorized access.
  • Lack of Network Segmentation: Directly exposing servers may bypass network segmentation measures. Proper network segmentation is crucial for containing potential breaches and limiting the lateral movement of attackers within the network.
  • Unprotected Services: Services running on servers may not be properly protected or secured. Exposing these services directly to the internet increases the risk of exploitation, especially if default configurations or weak security practices are in place.
  • Limited Visibility and Control: Without a proper network architecture, monitoring, and control become challenging. Directly exposed servers may lack visibility into network traffic, making it harder to detect and respond to suspicious activities.
  • Denial-of-Service (DoS) Attacks: Exposed servers are more vulnerable to DoS attacks, where attackers flood the server with traffic to overwhelm and disrupt its normal operation. This can lead to service downtime and impact business operations.

Alternatives for exposing servers to the Internet, like an AWS Load Balancer, are used in the next sections. See also AWS Internet Gateway and AWS Route Tables.

Next Steps #

Continue with AWS NAT Gateway, or see the full series index.

#AWS #AWS Internet Gateway #AWS Terraform Tutorial #AWS VPC #OpenTofu #Terraform