![](/img/trans.png)
[英]Accessing RDS Instance subnet for Glue Connection using AWS CDK Python
[英]Multiple Instance AWS CDK python
如何使用 Python 通过 AWS CDK 启动多个实例。
下面的代码将创建一个实例。
instance = ec2.Instance(self, "Instance",
instance_name = "myinstance",
instance_type=ec2.InstanceType("t3a.medium"),
machine_image=ec2.MachineImage.generic_windows({
'us-east-x': 'amiid',
}),
怎么写成循环? 尝试了 forloop 和 while 循环,失败了。
尽管您没有发布收到的错误或循环示例,但我将简要说明如何启动多个单一资源:
正如gshpychka在回答您的问题时提到的,您创建的每个构造(在您的情况下是 EC2 实例)必须唯一标识。 如果您查看实例构造或任何与此相关的构造,您会注意到所需的参数。 首先,是指您正在创建的堆栈的scope
。 其次,是id
,它是您在堆栈中创建的构造的 id(您可以在此文档中了解有关构造 ID 的更多信息)。 此 ID 必须是唯一的。 您的代码重新使用Instance
字符串作为 id,因此当在循环中重复传递时,此字符串不是唯一的。 为了在 python 中启动多个 EC2 实例,您可以执行以下操作:
# define your desired instance quantity
num_instances = 5
# for each in that number range
for n in range(0, num_instances):
# convert the number to a str so we can add to the id
num_str = str(n)
# use leading zeros so naming is consistent for double digit numbers
suffix = num_str.zfill(2)
# create the instance
ec2.Instance(self, 'Instance{}'.format(suffix),
instance_name = "myinstance"
instance_type = ec2.InstanceType("t3a.medium"),
machine_image = ec2.MachineImage.generic_windows({
'us-east-x': 'amiid',
}),
这应该创建 5 个实例,其id
如下所示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.