AWS CDK EC2 Construct Library (v1)
This is the AWS Cloud Development Kit (CDK) Construct Library for AWS EC2, part of the AWS CDK v1 ecosystem. It provides high-level object-oriented abstractions to define EC2 resources and networking in Python, which are then provisioned via AWS CloudFormation. AWS CDK v1 is currently in maintenance mode, with active development focused on AWS CDK v2. The AWS CDK (including this library) generally follows a continuous release cadence for minor versions within its major release lines.
Common errors
-
ModuleNotFoundError: No module named 'aws_cdk.aws_ec2'
cause The Python package `aws-cdk.aws-ec2` is not installed in your environment or you are attempting to use v1 import syntax with a v2 `aws-cdk-lib` installation without proper aliasing.fixFor AWS CDK v1, run `pip install aws-cdk.aws-ec2`. For AWS CDK v2, ensure `pip install aws-cdk-lib` is run and update your imports to `from aws_cdk import aws_ec2 as ec2` if still using the v1-style import, or directly `from aws_cdk.aws_ec2 import Vpc` etc. if using v2's consolidated library. -
Error: Stack 'MyStack' requires account number and region. Please specify them using the 'env' property when defining the stack, or using the CDK_DEFAULT_ACCOUNT and CDK_DEFAULT_REGION environment variables.
cause CDK applications need to know the target AWS account and region for deployment. This information was not provided in the stack definition or via environment variables.fixDefine `env` in your stack: `env=core.Environment(account='YOUR_ACCOUNT_ID', region='YOUR_REGION')` or set environment variables: `export CDK_DEFAULT_ACCOUNT='YOUR_ACCOUNT_ID'` and `export CDK_DEFAULT_REGION='YOUR_REGION'`. -
cdk deploy failed. Stack 'MyEc2Stack' is in ROLLBACK_COMPLETE state.
cause A previous deployment attempt failed and rolled back, leaving the CloudFormation stack in a non-deployable state for direct updates. This can be due to various configuration errors or resource limits.fixInspect the CloudFormation events in the AWS console for detailed error messages. Often, deleting the stack (`cdk destroy MyEc2Stack`) and redeploying after fixing the issue is the quickest way to resolve this, especially during initial development. -
jsii.errors.JSIIError: Could not find any AMIs for the given criteria
cause The `MachineImage` parameters (e.g., `AmazonLinuxGeneration`, `edition`, `virtualization`, `storage`) did not match any available AMIs in the specified AWS region, or the region does not support the requested configuration.fixDouble-check the `MachineImage` criteria against the AWS console or documentation for the target region. Consider using a specific AMI ID if you know it, or broaden your search criteria. Ensure your `CDK_DEFAULT_REGION` is correctly set.
Warnings
- breaking AWS CDK v1 construct libraries like `aws-cdk.aws-ec2` are separate packages. AWS CDK v2 consolidates all stable constructs into a single package, `aws-cdk-lib`. Migrating from v1 to v2 requires updating import statements (e.g., `from aws_cdk import aws_ec2` becomes `from aws_cdk.aws_ec2`), re-bootstrapping environments, and may involve API changes.
- deprecated AWS CDK v1 reached End-of-Support on June 1, 2023. While packages like `aws-cdk.aws-ec2` are still available on PyPI, they are no longer actively updated and users are encouraged to migrate to AWS CDK v2 for continued support and new features.
- gotcha By default, a `Vpc` construct will create NAT Gateways in every public subnet, which incur costs.
- gotcha The `Vpc` construct, when looking up an existing VPC using `Vpc.from_lookup()`, writes context values to `cdk.context.json`. This file must be committed to source control to ensure repeatable builds and functionality in CI/CD environments.
- gotcha Using `MachineImage.latest_amazon_linux()` or similar methods might result in different AMIs over time. If precise AMI control is needed for consistency or compliance, use a specific AMI ID or an SSM parameter. The AWS official NAT instance AMI reached EOL on Dec 31, 2023.
Install
-
pip install aws-cdk.aws-ec2==1.204.0 -
pip install aws-cdk-lib
Imports
- aws_ec2
from aws_cdk import aws_ec2 as ec2
- Vpc
from aws_cdk_lib.aws_ec2 import Vpc
from aws_cdk.aws_ec2 import Vpc
Quickstart
import os
from aws_cdk import (
core,
aws_ec2 as ec2
)
class Ec2Stack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# Create a VPC
vpc = ec2.Vpc(self, "MyVpc",
cidr="10.0.0.0/16",
max_azs=2,
subnet_configuration=[
ec2.SubnetConfiguration(
name="Public",
subnet_type=ec2.SubnetType.PUBLIC,
cidr_mask=24
),
ec2.SubnetConfiguration(
name="Private",
subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,
cidr_mask=24
)
]
)
# Define an Amazon Linux 2 AMI
ami = ec2.MachineImage.latest_amazon_linux(
generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
edition=ec2.AmazonLinuxEdition.STANDARD,
virtualization=ec2.AmazonLinuxVirt.HVM,
storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE
)
# Create an EC2 instance
instance = ec2.Instance(self, "MyInstance",
vpc=vpc,
instance_type=ec2.InstanceType.of(
ec2.InstanceClass.T3,
ec2.InstanceSize.MICRO
),
machine_image=ami,
key_name="MyKeyPair" # Ensure this key pair exists in your AWS account
)
# Output the public IP address of the EC2 instance
core.CfnOutput(self, "InstancePublicIp", value=instance.instance_public_ip)
app = core.App()
Ec2Stack(app, "MyEc2Stack",
env=core.Environment(
account=os.environ.get("CDK_DEFAULT_ACCOUNT"),
region=os.environ.get("CDK_DEFAULT_REGION")
)
)
app.synth()