Reputation: 361
Wondering if there's a way with the AWS CDK to list all the available VPCs for the current account.
For example the CLI provides aws ec2 describe-vpcs
which is very handy to retrieve all the available VPCs.
I can also import a VPC if I know its identifier (python example) :
vpc = ec2.Vpc.from_lookup(self, "vpc", vpc_id=vpc_id)
However at this point, I haven't found a way to retrieve all (or filtered) VPCs (or their ids) using the CDK. Any pointers ?
Note : we're currently passing a CIDR block string to the cdk
command line so we can configure the cidr
parameter of the aw2s_ec2.Vpc
constructor. We would like to avoid that and let the application find the next available CIDR block on its own (or the one that was used for this deployment if previously created). For example, Vpc.private_subnets
offers a way to list all private subnets (and their CIDR blocks) for an existing vpc, so I would have assumed the same could be obtained for vpcs in an AWS account.
Upvotes: 2
Views: 1835
Reputation: 11512
Short answer: don't.
Long answer: This is against AWS CDK best practices. As described in the docs on the topic, CDK apps should be deterministic. That is, CDK code (along with context) in your VCS should always synth to the same template:
Determinism is key to successful AWS CDK deployments. A AWS CDK app should have essentially the same result whenever it is deployed (notwithstanding necessary differences based on the environment where it's deployed).
Using AWS SDK in your CDK code breaks this determinism, so it's a good idea to rethink your approach.
Upvotes: 4
Reputation: 103
The great thing about CDK, in my opinion, is the pre-processing you can do on your templates. I have done similar things by combining boto3
in my CDK code.
from aws_cdk import (
core,
core as cdk,
aws_ec2 as ec2
)
import boto3
class CdkTestStack(cdk.Stack):
def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# The code that defines your stack goes here
client = boto3.client('ec2')
all_vpcs = client.describe_vpcs()
vpc = ec2.Vpc.from_lookup(self, "vpc", vpc_id=all_vpcs['Vpcs'][2]['VpcId'])
sg = ec2.SecurityGroup(self, 'testSG',
vpc=vpc)
sg.add_ingress_rule(peer=ec2.Peer.any_ipv4(),
connection=ec2.Port.tcp(80))
Running cdk synth
, we get:
Resources:
testSG462E14A9:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: CdkTestStack/testSG
SecurityGroupEgress:
- CidrIp: 0.0.0.0/0
Description: Allow all outbound traffic by default
IpProtocol: "-1"
SecurityGroupIngress:
- CidrIp: 0.0.0.0/0
Description: from 0.0.0.0/0:80
FromPort: 80
IpProtocol: tcp
ToPort: 80
VpcId: vpc-1234567890abcdefg
Metadata:
aws:cdk:path: CdkTestStack/testSG/Resource
CDKMetadata:
:
Upvotes: 2