Search code examples
amazon-ec2aws-lambdaboto3botocore

How do i make the program wait till the status of newly created EC2 state is running using boto3


am creating a ec2 instances by using below code

import boto3

# taking input via variables
region = input("Enter the region name where you want to create your ec2 instance: ")
#device_name = input("Enter the device name: ")
count = int(input("Enter how many instances you want to create: "))
ami = input("Enter the ami name: ")
tag_name = input("Enter the tag name: ")

# dict with ami values and its names

ami_values = {
    'Amazon Linux 2 AMI (HVM) - Kernel 5.10': 'ami-0568773882d492fc8',
    'Amazon Linux 2 AMI (HVM) - Kernel 4.14': 'ami-0ee5c62243ab25259'
}

ami_id = ami_values.get(ami)

aws_mgt_cons = boto3.session.Session(profile_name='myprofile')
ec2_mgt_cos_res = aws_mgt_cons.resource(service_name='ec2', region_name=region)

instances = ec2_mgt_cos_res.create_instances(
    ImageId=ami_id,
    # BlockDeviceMappings=[{
    #     'DeviceName': device_name,
    #     'Ebs': {
    #         'DeleteOnTermination': True,
    #         # 'VolumeSize': volume_size,
    #         # 'VolumeType': volume_type
    #     }
    # }],
    MinCount=1,
    MaxCount=count,
    InstanceType="t2.micro",
    KeyName="boto3-keypair",
    TagSpecifications=[
            {
                'ResourceType': 'instance',
                'Tags': [
                    {
                        'Key': 'Name',
                        'Value': tag_name
                    },
                ]
            },
        ],

)

Now how to wait the script until the state of newly created instances is running and need suggestions for same scenario if am creating more than one instances.

And is there any way to print the newly created instance id?


Solution

  • You need to use the Boto3's EC2 InstanceRunning Waiter. You can pass multiple instance IDs to that waiter if you are creating multiple instances.