Reputation: 21
How to launch multiple instances via AWS CDK using Python.
below code will create a single instance.
instance = ec2.Instance(self, "Instance",
instance_name = "myinstance",
instance_type=ec2.InstanceType("t3a.medium"),
machine_image=ec2.MachineImage.generic_windows({
'us-east-x': 'amiid',
}),
How can write in a loop? tried with forloop and while loop, failed.
Upvotes: 1
Views: 1261
Reputation: 5065
Although you didn't post what error you received or an example of your loop I'll explain briefly how you might launch multiples of a single resource:
As gshpychka mentioned in reply to your question each construct you create, in your case an EC2 instance, must be uniquely identified. If you review the instance construct, or any construct for that matter, you will notice the parameters that are required. First, is the scope
which refers to the stack you are creating. Second, is the id
which is the id of the construct you are creating within the stack (you can learn more about Construct IDs in this doc). This id must be unique. Your code re-uses the Instance
string as the id so when passed repeatedly in a loop this string is not unique. In order to launch multiples of an EC2 instance in python you might do something like below:
# 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',
}),
This should create 5 instances with and id
like follows:
Upvotes: 1