'AWS Lambda create EC2 and associate EIP

I am trying to deploy an EC2 instance and associate an EIP to it, but I am getting and error when trying to associate the EIP because the instance is not running. This is my code:

import boto3
from botocore.exceptions import ClientError
 
AMI = 'ami-0bf84....'    
INSTANCE_TYPE = 't2.micro'
KEY_NAME = 'EC2company'
SUBNET_ID = 'subnet-065....'
 
 
ec2 = boto3.client('ec2')
 
def lambda_handler(event, context):
 
    instance = ec2.run_instances(
        ImageId=AMI,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_NAME,
        SubnetId=SUBNET_ID,
        MaxCount=1,
        MinCount=1
    )
        
    waiter = ec2.get_waiter('instance_running')
    
    try:
        response = ec2.associate_address(
            AllocationId='eipalloc-0bc.....',
            InstanceId=instance['Instances'][0]['InstanceId'],
        )
        print(response)
    except ClientError as e:
        print(e)

I suppose that the issue is related to be applying the waiter in the wrong way, and not sure how i should do it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source