How Do I Configure an AWS VPC With 2 EC2 Instances That Can Connect to Each Other?
Introduction
In this guide, we will create an AWS Virtual Private Cloud (VPC) with two EC2 instances that can communicate with each other. This setup involves creating a VPC, subnets, security groups, and EC2 instances using Pulumi’s AWS SDK in TypeScript.
Step-by-Step Explanation
Step 1: Create a VPC
First, we create a VPC with a specified CIDR block.
Step 2: Create Subnets
Next, we create two subnets within the VPC. These subnets will host our EC2 instances.
Step 3: Create a Security Group
We then create a security group that allows traffic between the two EC2 instances.
Step 4: Launch EC2 Instances
Finally, we launch two EC2 instances within the subnets and associate them with the security group.
Conclusion
By following these steps, you will have a VPC with two EC2 instances that can communicate with each other. This setup is useful for creating isolated environments for your applications.
Full Code Example
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Step 1: Create a VPC
const vpc = new aws.ec2.Vpc("my-vpc", {
cidrBlock: "10.0.0.0/16",
});
// Step 2: Create Subnets
const subnet1 = new aws.ec2.Subnet("subnet1", {
vpcId: vpc.id,
cidrBlock: "10.0.1.0/24",
availabilityZone: "us-west-2a",
});
const subnet2 = new aws.ec2.Subnet("subnet2", {
vpcId: vpc.id,
cidrBlock: "10.0.2.0/24",
availabilityZone: "us-west-2b",
});
// Step 3: Create a Security Group
const securityGroup = new aws.ec2.SecurityGroup("securityGroup", {
vpcId: vpc.id,
ingress: [
{
protocol: "tcp",
fromPort: 0,
toPort: 65535,
cidrBlocks: ["10.0.0.0/16"],
},
],
egress: [
{
protocol: "-1",
fromPort: 0,
toPort: 0,
cidrBlocks: ["0.0.0.0/0"],
},
],
});
// Step 4: Launch EC2 Instances
const instance1 = new aws.ec2.Instance("instance1", {
instanceType: "t2.micro",
ami: "ami-0c55b159cbfafe1f0", // Amazon Linux 2 AMI
subnetId: subnet1.id,
vpcSecurityGroupIds: [securityGroup.id],
});
const instance2 = new aws.ec2.Instance("instance2", {
instanceType: "t2.micro",
ami: "ami-0c55b159cbfafe1f0", // Amazon Linux 2 AMI
subnetId: subnet2.id,
vpcSecurityGroupIds: [securityGroup.id],
});
export const vpcId = vpc.id;
export const subnet1Id = subnet1.id;
export const subnet2Id = subnet2.id;
export const securityGroupId = securityGroup.id;
export const instance1Id = instance1.id;
export const instance2Id = instance2.id;
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.