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
gefragt vor 3 Monaten189 Aufrufe
3 Antworten
2
Akzeptierte Antwort

Thank you guys. Problem is here. Instead of

Owners=['self']

Should be:

Owners=['ACCOUNT_A']
profile picture
beantwortet vor 3 Monaten
profile picture
EXPERTE
überprüft vor 2 Monaten
profile pictureAWS
EXPERTE
überprüft vor 3 Monaten
2
profile pictureAWS
beantwortet vor 3 Monaten
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
EXPERTE
beantwortet vor 3 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen