How do I configure an AWS EC2 Security Group Rule?
In this example, you’ll learn how to configure a security group rule for an AWS EC2 instance. A security group acts as a virtual firewall for your instance to control incoming and outgoing traffic. By defining security group rules, you can specify which traffic is allowed or denied to reach the instance.
Here’s what you’ll be going to accomplish:
- Create a new security group.
- Define inbound and outbound rules for this security group to control traffic.
- Export the security group ID and the rules for verification.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Defines the security group
const exampleSg = new aws.ec2.SecurityGroup("example_sg", {
name: "example-sg",
description: "Example security group",
vpcId: "vpc-123456",
tags: {
Name: "example-sg",
},
});
// Defines an inbound security group rule
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: exampleSg.id,
});
// Defines another inbound security group rule
const allowHttps = new aws.ec2.SecurityGroupRule("allow_https", {
type: "ingress",
fromPort: 443,
toPort: 443,
protocol: aws.ec2.ProtocolType.TCP,
cidrBlocks: ["0.0.0.0/0"],
securityGroupId: exampleSg.id,
});
export const securityGroupId = exampleSg.id;
export const httpRule = allowHttp.id;
export const httpsRule = allowHttps.id;
In this program, we first specify the AWS provider and the region where the resources will be created. Next, we create a security group resource called example_sg
in a specified VPC. Within this security group, we define two inbound rules to allow HTTP and HTTPS traffic from any IP address. Finally, we export the security group’s ID and the IDs of the rules to verify and make use of them later if needed.
We’ve now configured an AWS EC2 security group with specific rules to allow inbound HTTP and HTTPS traffic.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.