
import boto3
import argparse

def share_ami_across_accounts(
    ami_id,
    target_account_ids,
    region_name='us-east-1'
):
    """
    Shares a specified Amazon Machine Image (AMI) with one or more target AWS accounts.

    Args:
        ami_id (str): The ID of the AMI to share (e.g., 'ami-0abcdef1234567890').
        target_account_ids (list): A list of AWS account IDs to share the AMI with.
        region_name (str): The AWS region where the AMI is located.
    """
    ec2_client = boto3.client('ec2', region_name=region_name)

    print(f"Starting AMI sharing process for AMI '{ami_id}' in region {region_name}...")

    # 1. Verify AMI exists
    print("\n>>> Step 1: Verifying AMI existence...")
    try:
        response = ec2_client.describe_images(
            ImageIds=[ami_id],
            Owners=['self'] # Ensure we only describe AMIs owned by this account
        )
        if not response['Images']:
            print(f"Error: AMI '{ami_id}' not found or not owned by this account. Exiting.")
            return
        print(f"   AMI '{ami_id}' found.")
    except Exception as e:
        print(f"Error verifying AMI '{ami_id}': {e}")
        return

    # 2. Modify AMI launch permissions to share with target accounts
    print(f"\n>>> Step 2: Modifying launch permissions for AMI '{ami_id}'...")
    try:
        for account_id in target_account_ids:
            print(f"   Sharing AMI '{ami_id}' with account: {account_id}")
            ec2_client.modify_image_attribute(
                ImageId=ami_id,
                LaunchPermission={
                    'Add': [
                        {'UserId': account_id}
                    ]
                }
            )
            print(f"   Successfully added launch permission for account {account_id}.")

    except Exception as e:
        print(f"Error sharing AMI '{ami_id}': {e}")
        return

    print("\nAMI sharing process completed.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Share an AMI across AWS accounts.")
    parser.add_argument("--ami-id", required=True, help="The ID of the AMI to share (e.g., 'ami-0abcdef1234567890').")
    parser.add_argument("--target-account-ids", nargs='+', required=True, help="A list of AWS account IDs to share the AMI with.")
    parser.add_argument("--region", default="us-east-1", help="AWS region where the AMI is located (default: us-east-1).")

    args = parser.parse_args()

    share_ami_across_accounts(
        ami_id=args.ami_id,
        target_account_ids=args.target_account_ids,
        region_name=args.region
    )
