4

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.....

6
  • What error, specifically do you see? Did you import boto3? Commented Sep 22, 2019 at 4:21
  • Yes import boto3 Error on lambda errorType": "AttributeError", "errorMessage": "'ec2.ServiceResource' object has no attribute 'create_instance Commented Sep 22, 2019 at 4:25
  • Then you've not posted a complete code example. Any answer will likely be a guess. Commented Sep 22, 2019 at 4:26
  • I have updated please check. Commented Sep 22, 2019 at 4:30
  • Try just running EC2 instance from Boto3, after getting a connection, proceed with next steps. Commented Sep 22, 2019 at 4:45

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

15 Comments

import boto3 import json region = 'us-east-2' ec2 = boto3.client('ec2') def lambda_handler(event, context): response = ec2.describe_images( Filters=[ { 'Name': 'description', 'Values': [ 'lambdaami', ] }, ], Owners=[ 'self' ] ) amis = sorted(response['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)
^^ Output Response: { "stackTrace": [ [ "/var/task/lambda_function.py", 21, "lambda_handler", "print amis[0]['ImageId']" ] ], "errorType": "IndexError", "errorMessage": "list index out of range
Please do not include your code as a comment but just modify your answer. And I modified my answer several times, please check it again.
Btw, what is the 'ImageId'? You didn't defined.
Now its working for me now. INSTANCE = ec2.create_instances(ImageId=IMAGEID, InstanceType='t2.micro', MinCount=1, MaxCount=1) Thanks a lot.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.