1. Answers
  2. Setting up an AWS EC2 Security Group

How do I configure an AWS EC2 Security Group?

In this example, we’ll set up an AWS EC2 Security Group which controls the inbound and outbound traffic to your EC2 instances. Security groups act as virtual firewalls for your instances to control the traffic. We can define rules within these security groups that specify the allowed traffic.

Here’s an example where we create a security group that allows HTTP and SSH access from the outside world (0.0.0.0/0) and allows all outbound traffic.

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

const webSg = new aws.ec2.SecurityGroup("web_sg", {
    name: "web_sg",
    description: "Security group for web servers",
    vpcId: "vpc-12345678",
    ingress: [
        {
            description: "Allow HTTP traffic",
            fromPort: 80,
            toPort: 80,
            protocol: "tcp",
            cidrBlocks: ["0.0.0.0/0"],
        },
        {
            description: "Allow SSH traffic",
            fromPort: 22,
            toPort: 22,
            protocol: "tcp",
            cidrBlocks: ["0.0.0.0/0"],
        },
    ],
    egress: [{
        description: "Allow all outbound traffic",
        fromPort: 0,
        toPort: 0,
        protocol: "-1",
        cidrBlocks: ["0.0.0.0/0"],
    }],
    tags: {
        Name: "web_sg",
    },
});
export const securityGroupId = webSg.id;

Summary

In this setup, the aws_security_group resource is used to create a new security group named “web_sg” inside the specified VPC. We define two ingress rules to allow HTTP (port 80) and SSH (port 22) traffic from any IP address. An egress rule is configured to allow all outbound traffic. Finally, we output the security group ID for reference.

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