11

There is lots of example code, but the rapidly improving cdk package isn't helping me find working examples of some (I thought) simple things. eg., even an import I found in an example fails:

import { VpcNetworkRef } from '@aws-cdk/aws-ec2';
 error TS2724: Module '"../node_modules/@aws-cdk/aws-ec2/lib"' has no exported member 'VpcNetworkRef'. Did you mean 'IVpcNetwork'?

Why does the example ec2 code not show creation of raw ec2 instances?

WHAT would help is example cdk code that uses hardcoded VpcId and SecurityGroupId (I'll pass these in as context values) to create a pair of new subnets (ie., 1 for each availability zone) into which we place a pair of EC2 instances.

Again, the target VPC and SecurityGroup for the instances already exist. We just (today) create new subnets as we add new sets of EC2 instances.

We have lots of distinct environments (sets of aws infrastructure) that currently share a single account, VPC, and security group. This will change, but my current goal is to see if we can use the cloud dev kit to create new distinct environments in this existing model. We have a CF template today.

I can't tell where to start. The examples for referencing existing VPCs aren't compiling.

import { VpcNetworkRef } from '@aws-cdk/aws-ec2';
const vpc = VpcNetworkRef.import(this, 'unused', {vpcId, availabilityZones: ['unused']});

Again, the target VPC and SecurityGroup for the instances already exist. We just (today) create new subnets as we add new sets of EC2 instances.

-----edit-------->

Discussions on gitter helped me answer this and how to add a bare Instance

const vpc - ec2.VpcNetwork.import(this, 'YOUR-VPC-NAME', {
    vpcId: 'your-vpc-id',
    availabilityZones: ['list', 'some', 'zones'],
    publicSubnetIds: ['list', 'some', 'subnets'],
    privateSubnetIds: ['list', 'some', 'more'],
});

const sg = ec2.SecurityGroup.import(this, 'YOUR-SG-NAME', {
    securityGroupId: 'your-sg-id'
});

// can add subnets to existing..
const newSubnet = new ec2.VpcSubnet(this, "a name", {
    availablityZone: "us-west-2b",
    cidrBlock: "a.b.c.d/e",
    vpcId: vpc.vpcId
});

// add bare instance
new ec2.CfnInstance(this, "instance name", {
    imageId: "an ami",
    securityGroupIds: [sg.securityGroupId],
    subnetId: newSubnet.subnetId,
    instanceType: "an instance type",
    tags: [{ key: "key", value: "value"}]
});

No further answers needed... for me.

2
  • Can you provide a re-producible code snippet? Have you looked at the complete examples for ec2? If your code snippet is complete, you need to create an app and stack properly. 'this' must point to an app, stack or construct. This example might help: github.com/awslabs/aws-cdk/blob/master/examples/…
    – Upio
    Jan 15, 2019 at 2:29
  • Well aware of that example which doesn't re-use an existing vpc, security group, add a subnet, or even a raw ec2 instance without an autoscaling group. But thanks for reading. Jan 15, 2019 at 14:41

3 Answers 3

7
import ec2 = require('@aws-cdk/aws-ec2');

// looking up a VPC by its name
const vpc = ec2.Vpc.fromLookup(this, 'VPC', {
  vpcName: 'VPC-Name'
});


// looking up an SG by its ID
const sg = ec2.SecurityGroup.fromSecurityGroupId(this, 'SG', 'SG-ID')


// creating the EC2 instance
const instance = new ec2.Instance(this, 'Instance', {
  vpc: vpc,
  securityGroup: sg,
  instanceType: new ec2.InstanceType('m4.large'),
  machineImage: new ec2.GenericLinuxImage({
    'us-east-1': 'ami-abcdef' // <- add your ami-region mapping here
   }),
});
2
  • Why the documentation can't have a nice simple example like this, I don't know! Thanks @udondan Dec 23, 2020 at 18:11
  • Can we import sg using name tag?. I could see VPC import with name tag
    – Prashanna
    Feb 18, 2021 at 3:22
0

I was running into the issue of importing an existing vpc / subnet / security group as well. I believe it's changed a bit since the original post. Here is how to do it as of v1.18.0:

import cdk, { Construct, Stack, Subnet, StackProps } from '@aws-cdk/core';
import { SecurityGroup, SubnetType, Vpc } from "@aws-cdk/aws-ec2";

const stackProps: StackProps = {
  env: {
    region: 'your region',
    account: 'your account'
  },
};

export class MyStack extends Stack {
  constructor(scope: Construct, id: string) {
    super(scope, id, stackProps);

    const vpc = Vpc.fromVpcAttributes(this, 'vpc', {
      vpcId: 'your vpc id',
      availabilityZones: ['your region'],
      privateSubnetIds: ['your subnet id']
    });

    //Get subnets that already exists off your current vpc. 
    const subnets = vpc.selectSubnets({subnetType: SubnetType.PRIVATE});

    //Create a subnet in the existing vpc
     const newSubnet = new Subnet(this, 'subnet', {
       availabilityZone: 'your zone', 
       cidrBlock: 'a.b.c.d/e', 
       vpcId: vpc.vpcId
     });

    //Get an existing security group.
    const securityGroup = SecurityGroup.fromSecurityGroupId(this, 'securitygroup', 'your security group id');

  }
}
0

To add to udondan's already solid answer, it's become possible as of late 2021, to look up a security group by name, for example for the default security group:

const sg = ec2.SecurityGroup.fromLookupByName(this, 'SG', 'default', vpc);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.