[英]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.