{
  "output": "#!/usr/bin/env python3\nimport boto3\nimport csv\nimport time\nfrom botocore.exceptions import ClientError, ProfileNotFound\nfrom collections import defaultdict\nfrom aws_utils import setup_org_accounts_session, get_boto_session, export_to_sheets\n\n\n# The original script's helper function to get an AMI's human-readable name from its ID\ndef get_ami_name(ec2_client, ami_id):\n    if not ami_id:\n        return \"N/A - No AMI ID\"\n    if not ami_id.startswith(\"ami-\"):\n        return f\"Invalid AMI ID format\"\n    try:\n        image_info = ec2_client.describe_images(ImageIds=[ami_id])[\"Images\"]\n        if image_info:\n            return image_info[0].get(\"Name\", \"Unnamed AMI\")\n        return \"AMI not found\"\n    except ClientError as e:\n        return f\"AMI not accessible (Error: {e.response['Error']['Code']})\"\n    except Exception as e:\n        return f\"AMI lookup error: {e}\"\n\n\ndef get_asg_details(account_id, account_name, region, asg_client, ec2_client):\n    asg_info_list = []\n    paginator = asg_client.get_paginator(\"describe_auto_scaling_groups\")\n    try:\n        for page in paginator.paginate():\n            for asg in page[\"AutoScalingGroups\"]:\n                ami_id = \"N/A\"\n                template_type = \"None\"\n                template_name = \"None\"\n                template_version = \"N/A\"\n\n                lt_data = asg.get(\"LaunchTemplate\") or asg.get(\n                    \"MixedInstancesPolicy\", {}\n                ).get(\"LaunchTemplate\")\n                if lt_data:\n                    template_type = \"LaunchTemplate\"\n                    template_id = lt_data.get(\"LaunchTemplateId\")\n                    template_name = lt_data.get(\"LaunchTemplateName\")\n                    template_version = lt_data.get(\"Version\") or \"$Default\"\n                    if template_id or template_name:\n                        try:\n                            lt_lookup_args = {\"Versions\": [template_version]}\n                            if template_id:\n                                lt_lookup_args[\"LaunchTemplateId\"] = template_id\n                            elif template_name:\n                                lt_lookup_args[\"LaunchTemplateName\"] = template_name\n\n                            lt_versions = ec2_client.describe_launch_template_versions(\n                                **lt_lookup_args\n                            )[\"LaunchTemplateVersions\"]\n                            if lt_versions:\n                                ami_id = lt_versions[0][\"LaunchTemplateData\"].get(\n                                    \"ImageId\", \"AMI ID not specified in LT\"\n                                )\n                        except ClientError as e:\n                            ami_id = f\"LT lookup error: {e.response['Error']['Code']}\"\n                        except Exception as e:\n                            ami_id = f\"LT processing error: {e}\"\n\n                elif asg.get(\"LaunchConfigurationName\"):\n                    lc_name = asg[\"LaunchConfigurationName\"]\n                    template_type = \"LaunchConfiguration\"\n                    template_name = lc_name\n                    template_version = \"Latest\"\n                    try:\n                        lc_response = asg_client.describe_launch_configurations(\n                            LaunchConfigurationNames=[lc_name]\n                        )[\"LaunchConfigurations\"]\n                        if lc_response:\n                            ami_id = lc_response[0].get(\n                                \"ImageId\", \"AMI ID not specified in LC\"\n                            )\n                    except ClientError as e:\n                        ami_id = f\"LC lookup error: {e.response['Error']['Code']}\"\n                    except Exception as e:\n                        ami_id = f\"LC processing error: {e}\"\n\n                asg_info_list.append(\n                    {\n                        \"AccountName\": account_name,\n                        \"AccountID\": account_id,\n                        \"Region\": region,\n                        \"ASG_Name\": asg[\"AutoScalingGroupName\"],\n                        \"Template_Type\": template_type,\n                        \"Template_Name\": template_name,\n                        \"Template_Version\": template_version,\n                        \"AMI_ID\": ami_id,\n                        \"AMI_Name\": get_ami_name(ec2_client, ami_id),\n                    }\n                )\n    except ClientError as e:\n        print(f\"  -> Error listing ASGs in {region}: {e}\")\n    return asg_info_list\n\n\ndef main():\n    get_boto_session()\n    all_asg_info = []\n    regions_to_check = [\"eu-west-1\", \"eu-west-2\"]\n    rows_for_sheets = []\n    csv_filepath = \"autoscaling_group_ami_template_info.csv\"\n\n    fieldnames = [\n        \"AccountName\",\n        \"AccountID\",\n        \"Region\",\n        \"ASG_Name\",\n        \"Template_Type\",\n        \"Template_Name\",\n        \"Template_Version\",\n        \"AMI_ID\",\n        \"AMI_Name\",\n    ]\n\n    with open(csv_filepath, mode=\"w\", newline=\"\") as csvfile:\n        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n        writer.writeheader()\n\n        print(\"\\nIterating through accounts to collect ASG data...\")\n        for account, profile_name in setup_org_accounts_session():\n            account_id = account[\"Id\"]\n            account_name = account[\"Name\"]\n            print(f\"\\n--- Checking Account: {account_name} (ID: {account_id}) ---\")\n\n            try:\n                boto3.setup_default_session(profile_name=profile_name)\n                for region in regions_to_check:\n                    try:\n                        asg_client = boto3.client(\"autoscaling\", region_name=region)\n                        ec2_client = boto3.client(\"ec2\", region_name=region)\n                        asg_data = get_asg_details(\n                            account_id, account_name, region, asg_client, ec2_client\n                        )\n\n                        for asg in asg_data:\n                            all_asg_info.append(asg)\n                            writer.writerow(asg)\n                            rows_for_sheets.append(list(asg.values()))\n                            print(\n                                f\"  [FOUND] ASG: {asg['ASG_Name']}, AMI ID: {asg['AMI_ID']}\"\n                            )\n                    except ClientError as e:\n                        print(f\"  -> Error in {region}: {e}\")\n                    time.sleep(0.5)\n            except (ClientError, ProfileNotFound) as e:\n                print(f\"  -> Error setting up profile '{profile_name}': {e}\")\n\n    print(f\"\\nTotal ASGs found: {len(all_asg_info)}\")\n    print(f\"CSV file '{csv_filepath}' generated successfully.\")\n    export_to_sheets(\"aws-asg-lt-ami\", fieldnames, rows_for_sheets)\n\n\nif __name__ == \"__main__\":\n    main()\n"
}