{
  "output": "Successfully created and wrote to new file: /Users/bob/git/dxw/aws-stuff/audits/asg.py. Here is the updated code:\nimport boto3\nimport csv\nimport time\nfrom botocore.exceptions import ClientError, ProfileNotFound\nfrom aws_utils import setup_org_accounts_session, get_boto_session, export_to_sheets\n\ndef get_ami_name(ec2_client, ami_id):\n    if not ami_id or not ami_id.startswith(\"ami-\"):\n        return \"N/A\"\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:\n        return \"AMI not accessible\"\n    except Exception:\n        return \"AMI lookup error\"\n\ndef fetch_asg_details(asg_client, ec2_client, account_id, account_name, region):\n    \"\"\"\n    Fetches ASG details for a specific region and account.\n    Returns a list of dicts.\n    \"\"\"\n    asg_info_list = []\n    try:\n        paginator = asg_client.get_paginator(\"describe_auto_scaling_groups\")\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(\"MixedInstancesPolicy\", {}).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                    try:\n                        args = {\"Versions\": [template_version]}\n                        if template_id: args[\"LaunchTemplateId\"] = template_id\n                        elif template_name: args[\"LaunchTemplateName\"] = template_name\n                        \n                        lt_versions = ec2_client.describe_launch_template_versions(**args)[\"LaunchTemplateVersions\"]\n                        if lt_versions:\n                            ami_id = lt_versions[0][\"LaunchTemplateData\"].get(\"ImageId\", \"N/A\")\n                    except ClientError:\n                        ami_id = \"LT lookup error\"\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(LaunchConfigurationNames=[lc_name])[\"LaunchConfigurations\"]\n                        if lc_response:\n                            ami_id = lc_response[0].get(\"ImageId\", \"N/A\")\n                    except ClientError:\n                        ami_id = \"LC lookup error\"\n\n                asg_info_list.append({\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    except ClientError as e:\n        print(f\"Error fetching ASGs: {e}\")\n        \n    return asg_info_list\n\ndef run():\n    get_boto_session()\n    regions = [\"eu-west-1\", \"eu-west-2\"]\n    all_rows = []\n    fieldnames = [\"AccountName\", \"AccountID\", \"Region\", \"ASG_Name\", \"Template_Type\", \"Template_Name\", \"Template_Version\", \"AMI_ID\", \"AMI_Name\"]\n\n    for account, profile_name in setup_org_accounts_session():\n        account_id = account[\"Id\"]\n        account_name = account[\"Name\"]\n        try:\n            account_session = boto3.Session(profile_name=profile_name)\n            for region in regions:\n                asg_client = account_session.client(\"autoscaling\", region_name=region)\n                ec2_client = account_session.client(\"ec2\", region_name=region)\n                asg_data = fetch_asg_details(asg_client, ec2_client, account_id, account_name, region)\n                all_rows.extend(asg_data)\n                for asg in asg_data:\n                    print(f\"  [FOUND] {account_name} ({region}) ASG: {asg['ASG_Name']}, AMI: {asg['AMI_ID']}\")\n                time.sleep(0.1)\n        except (ClientError, ProfileNotFound) as e:\n            print(f\"Error accessing account {account_name}: {e}\")\n\n    # Write to CSV\n    csv_filepath = \"autoscaling_group_ami_template_info.csv\"\n    with open(csv_filepath, mode=\"w\", newline=\"\") as csvfile:\n        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n        writer.writeheader()\n        for row in all_rows:\n            writer.writerow(row)\n            \n    print(f\"\\nTotal ASGs found: {len(all_rows)}\")\n    export_to_sheets(\"aws-asg-lt-ami\", fieldnames, [list(r.values()) for r in all_rows])\n\nif __name__ == \"__main__\":\n    run()\n"
}