How to create a security group within a specified VPC?
TypeScriptSure, you can use the
aws.ec2.SecurityGroup
andaws.ec2.Vpc
resources in the Pulumi AWS package to create a security group within a specified VPC.In this program, we first create a VPC. Then, we create a security group within that VPC, and finally, we export the ID of the security group.
Here's the program to accomplish this:
import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; // Create a new VPC const vpc = new aws.ec2.Vpc("my-vpc", { cidrBlock: "10.0.0.0/16", }); // Create a new security group within the VPC const securityGroup = new aws.ec2.SecurityGroup("my-security-group", { vpcId: vpc.id, ingress: [ { protocol: "tcp", fromPort: 22, toPort: 22, cidrBlocks: ["0.0.0.0/0"] }, ], egress: [ { protocol: "-1", fromPort: 0, toPort: 0, cidrBlocks: ["0.0.0.0/0"] }, ], }); // Export the security group ID exports.sgId = securityGroup.id;
In this program, the
aws.ec2.Vpc
resource creates a new VPC with a CIDR block of"10.0.0.0/16"
. Theaws.ec2.SecurityGroup
resource creates a new security group in this VPC. ThevpcId
property is set tovpc.id
, referencing the ID of the VPC we created.The
ingress
property ofaws.ec2.SecurityGroup
defines the inbound rules for the security group. We allow all TCP traffic over port 22 (the standard port for SSH) from any IP address ("0.0.0.0/0"
).The
egress
property defines the outbound rules. Here, we are allowing all outbound traffic (protocol: "-1"
means all protocols) to any IP address.For more details, refer to the Pulumi API documentation for aws.ec2.Vpc and aws.ec2.SecurityGroup.