Access private image by Lambda - image not found error

0

Hi,

I have EC2 builder that builds EC2 in Account A. Then this image appears to be OWNED BY ME. Lambda below works fine. I share this image with account B. Then this image appears to be PRIVATE. But the same lambda on account B gets me an error:

{
  "statusCode": 400,
  "body": "No AMI found with the specified name."
}

Lambda, all lambdas have all ec2 permissions.

import boto3

def lambda_handler(event, context):
    # Replace 'YourAMIName' with the actual AMI name you want to use
    ami_name = 'some_image_name'

    # EC2 client
    ec2_client = boto3.client('ec2')

    # Get the latest AMI with the specified name
    amis = ec2_client.describe_images(Filters=[{'Name': 'name', 'Values': [ami_name]}], Owners=['self'])
    
    if not amis['Images']:
        return {
            'statusCode': 400,
            'body': 'No AMI found with the specified name.'
        }

    # Get the latest AMI ID
    latest_ami_id = sorted(amis['Images'], key=lambda x: x['CreationDate'], reverse=True)[0]['ImageId']

    # Launch EC2 instance with the latest AMI
    instance = ec2_client.run_instances(
        ImageId=latest_ami_id,
        MinCount=1,
        MaxCount=1,
        InstanceType='t2.micro',  # Replace with your desired instance type
        KeyName='ssh-2024'  # Replace with your key pair name
    )

    instance_id = instance['Instances'][0]['InstanceId']

    return {
        'statusCode': 200,
        'body': f'EC2 instance {instance_id} launched with AMI {latest_ami_id}.'
    }

profile picture
asked 3 months ago179 views
3 Answers
2
Accepted Answer

Thank you guys. Problem is here. Instead of

Owners=['self']

Should be:

Owners=['ACCOUNT_A']
profile picture
answered 3 months ago
profile picture
EXPERT
reviewed a month ago
profile pictureAWS
EXPERT
reviewed 3 months ago
2
profile pictureAWS
answered 3 months ago
2

Hi,

You may want to try the code of this Lambda out of the Lambda environment (i.e. as a regular Python script) in account B to see what's happening and if you get more explicit error messages.

Best,

Didier

profile pictureAWS
EXPERT
answered 3 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions