Skip to content

Instantly share code, notes, and snippets.

@NutterzUK
Created December 24, 2018 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NutterzUK/dabd669d4ebad3bbc4d4e82d5f23c1ee to your computer and use it in GitHub Desktop.
Save NutterzUK/dabd669d4ebad3bbc4d4e82d5f23c1ee to your computer and use it in GitHub Desktop.
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