aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
https://aws.amazon.com/cdk
Apache License 2.0
11.66k stars 3.92k forks source link

ImportError: cannot import name 'core' from 'aws_cdk' #19118

Closed ivan1016017 closed 2 years ago

ivan1016017 commented 2 years ago

What is the problem?

I run the basic commands to create a Python CDK project. I install the respective dependencies and I activate the python env, but I get ImportError when I try to create the CloudFormation stack.

Reproduction Steps

1 Create a project directory

mkdir ecs-devops-sandbox-cdk

2 Enter the directory

cd ecs-devops-sandbox-cdk

3 Use the CDK CLI to initiate a Python CDK project

cdk init --language python

4 Activate your Python virtual environment

.venv/Scripts/activate

5 Install CDK Python general dependencies

pip install -r requirements.txt

6 Install CDK Python ECS dependencies

7 Write the following code in ecs_devops_sandbox_cdk_stack.py is

from aws_cdk import (core, aws_ecs as ecs, aws_ecr as ecr, aws_ec2 as ec2, aws_iam as iam)

class EcsDevopsSandboxCdkStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create the ECR Repository
        ecr_repository = ecr.Repository(self,
                                        "ecs-devops-sandbox-repository",
                                        repository_name="ecs-devops-sandbox-repository")

        # Create the ECS Cluster (and VPC)
        vpc = ec2.Vpc(self,
                      "ecs-devops-sandbox-vpc",
                      max_azs=3)
        cluster = ecs.Cluster(self,
                              "ecs-devops-sandbox-cluster",
                              cluster_name="ecs-devops-sandbox-cluster",
                              vpc=vpc)

        # Create the ECS Task Definition with placeholder container (and named Task Execution IAM Role)
        execution_role = iam.Role(self,
                                  "ecs-devops-sandbox-execution-role",
                                  assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
                                  role_name="ecs-devops-sandbox-execution-role")
        execution_role.add_to_policy(iam.PolicyStatement(
            effect=iam.Effect.ALLOW,
            resources=["*"],
            actions=[
                "ecr:GetAuthorizationToken",
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
                ]
        ))
        task_definition = ecs.FargateTaskDefinition(self,
                                                    "ecs-devops-sandbox-task-definition",
                                                    execution_role=execution_role,
                                                    family="ecs-devops-sandbox-task-definition")
        container = task_definition.add_container(
            "ecs-devops-sandbox",
            image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
        )

        # Create the ECS Service
        service = ecs.FargateService(self,
                                     "ecs-devops-sandbox-service",
                                     cluster=cluster,
                                     task_definition=task_definition,
                                     service_name="ecs-devops-sandbox-service")

7 Create the CloudFormation stack

cdk deploy

What did you expect to happen?

I expected to not get any error when I run the command cdk deploy to create the CloudFormation stack

What actually happened?

I got the following error

Traceback (most recent call last):
  File "app.py", line 6, in <module>
    from ecs_devops_sandbox_cdk.ecs_devops_sandbox_cdk_stack import EcsDevopsSandboxCdkStack
  File "C:\Users\ivan\DjangoProjects\sampleCI-CD\ecs-devops-sandbox-cdk\ecs_devops_sandbox_cdk\ecs_devops_sandbox_cdk_stack.py", line 2, in <module>
    from aws_cdk import (core, aws_ecs as ecs, aws_ecr as ecr, aws_ec2 as ec2, aws_iam as iam)
ImportError: cannot import name 'core' from 'aws_cdk' (C:\Users\ivan\DjangoProjects\sampleCI-CD\ecs-devops-sandbox-cdk\.venv\lib\site-packages\aws_cdk\__init__.py)

CDK CLI Version

2.13.0

Framework Version

Visual Studio Code

Node.js Version

16.13.1

OS

Windows

Language

Python

Language Version

3.8.4

Other information

No response

ryparker commented 2 years ago

Hey @ivan1016017 👋🏻

In CDK v2 you'll need to update any v1 core.* modules to instead be imported as a top level module from aws_cdk. You'll also import the constructs module from the Construct package. See the following from our docs:

Change your imports to import Construct from the new constructs module, core types such as App and Stack from the top level of aws-cdk-lib, and stable Construct Library modules for the services you use from namespaces under aws-cdk-lib.

  from constructs import Construct
  from aws_cdk import App, Stack                    # core constructs
  from aws_cdk import aws_s3 as s3                  # stable module
  import aws_cdk.aws_codestar_alpha as codestar     # experimental module

  # ...

  class MyConstruct(Construct):
   # ...

  class MyStack(Stack):
   # ...

  s3.Bucket(...)

"CDK Toolkit compatibility" section of "Migrating from AWS CDK v1 to CDK v2" docs

github-actions[bot] commented 2 years ago

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.

ivan1016017 commented 2 years ago

Hi @ryparker . I could not reproduce your advice, but I could solve the issue. In CDK v2 you get the following default *_stack.py file.

class EcsDevopsSandboxCdkStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # The code that defines your stack goes here

        # example resource
        # queue = sqs.Queue(
        #     self, "EcsDevopsSandboxCdkQueue",
        #     visibility_timeout=Duration.seconds(300),
        # )

With this in mind, I switch core.Construct to Construct, and core.Stack to Stack. This is how you solve this issue. I got

(.venv) PS C:\Users\ivan\DjangoProjects\sampleCI-CD\ecs-devops-sandbox-cdk> cdk deploy

✨  Synthesis time: 8.61s
RaghunagaY commented 11 months ago

Hi @ivan1016017 @ryparker - Do you possess the solution for this problem? I'm encountering a similar issue while attempting to install app sync from the CDK. ImportError: cannot import name 'aws_cdk' from 'aws_cdk' (C:\01-myDemos\cdkAppsync.venv\Lib\site-packages\aws_cdk__init__.py) cdk version # 2.97.0 (build d7cf3be)