Software Engineering

How to create an Internet Gateway and assign it to an EC2 in Terraform

To create an Internet gateway and assign it to an EC2 instance using Terraform, you can follow these steps:

Step 1: Set up your Terraform environment

  1. Install Terraform: Download and install Terraform from the official website ( based on your operating system.
  2. Configure AWS credentials: Set up your AWS access key and secret access key as environment variables or use an AWS profile configured on your system.

Step 2: Create a Terraform configuration file

Create a new file with a .tf extension (e.g., and add the following contents:

provider "aws" {
  region = "us-west-2"  # Replace with your desired region

resource "aws_internet_gateway" "example" {
  vpc_id =

resource "aws_vpc" "example" {
  cidr_block = ""  # Replace with your desired VPC CIDR block

resource "aws_subnet" "example" {
  vpc_id                  =
  cidr_block              = ""  # Replace with your desired subnet CIDR block
  availability_zone       = "us-west-2a"  # Replace with your desired availability zone

resource "aws_route_table" "example" {
  vpc_id =

  route {
    cidr_block = ""
    gateway_id =

resource "aws_instance" "example" {
  ami           = "ami-0123456789abcdef0"  # Replace with your desired AMI ID
  instance_type = "t2.micro"  # Replace with your desired instance type
  subnet_id     =

Make sure to replace the placeholder values (region, cidr_block, availability_zone, ami, etc.) with your desired values.

Step 3: Initialize and apply Terraform configuration

  1. Open a terminal or command prompt and navigate to the directory containing your Terraform configuration file.
  2. Run the following command to initialize Terraform and download the necessary provider plugins:
terraform init
  1. After the initialization is complete, run the following command to create the infrastructure:
terraform apply
  1. Review the changes that Terraform will make and confirm by typing yes when prompted.
  2. Terraform will now create the internet gateway, VPC, subnet, route table, and EC2 instance according to the configuration.

Once the terraform apply command completes, your infrastructure will be provisioned, and the EC2 instance will be associated with the internet gateway.

It’s important to have a basic understanding of networking and AWS concepts when working with Terraform to create network infrastructure. Also, ensure that you have appropriate permissions and a properly configured AWS account to create the required resources.