Niranjan
Niranjan

Reputation: 2229

Unable to run Python in AWS CDK

Hi I am working on Python. I recently started working with Python. I am using Python in AWS cdk to create resources. Below is my code from app.py file:

from aws_cdk import core
from cdk_python.cdk_python_stack import CdkPythonStack
app = core.App()
CdkPythonStack(app, "cdk-python-1", env={'region': 'ap-southeast-2'})

app.synth()

Below is my code from cdk_python_stack.py file.

from aws_cdk import (
    aws_ec2 as ec2,
    aws_ecs as ecs,
    aws_elasticloadbalancingv2 as elbv2,
    aws_ecr as ecr,
    core,
)
class CdkPythonStack(core.Stack):
    def __init__(self, app: core.Construct, id: str, **kwargs) -> None:
        super().__init__(app, id, **kwargs)


vpc = ec2.Vpc.from_lookup(self, vpc_id='vpc-d45072b3', id="test")

When I run cdk synth I get this error:

File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\cdk_python\cdk_python_stack.py", line 13, in <module>
    vpc = ec2.Vpc.from_lookup(self, vpc_id='vpc-d45072b3', id="test")
NameError: name 'self' is not defined

Can someone help me to fix this error? Any help would be appreciated. Thanks.

Upvotes: 0

Views: 3001

Answers (2)

Yang Xiao
Yang Xiao

Reputation: 136

The indent is off, which makes the code outside of the class

class CdkPythonStack(core.Stack):
    def __init__(self, app: core.Construct, id: str, **kwargs) -> None:
        super().__init__(app, id, **kwargs)


    vpc = ec2.Vpc.from_lookup(self, vpc_id='vpc-d45072b3', id="test") <-- here

Upvotes: 0

quadroid
quadroid

Reputation: 8940

In python the indentation matters. self references the class construct itself if the code calling it is part of it. Which in your case it is not.

class CdkPythonStack(core.Stack):
    def __init__(self, app: core.Construct, id: str, **kwargs) -> None:
        super().__init__(app, id, **kwargs)


        vpc = ec2.Vpc.from_lookup(self, vpc_id='vpc-d45072b3', id="test")

Fixing the indentation (moving the vpc = ec2.Vpc... code into the __init__ method of the class will work

Upvotes: 2

Related Questions