繁体   English   中英

无法在 AWS CDK 中运行 Python

[英]Unable to run Python in AWS CDK

嗨,我正在研究 Python。 我最近开始使用 Python。 我在AWS cdk中使用 Python 来创建资源。 下面是我的 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()

下面是我来自 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")

当我运行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

有人可以帮我解决这个错误吗? 任何帮助,将不胜感激。 谢谢。

在 python 中,缩进很重要。 self引用 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")

修复缩进(将vpc = ec2.Vpc...__init__方法中即可

缩进关闭,这使得代码在 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