Reputation: 111
I'm trying to reference a couple of subnets to create ec2 instances but I'm sort of stuck. Let's say I have this:
const vpc = new Vpc(this, 'gwc-vpc', {
cidr: "10.20.0.0/16",
maxAzs: 3,
subnetConfiguration: [
{
subnetType: SubnetType.PRIVATE,
name: 'gossipSubnet',
cidrMask: 24
},
{
subnetType: SubnetType.PRIVATE,
name: 'dbSubnet',
cidrMask: 24
},
{
subnetType: SubnetType.PUBLIC,
name: 'extSubnet',
cidrMask: 24
}
]
})
How can I create an instance in the dbSubnet for example? Even better, what if I want to create an EC2 instance with 2 interfaces each of one is sitting in a different subnet (dbSubnet and gossipSubnet)? Any ideas?
Thanks!
Upvotes: 11
Views: 19921
Reputation: 161
Not sure if this is relevant here, but couldn't you also use the built-ins to select/target the subnet you are interested in?
const vpc = new Vpc(this, 'ProductionVPC', {
cidr: '10.10.0.0/16',
enableDnsHostnames: true,
enableDnsSupport: true,
defaultInstanceTenancy: DefaultInstanceTenancy.DEFAULT,
maxAzs: 2,
natGateways: 1,
subnetConfiguration: [
{
cidrMask: 24,
name: 'Public',
subnetType: SubnetType.PUBLIC
},
{
cidrMask: 24,
name: 'Private - Application',
subnetType: SubnetType.PRIVATE,
},
{
cidrMask: 24,
name: 'Private - Database',
subnetType: SubnetType.ISOLATED,
},
]
});
Tag.add(vpc, 'Name', 'Production VPC');
const subnets = vpc.selectSubnets({subnetType: SubnetType.Public}).subnets;
Upvotes: 16
Reputation: 87
vpc.selectSubnets({ subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS }).subnetIds
Upvotes: 2
Reputation: 1361
I've just done this in Python, not sure about the JS equivalent, and it is a bit roundabout, but it goes like this:
subnet_name = "some-name-to-find"
vpc = ec2.Vpc(
...,
subnet_configuration=[
...,
ec2.SubnetConfiguration(
name=subnet_name,
cidr_mask=20,
subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT
),
...
]
)
subnet_id = vpc.select_subnets(subnet_group_name=subnet_name).subnet_ids[0]
Essentially, the group name seems to just be the name of the subnet. It returns an object of type SelectedSubnets
that contains a list of subnet IDs.
Upvotes: 3
Reputation: 855
What I recommend is to have a single app that defines your network infrastructure (vpc, subnets, gateways, security groups, etc). Then you can add any number of separate apps that interface with it.
So you could have a single app that has the above that builds the VPC and Subnets and from there you should export the id of the vpc and all of the subnets you created with nice readable names
Now any other apps you create that build stuff in the VPC have the option to use simple Fn.importValue
to get any subnet or vpc id they need. Or they can use Vpc.fromLookup
to get a usable Vpc object in the cdk app. Once you have a Vpc object then you can use vpc.selectSubnets
to get the subnets you want to use in your app. Let me know if you want to see any examples in a specific language.
Upvotes: 3