1. Answers
  2. Restricting inbound traffic to EC2 instances

How do I restrict inbound traffic to EC2 instances?

In this guide, we will create an AWS EC2 instance and restrict its inbound traffic using a security group. We will define a security group that only allows inbound traffic on port 22 (SSH) from a specific IP address. This setup enhances the security of your EC2 instance by limiting access to the instance.

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// Define a security group
const securityGroup = new aws.ec2.SecurityGroup("web-secgrp", {
    description: "Allow SSH inbound traffic",
    ingress: [
        {
            protocol: "tcp",
            fromPort: 22,
            toPort: 22,
            cidrBlocks: ["203.0.113.0/24"], // Replace with your IP address range
        },
    ],
    egress: [
        {
            protocol: "-1",
            fromPort: 0,
            toPort: 0,
            cidrBlocks: ["0.0.0.0/0"],
        },
    ],
});

// Create an EC2 instance
const server = new aws.ec2.Instance("web-server", {
    instanceType: "t2.micro", // Choose the instance type
    ami: "ami-0c55b159cbfafe1f0", // Replace with a valid AMI ID
    securityGroups: [securityGroup.name], // Attach the security group
    keyName: "my-key-pair", // Replace with your key pair name
    tags: {
        Name: "web-server",
    },
});

// Export the instance's public IP address
export const publicIp = server.publicIp;
export const publicDns = server.publicDns;

Key Points:

  • We created a security group that allows inbound SSH traffic only from a specified IP address range.
  • An EC2 instance was created and associated with the security group.
  • The instance type, AMI ID, and key pair name were specified for the EC2 instance.
  • The public IP and DNS of the EC2 instance were exported for easy access.

Summary:

In this guide, we successfully created an AWS EC2 instance and restricted its inbound traffic using a security group. This setup ensures that only specified IP addresses can access the instance via SSH, enhancing the security of the instance.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up