1. Answers
  2. Allowing outbound traffic to specific ports from EC2 instances

How do I allow outbound traffic to specific ports from EC2 instances?

In this guide, we will configure an AWS EC2 instance to allow outbound traffic to specific ports using Pulumi. We will create a security group with an egress rule that allows traffic on specified ports and then associate this security group with an EC2 instance.

Key Points:

  • Create a security group with specific egress rules.
  • Allow outbound traffic on specified ports.
  • Associate the security group with an EC2 instance.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// Define the VPC
const vpc = new aws.ec2.Vpc("myVpc", {
    cidrBlock: "10.0.0.0/16",
});

// Define a subnet
const subnet = new aws.ec2.Subnet("mySubnet", {
    vpcId: vpc.id,
    cidrBlock: "10.0.1.0/24",
    availabilityZone: "us-west-2a",
});

// Create a security group
const securityGroup = new aws.ec2.SecurityGroup("mySecurityGroup", {
    vpcId: vpc.id,
    egress: [
        {
            protocol: "tcp",
            fromPort: 80,
            toPort: 80,
            cidrBlocks: ["0.0.0.0/0"],
        },
        {
            protocol: "tcp",
            fromPort: 443,
            toPort: 443,
            cidrBlocks: ["0.0.0.0/0"],
        },
        // Add more rules as needed
    ],
});

// Define an EC2 instance
const instance = new aws.ec2.Instance("myInstance", {
    ami: "ami-0c55b159cbfafe1f0", // Example AMI ID for Amazon Linux 2
    instanceType: "t2.micro",
    subnetId: subnet.id,
    vpcSecurityGroupIds: [securityGroup.id],
    tags: {
        Name: "myInstance",
    },
});

// Export the instance ID and public IP
export const instanceId = instance.id;
export const publicIp = instance.publicIp;

Summary:

In this guide, we created a security group with egress rules that allow outbound traffic on specific ports. We then associated this security group with an EC2 instance, ensuring that the instance can communicate over the specified ports. This setup enhances the security of your infrastructure by controlling the outbound traffic from your EC2 instances.

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