{"id":7949,"library":"aws-cdk-aws-ec2","title":"AWS CDK EC2 Construct Library (v1)","description":"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.","status":"maintenance","version":"1.204.0","language":"en","source_language":"en","source_url":"https://github.com/aws/aws-cdk.git","tags":["aws","cdk","ec2","infrastructure-as-code","cloud-development-kit","python"],"install":[{"cmd":"pip install aws-cdk.aws-ec2==1.204.0","lang":"bash","label":"Install specific version (v1)"},{"cmd":"pip install aws-cdk-lib","lang":"bash","label":"Install AWS CDK v2 (recommended for new projects)"}],"dependencies":[{"reason":"Core AWS CDK framework for v1 constructs.","package":"aws-cdk","optional":false},{"reason":"Foundational building blocks for CDK applications.","package":"constructs","optional":false}],"imports":[{"symbol":"aws_ec2","correct":"from aws_cdk import aws_ec2 as ec2"},{"note":"This is a v1 import path; v2 uses 'aws_cdk.aws_ec2' directly within 'aws-cdk-lib'.","wrong":"from aws_cdk_lib.aws_ec2 import Vpc","symbol":"Vpc","correct":"from aws_cdk.aws_ec2 import Vpc"}],"quickstart":{"code":"import os\nfrom aws_cdk import (\n    core,\n    aws_ec2 as ec2\n)\n\nclass Ec2Stack(core.Stack):\n    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:\n        super().__init__(scope, id, **kwargs)\n\n        # Create a VPC\n        vpc = ec2.Vpc(self, \"MyVpc\",\n                      cidr=\"10.0.0.0/16\",\n                      max_azs=2,\n                      subnet_configuration=[\n                          ec2.SubnetConfiguration(\n                              name=\"Public\",\n                              subnet_type=ec2.SubnetType.PUBLIC,\n                              cidr_mask=24\n                          ),\n                          ec2.SubnetConfiguration(\n                              name=\"Private\",\n                              subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,\n                              cidr_mask=24\n                          )\n                      ]\n                     )\n\n        # Define an Amazon Linux 2 AMI\n        ami = ec2.MachineImage.latest_amazon_linux(\n            generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,\n            edition=ec2.AmazonLinuxEdition.STANDARD,\n            virtualization=ec2.AmazonLinuxVirt.HVM,\n            storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE\n        )\n\n        # Create an EC2 instance\n        instance = ec2.Instance(self, \"MyInstance\",\n                                vpc=vpc,\n                                instance_type=ec2.InstanceType.of(\n                                    ec2.InstanceClass.T3,\n                                    ec2.InstanceSize.MICRO\n                                ),\n                                machine_image=ami,\n                                key_name=\"MyKeyPair\" # Ensure this key pair exists in your AWS account\n                               )\n\n        # Output the public IP address of the EC2 instance\n        core.CfnOutput(self, \"InstancePublicIp\", value=instance.instance_public_ip)\n\napp = core.App()\nEc2Stack(app, \"MyEc2Stack\",\n         env=core.Environment(\n             account=os.environ.get(\"CDK_DEFAULT_ACCOUNT\"),\n             region=os.environ.get(\"CDK_DEFAULT_REGION\")\n         )\n)\napp.synth()\n","lang":"python","description":"This quickstart code defines an AWS CDK v1 stack in Python that provisions a new VPC with public and private subnets, and an EC2 T3.Micro instance running Amazon Linux 2 within that VPC. It then outputs the public IP address of the instance. Replace 'MyKeyPair' with an existing EC2 Key Pair in your AWS account. You'll need to run `cdk bootstrap` and configure `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION` environment variables before deploying with `cdk deploy`."},"warnings":[{"fix":"Refer to the official AWS CDK Migration Guide for v1 to v2. For new projects, it is highly recommended to use `aws-cdk-lib` (CDK v2).","message":"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.","severity":"breaking","affected_versions":"All versions of aws-cdk.aws-ec2 (v1) when migrating to CDK v2"},{"fix":"Plan to migrate your CDK applications to AWS CDK v2. Install `aws-cdk-lib` and update your code accordingly.","message":"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.","severity":"deprecated","affected_versions":"1.x.x"},{"fix":"To control NAT Gateway creation, specify `nat_gateways: 0` in your `Vpc` props and configure alternative egress paths, or use `ec2.SubnetType.PRIVATE_ISOLATED` for subnets that do not require internet access.","message":"By default, a `Vpc` construct will create NAT Gateways in every public subnet, which incur costs.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure `cdk.context.json` is committed to your repository and not ignored by `.gitignore`.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"For production environments requiring specific AMI versions, use `MachineImage.generic_linux(ami_map={'region': 'ami-id'})` or `MachineImage.from_ssm_parameter('parameter-name')`.","message":"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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"For 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.","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.","error":"ModuleNotFoundError: No module named 'aws_cdk.aws_ec2'"},{"fix":"Define `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'`.","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.","error":"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."},{"fix":"Inspect 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.","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.","error":"cdk deploy failed. Stack 'MyEc2Stack' is in ROLLBACK_COMPLETE state."},{"fix":"Double-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.","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.","error":"jsii.errors.JSIIError: Could not find any AMIs for the given criteria"}]}