diff --git a/packages/@aws-cdk/aws-ec2/lib/instance.ts b/packages/@aws-cdk/aws-ec2/lib/instance.ts index 1cd3d73a62c9f..79a6bb262d053 100644 --- a/packages/@aws-cdk/aws-ec2/lib/instance.ts +++ b/packages/@aws-cdk/aws-ec2/lib/instance.ts @@ -8,7 +8,7 @@ import { IMachineImage, OperatingSystemType } from './machine-image'; import { ISecurityGroup, SecurityGroup } from './security-group'; import { UserData } from './user-data'; import { BlockDevice, synthesizeBlockDeviceMappings } from './volume'; -import { IVpc, SubnetSelection } from './vpc'; +import { IVpc, Subnet, SubnetSelection } from './vpc'; /** * Name tag constant @@ -291,10 +291,22 @@ export class Instance extends Resource implements IInstance { if (selected.length === 1) { subnet = selected[0]; } else { - throw new Error(`Need exactly 1 subnet to match AZ '${props.availabilityZone}', found ${selected.length}. Use a different availabilityZone.`); + this.node.addError(`Need exactly 1 subnet to match AZ '${props.availabilityZone}', found ${selected.length}. Use a different availabilityZone.`); } } else { - subnet = subnets[0]; + if (subnets.length > 0) { + subnet = subnets[0]; + } else { + this.node.addError(`Did not find any subnets matching '${JSON.stringify(props.vpcSubnets)}', please use a different selection.`); + } + } + if (!subnet) { + // We got here and we don't have a subnet because of validation errors. + // Invent one on the spot so the code below doesn't fail. + subnet = Subnet.fromSubnetAttributes(this, 'DummySubnet', { + subnetId: 's-notfound', + availabilityZone: 'az-notfound', + }); } this.instance = new CfnInstance(this, 'Resource', { diff --git a/packages/@aws-cdk/aws-ec2/test/test.vpc.from-lookup.ts b/packages/@aws-cdk/aws-ec2/test/test.vpc.from-lookup.ts index 0c88693f1e7db..cbbb2550e2dcc 100644 --- a/packages/@aws-cdk/aws-ec2/test/test.vpc.from-lookup.ts +++ b/packages/@aws-cdk/aws-ec2/test/test.vpc.from-lookup.ts @@ -1,7 +1,7 @@ import { Construct, ContextProvider, GetContextValueOptions, GetContextValueResult, Lazy, Stack } from '@aws-cdk/core'; import * as cxapi from '@aws-cdk/cx-api'; import { Test } from 'nodeunit'; -import { SubnetType, Vpc } from '../lib'; +import { GenericLinuxImage, Instance, InstanceType, SubnetType, Vpc } from '../lib'; export = { 'Vpc.fromLookup()': { @@ -188,6 +188,26 @@ export = { test.done(); }, + + 'don\'t crash when using subnetgroup name in lookup VPC'(test: Test) { + // GIVEN + const stack = new Stack(undefined, 'MyTestStack', { env: { account: '1234567890', region: 'dummy' } }); + const vpc = Vpc.fromLookup(stack, 'vpc', { isDefault: true }); + + // WHEN + new Instance(stack, 'Instance', { + vpc, + instanceType: new InstanceType('t2.large'), + machineImage: new GenericLinuxImage({ dummy: 'ami-1234' }), + vpcSubnets: { + subnetGroupName: 'application_layer', + }, + }); + + // THEN -- no exception occurred + + test.done(); + }, }, };