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