无法在 AWS cdk 中导入 VPC
Unable to import VPC in AWS cdk
您好,我正在研究 AWS cdk。我正在尝试创建一些资源,如 ECS、SG、LB 等。我想在资源中使用默认 VPC。下面是我的代码。
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, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
vpc = ec2.Vpc.from_lookup(scope = core.Construct, vpc_id='vpc-d45072b3', is_default=True, id="test" )
cluster = ecs.Cluster(
stack, "EcsCluster",
vpc=vpc
)
cluster.add_capacity("DefaultAutoScalingGroup",
instance_type=ec2.InstanceType("t2.micro"),
key_name="MyNewEC2KeyPair",
desired_capacity=1)
# create SG
sg_elb = ec2.SecurityGroup(stack, "MerchWebServicesLoadBalancerSecurityGroup",
description= "Allow ssh access to ec2 instances",
security_group_name= "MerchWebServicesLoadBalancerSecurityGroup",
vpc= vpc
);
sg_elb.add_ingress_rule(
peer = ec2.Peer.any_ipv4(),
connection = ec2.Port.tcp(22)
)
# Create a task definition with placement constraints
task_definition = ecs.Ec2TaskDefinition(
stack, "TaskDef",
# placement_constraints=[
# ecs.PlacementConstraint.distinct_instances()
# ]
)
container = task_definition.add_container(
"web",
image=ecs.ContainerImage.from_registry("nginx:latest"),
memory_limit_mib=256,
)
port_mapping = ecs.PortMapping(
container_port=80,
host_port=8080,
protocol=ecs.Protocol.TCP
)
container.add_port_mappings(port_mapping)
# Create Service
service = ecs.Ec2Service(
stack, "Service",
cluster=cluster,
task_definition=task_definition,
security_group=sg_elb
)
lb = elbv2.ApplicationLoadBalancer(
stack, "LB",
vpc = vpc,
internet_facing= True
)
listener = lb.add_listener(
"PublicListener",
port = 80,
open = True
)
health_check = elbv2.HealthCheck(
interval=core.Duration.seconds(60),
path="/",
timeout=core.Duration.seconds(5)
)
# Attach ALB to ECS Service
listener.add_targets(
"ECS",
port=80,
targets=[service],
health_check=health_check,
)
service.add_placement_strategies(
ecs.PlacementStrategy.packed_by(ecs.BinPackResource.MEMORY))
service.add_placement_strategies(
ecs.PlacementStrategy.spread_across(
ecs.BuiltInAttributes.AVAILABILITY_ZONE))
app.synth()
当我执行 cdk synth 时出现以下错误。
File "app.py", line 5, in <module>
from cdk_python.cdk_python_stack import CdkPythonStack
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\cdk_python\cdk_python_stack.py", line 21, in <module>
vpc = ec2.Vpc.from_lookup(scope = core.Construct, vpc_id='vpc-d45072b3', is_default=True, id="test" )
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\aws_cdk\aws_ec2\__init__.py", line 21474, in from_lookup
return jsii.sinvoke(cls, "fromLookup", [scope, id, options])
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\__init__.py", line 105, in wrapped
return _recursize_dereference(kernel, fn(kernel, *args, **kwargs))
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\__init__.py", line 292, in sinvoke
args=_make_reference_for_native(self, args),
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\providers\process.py", line 349, in sinvoke
return self._process.send(request, InvokeResponse)
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\providers\process.py", line 301, in send
data = json.dumps(req_dict, default=jdefault).encode("utf8")
File "C:\Program Files (x86)\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Program Files (x86)\Python37-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Program Files (x86)\Python37-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\providers\process.py", line 144, in jdefault
raise TypeError("Don't know how to convert object to JSON: %r" % obj)
TypeError: Don't know how to convert object to JSON: <class 'aws_cdk.core.Construct'>
在构造函数中我改为
def init(self, app: core.Construct, id: str, **kwargs) -> None:
现在我开始收到错误
NameError: name 'self' is not defined
(.env) C:\Users\ngodbole\Documents\MerchWebServices\LocationCDK\LocationCDK>cdk synth
Traceback (most recent call last):
File "app.py", line 5, in <module>
from location_cdk.location_cdk_stack import LocationCdkStack
File "C:\Users\ngodbole\Documents\MerchWebServices\LocationCDK\LocationCDK\location_cdk\location_cdk_stack.py", line 9, in <module>
class LocationCdkStack(core.Stack):
File "C:\Users\ngodbole\Documents\MerchWebServices\LocationCDK\LocationCDK\location_cdk\location_cdk_stack.py", line 15, in LocationCdkStack
vpc = ec2.Vpc.from_lookup(self, "", is_default=True)
NameError: name 'self' is not defined
Subprocess exited with error 1
我正在尝试获取我帐户中存在的默认 VPC。我想在我的 python cdk 脚本期间创建的所有资源中使用相同的 VPC。
有人可以帮我弄清楚这个问题吗?任何帮助将不胜感激。谢谢
只需将 is_default 参数设置为 True 即可获取默认 VPC。
stack.py
class CdkPythonStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
vpc = ec2.Vpc.from_lookup(self, "default_vpc", is_default=True)
cluster = ecs.Cluster(
self, "EcsCluster",
vpc=vpc
)
...
您还需要按照此 issue 中所述在您的堆栈配置中明确设置帐户和区域。因此,无论何时执行资源查找,都必须指定帐户。
app.py
CdkPythonStack(
app=app,
id="cdk-python-1",
env={
'account': os.environ['CDK_DEFAULT_ACCOUNT'],
'region': os.environ['CDK_DEFAULT_REGION']
}
)
在 JS 中,这是我定义要使用的 VPC 的方式...
在此文件中...
rootProject/lib/applicationName.js
#!/usr/bin/env node
const cdk = require('@aws-cdk/core');
const { PrerenderInfrasctutureStack } = require('../lib/applicationName-stack');
const app = new cdk.App();
const DEVapSouthEast2Env = {account: 'xxx', region: 'ap-southeast-2'};
const PRODapSouthEast2Env = {account: 'xxx', region: 'ap-southeast-2'};
// change the env to define where the app will be deployed
new applicationName(app, 'applicationName', {env: DEVapSouthEast2Env});
然后在这个文件中...
rootProject/lib/applicationName-stack.js:
const myVPC = ec2.Vpc.fromLookup(this, 'publicVpc', {
vpcId:'vpc-xxx'
});
所以基本上,传递帐户详细信息,然后为'ec2.Vpc.fromLookup'传递vpcID
您好,我正在研究 AWS cdk。我正在尝试创建一些资源,如 ECS、SG、LB 等。我想在资源中使用默认 VPC。下面是我的代码。
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, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
vpc = ec2.Vpc.from_lookup(scope = core.Construct, vpc_id='vpc-d45072b3', is_default=True, id="test" )
cluster = ecs.Cluster(
stack, "EcsCluster",
vpc=vpc
)
cluster.add_capacity("DefaultAutoScalingGroup",
instance_type=ec2.InstanceType("t2.micro"),
key_name="MyNewEC2KeyPair",
desired_capacity=1)
# create SG
sg_elb = ec2.SecurityGroup(stack, "MerchWebServicesLoadBalancerSecurityGroup",
description= "Allow ssh access to ec2 instances",
security_group_name= "MerchWebServicesLoadBalancerSecurityGroup",
vpc= vpc
);
sg_elb.add_ingress_rule(
peer = ec2.Peer.any_ipv4(),
connection = ec2.Port.tcp(22)
)
# Create a task definition with placement constraints
task_definition = ecs.Ec2TaskDefinition(
stack, "TaskDef",
# placement_constraints=[
# ecs.PlacementConstraint.distinct_instances()
# ]
)
container = task_definition.add_container(
"web",
image=ecs.ContainerImage.from_registry("nginx:latest"),
memory_limit_mib=256,
)
port_mapping = ecs.PortMapping(
container_port=80,
host_port=8080,
protocol=ecs.Protocol.TCP
)
container.add_port_mappings(port_mapping)
# Create Service
service = ecs.Ec2Service(
stack, "Service",
cluster=cluster,
task_definition=task_definition,
security_group=sg_elb
)
lb = elbv2.ApplicationLoadBalancer(
stack, "LB",
vpc = vpc,
internet_facing= True
)
listener = lb.add_listener(
"PublicListener",
port = 80,
open = True
)
health_check = elbv2.HealthCheck(
interval=core.Duration.seconds(60),
path="/",
timeout=core.Duration.seconds(5)
)
# Attach ALB to ECS Service
listener.add_targets(
"ECS",
port=80,
targets=[service],
health_check=health_check,
)
service.add_placement_strategies(
ecs.PlacementStrategy.packed_by(ecs.BinPackResource.MEMORY))
service.add_placement_strategies(
ecs.PlacementStrategy.spread_across(
ecs.BuiltInAttributes.AVAILABILITY_ZONE))
app.synth()
当我执行 cdk synth 时出现以下错误。
File "app.py", line 5, in <module>
from cdk_python.cdk_python_stack import CdkPythonStack
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\cdk_python\cdk_python_stack.py", line 21, in <module>
vpc = ec2.Vpc.from_lookup(scope = core.Construct, vpc_id='vpc-d45072b3', is_default=True, id="test" )
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\aws_cdk\aws_ec2\__init__.py", line 21474, in from_lookup
return jsii.sinvoke(cls, "fromLookup", [scope, id, options])
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\__init__.py", line 105, in wrapped
return _recursize_dereference(kernel, fn(kernel, *args, **kwargs))
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\__init__.py", line 292, in sinvoke
args=_make_reference_for_native(self, args),
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\providers\process.py", line 349, in sinvoke
return self._process.send(request, InvokeResponse)
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\providers\process.py", line 301, in send
data = json.dumps(req_dict, default=jdefault).encode("utf8")
File "C:\Program Files (x86)\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Program Files (x86)\Python37-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Program Files (x86)\Python37-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\ngodbole\Documents\MerchWebServices\CDKPython\.env\lib\site-packages\jsii\_kernel\providers\process.py", line 144, in jdefault
raise TypeError("Don't know how to convert object to JSON: %r" % obj)
TypeError: Don't know how to convert object to JSON: <class 'aws_cdk.core.Construct'>
在构造函数中我改为
def init(self, app: core.Construct, id: str, **kwargs) -> None:
现在我开始收到错误
NameError: name 'self' is not defined
(.env) C:\Users\ngodbole\Documents\MerchWebServices\LocationCDK\LocationCDK>cdk synth
Traceback (most recent call last):
File "app.py", line 5, in <module>
from location_cdk.location_cdk_stack import LocationCdkStack
File "C:\Users\ngodbole\Documents\MerchWebServices\LocationCDK\LocationCDK\location_cdk\location_cdk_stack.py", line 9, in <module>
class LocationCdkStack(core.Stack):
File "C:\Users\ngodbole\Documents\MerchWebServices\LocationCDK\LocationCDK\location_cdk\location_cdk_stack.py", line 15, in LocationCdkStack
vpc = ec2.Vpc.from_lookup(self, "", is_default=True)
NameError: name 'self' is not defined
Subprocess exited with error 1
我正在尝试获取我帐户中存在的默认 VPC。我想在我的 python cdk 脚本期间创建的所有资源中使用相同的 VPC。 有人可以帮我弄清楚这个问题吗?任何帮助将不胜感激。谢谢
只需将 is_default 参数设置为 True 即可获取默认 VPC。
stack.py
class CdkPythonStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
vpc = ec2.Vpc.from_lookup(self, "default_vpc", is_default=True)
cluster = ecs.Cluster(
self, "EcsCluster",
vpc=vpc
)
...
您还需要按照此 issue 中所述在您的堆栈配置中明确设置帐户和区域。因此,无论何时执行资源查找,都必须指定帐户。
app.py
CdkPythonStack(
app=app,
id="cdk-python-1",
env={
'account': os.environ['CDK_DEFAULT_ACCOUNT'],
'region': os.environ['CDK_DEFAULT_REGION']
}
)
在 JS 中,这是我定义要使用的 VPC 的方式...
在此文件中... rootProject/lib/applicationName.js
#!/usr/bin/env node
const cdk = require('@aws-cdk/core');
const { PrerenderInfrasctutureStack } = require('../lib/applicationName-stack');
const app = new cdk.App();
const DEVapSouthEast2Env = {account: 'xxx', region: 'ap-southeast-2'};
const PRODapSouthEast2Env = {account: 'xxx', region: 'ap-southeast-2'};
// change the env to define where the app will be deployed
new applicationName(app, 'applicationName', {env: DEVapSouthEast2Env});
然后在这个文件中...
rootProject/lib/applicationName-stack.js:
const myVPC = ec2.Vpc.fromLookup(this, 'publicVpc', {
vpcId:'vpc-xxx'
});
所以基本上,传递帐户详细信息,然后为'ec2.Vpc.fromLookup'传递vpcID