1. Answers
  2. Create an AWS EC2 Security Group Rule

How do I build an AWS EC2 security group rule?

When configuring a secure and well-organized cloud environment, defining security groups and their associated rules is crucial. These security groups act like virtual firewalls which control both inbound and outbound traffic for your EC2 instances. Below is an example of how you can create a Security Group and the corresponding rules for an EC2 instance.

First, we need to create a security group allowing HTTP and SSH access, Set rules for inbound traffic, and allow all outbound traffic.

Example: Creating an AWS EC2 Security Group and Security Group Rules

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

// Define a security group to allow HTTP and SSH access
const example = new aws.ec2.SecurityGroup("example", {
    name: "example-security-group",
    description: "Allow SSH and HTTP",
    vpcId: "vpc-123456",
    egress: [{
        fromPort: 0,
        toPort: 0,
        protocol: "-1",
        cidrBlocks: ["0.0.0.0/0"],
    }],
});
// Allow inbound HTTP traffic on port 80
const allowHttp = new aws.ec2.SecurityGroupRule("allow_http", {
    type: "ingress",
    fromPort: 80,
    toPort: 80,
    protocol: aws.ec2.ProtocolType.TCP,
    cidrBlocks: ["0.0.0.0/0"],
    securityGroupId: example.id,
});
// Allow inbound SSH traffic on port 22
const allowSsh = new aws.ec2.SecurityGroupRule("allow_ssh", {
    type: "ingress",
    fromPort: 22,
    toPort: 22,
    protocol: aws.ec2.ProtocolType.TCP,
    cidrBlocks: ["0.0.0.0/0"],
    securityGroupId: example.id,
});
export const securityGroupId = example.id;

Summary

In this example, we created a security group named example-security-group with an egress rule allowing all outbound traffic. Additionally, two ingress rules were created to allow HTTP traffic on port 80 and SSH traffic on port 22. The security group ID is then exported as an output.

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