Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CDK EC2 Example
package com.myorg;
import software.amazon.awscdk.*;
import software.amazon.awscdk.services.ec2.*;
import java.util.Collections;
public class VpnStack extends Stack {
public VpnStack(final App parent, final String name, final StackProps props) {
super(parent, name, props);
CfnSecurityGroup sg = createSecurityGroup();
ParameterProps amiProps = new ParameterProps.Builder()
.withType("AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>")
.withDefault("/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2")
.build();
Parameter latestAmi = new Parameter(this, "LatestAmiId", amiProps);
CfnInstanceProps instanceProps = CfnInstanceProps.builder()
.withInstanceType("t2.small")
.withImageId(latestAmi.getRef())
.withKeyName("VPN")
.withTags(Collections.singletonList(new Tag.Builder().withKey("Name").withValue("My VPN Instance").build()))
.withSecurityGroupIds(Collections.singletonList(sg.getSecurityGroupId()))
// default VPN
// any subnet will do
.build();
CfnInstance instance = new CfnInstance(this, "MyVPN", instanceProps);
new Output(this, "PublicIPAddress", OutputProps.builder()
.withValue(instance.getInstancePublicIp())
.withDescription("VPN Public IP Address")
.build());
}
private CfnSecurityGroup createSecurityGroup() {
CfnSecurityGroupProps sgProps = CfnSecurityGroupProps.builder()
.withGroupDescription("Security Group for my VPN instance.")
.build();
CfnSecurityGroup sg = new CfnSecurityGroup(this, "VPNSecurityGroup", sgProps);
CfnSecurityGroupIngressProps sgIngressProps = CfnSecurityGroupIngressProps.builder()
.withToPort(22)
.withFromPort(22)
.withCidrIp("0.0.0.0/0")
.withIpProtocol("tcp")
.withDescription("Allows everyone access on port 22!")
.withGroupId(sg.getSecurityGroupId())
.build();
new CfnSecurityGroupIngress(this, "SgIngress", sgIngressProps);
return sg;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment