while trying launch instance from python function instance not launching but not getting python syntax error.
import boto3
ec2 = boto3.resource('ec2', region_name='us-east-2')
def lambda_handler(event, context):
images = ec2.images.filter(
Filters=[
{
'Name': 'description',
'Values': [
'lambdaami',
]
},
],
Owners=[
'self'
])
amis = sorted(images, key=lambda x: x['CreationDate'], reverse=True)
print amis[0]['ImageId']
INSTANCE = ec2.create_instance(ImageId='ImageId', InstanceType='t2.micro', MinCount=1, MaxCount=1)
print(INSTANCE[0].id)
Kindly help.....
You have defined ec2 twice,
ec2 = boto3.client('ec2')
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
and even again for client. Please use only one client
or resource
. Furthermore, there is no create_instance
and it seems a typo of a function create_instances
for resource.
Here is an example:
import boto3
ec2 = boto3.resource('ec2', region_name='us-east-2')
def lambda_handler(event, context):
images = ec2.images.filter(
Filters=[
{
'Name': 'description',
'Values': [
'lambdaami',
]
},
],
Owners=[
'self'
])
AMI = sorted(images, key=lambda x: x.creation_date, reverse=True)
IMAGEID = AMI[0].image_id
INSTANCE = ec2.create_instances(ImageId=IMAGEID, InstanceType='t2.micro', MinCount=1, MaxCount=1)
print(INSTANCE[0].image_id)
To make an image from an instance and wait for that,
import boto3
import time
ec2 = boto3.resource('ec2', region_name='us-east-2')
def lambda_handler(event, context):
instanceId = 'What instance id you want to create an image'
response = ec2.Instance(instanceId).create_image(Name='Image Name')
imageId = response.image_id
while(ec2.Image(imageId).state != 'available'):
time.sleep(5) # Wait for 5 seconds for each try.
# Since we know the imageId, no needs for other codes
instance = ec2.create_instances(ImageId=imageId, InstanceType='t2.micro', MinCount=1, MaxCount=1)
print(instance[0].image_id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With