如何使用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循环,但失败。
发布于 2021-11-11 07:33:47
尽管您没有发布收到的错误或循环示例,但我将简要说明如何启动多个单个资源:
正如gshpychka在回答您的问题时提到的,您创建的每个构造,在本例中是一个EC2实例,都必须唯一标识。如果您查看instance construct或任何与此相关的构造,您将注意到需要的参数。首先,是引用您正在创建的堆栈的scope
。第二个参数是id
,它是您在堆栈中创建的结构的id (您可以使用learn more about Construct IDs in this doc)。此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',
}),
这将使用和id
创建5个实例,如下所示:
https://stackoverflow.com/questions/69923353
复制