简体   繁体   English

无法在 AWS CDK 中运行 Python

[英]Unable to run Python in AWS CDK

Hi I am working on Python.嗨,我正在研究 Python。 I recently started working with Python.我最近开始使用 Python。 I am using Python in AWS cdk to create resources.我在AWS cdk中使用 Python 来创建资源。 Below is my code from app.py file:下面是我的 app.py 文件中的代码:

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.下面是我来自 cdk_python_stack.py 文件的代码。

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:当我运行cdk synth我得到这个错误:

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.谢谢。

In python the indentation matters.在 python 中,缩进很重要。 self references the class construct itself if the code calling it is part of it. self引用 class 结构本身,如果调用它的代码是它的一部分。 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修复缩进(将vpc = ec2.Vpc...__init__方法中即可

The indent is off, which makes the code outside of the class缩进关闭,这使得代码在 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM