# Buggy code
def find_asgs(conn, module, name=None, tags=None):
    """
    Args:
        conn (boto3.AutoScaling.Client): Valid Boto3 ASG client.
        name (str): Optional name of the ASG you are looking for.
        tags (dict): Optional dictionary of tags and values to search for.

    Basic Usage:
        >>> name = 'public-webapp-production'
        >>> tags = { 'env': 'production' }
        >>> conn = boto3.client('autoscaling', region_name='us-west-2')
        >>> results = find_asgs(name, conn)

    Returns:
        List
        [
            {
                "auto_scaling_group_arn": (
                    "arn:aws:autoscaling:us-west-2:275977225706:autoScalingGroup:58abc686-9783-4528-b338-3ad6f1cbbbaf:"
                    "autoScalingGroupName/public-webapp-production"
                ),
                "auto_scaling_group_name": "public-webapp-production",
                "availability_zones": ["us-west-2c", "us-west-2b", "us-west-2a"],
                "created_time": "2016-02-02T23:28:42.481000+00:00",
                "default_cooldown": 300,
                "desired_capacity": 2,
                "enabled_metrics": [],
                "health_check_grace_period": 300,
                "health_check_type": "ELB",
                "instances":
                [
                    {
                        "availability_zone": "us-west-2c",
                        "health_status": "Healthy",
                        "instance_id": "i-047a12cb",
                        "launch_configuration_name": "public-webapp-production-1",
                        "lifecycle_state": "InService",
                        "protected_from_scale_in": false
                    },
                    {
                        "availability_zone": "us-west-2a",
                        "health_status": "Healthy",
                        "instance_id": "i-7a29df2c",
                        "launch_configuration_name": "public-webapp-production-1",
                        "lifecycle_state": "InService",
                        "protected_from_scale_in": false
                    }
                ],
                "launch_config_name": "public-webapp-production-1",
                "launch_configuration_name": "public-webapp-production-1",
                "load_balancer_names": ["public-webapp-production-lb"],
                "max_size": 4,
                "min_size": 2,
                "new_instances_protected_from_scale_in": false,
                "placement_group": None,
                "status": None,
                "suspended_processes": [],
                "tags":
                [
                    {
                        "key": "Name",
                        "propagate_at_launch": true,
                        "resource_id": "public-webapp-production",
                        "resource_type": "auto-scaling-group",
                        "value": "public-webapp-production"
                    },
                    {
                        "key": "env",
                        "propagate_at_launch": true,
                        "resource_id": "public-webapp-production",
                        "resource_type": "auto-scaling-group",
                        "value": "production"
                    }
                ],
                "target_group_names": [],
                "target_group_arns": [],
                "termination_policies":
                [
                    "Default"
                ],
                "vpc_zone_identifier":
                [
                    "subnet-a1b1c1d1",
                    "subnet-a2b2c2d2",
                    "subnet-a3b3c3d3"
                ]
            }
        ]
    """

    try:
        asgs_paginator = conn.get_paginator("describe_auto_scaling_groups")
        asgs = asgs_paginator.paginate().build_full_result()
    except ClientError as e:
        module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response))

    if not asgs:
        return asgs
    try:
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(
            module, boto3=True
        )
        elbv2 = boto3_conn(
            module,
            conn_type="client",
            resource="elbv2",
            region=region,
            endpoint=ec2_url,
            **aws_connect_kwargs,
        )
    except ClientError as e:
        # This is nice to have, not essential
        elbv2 = None
    matched_asgs = []

    if name is not None:
        # if the user didn't specify a name
        name_prog = re.compile(r"^" + name)

    for asg in asgs["AutoScalingGroups"]:
        if name:
            matched_name = name_prog.search(asg["AutoScalingGroupName"])
        else:
            matched_name = True

        if tags:
            matched_tags = match_asg_tags(tags, asg)
        else:
            matched_tags = True

        if matched_name and matched_tags:
            asg = camel_dict_to_snake_dict(asg)
            # compatibility with ec2_asg module
            asg["launch_config_name"] = asg["launch_configuration_name"]
            # workaround for https://github.com/ansible/ansible/pull/25015
            if "target_group_ar_ns" in asg:
                asg["target_group_arns"] = asg["target_group_ar_ns"]
                del asg["target_group_ar_ns"]
            if asg.get("target_group_arns"):
                if elbv2:
                    tg_paginator = elbv2.get_paginator("describe_target_groups")
                    tg_result = tg_paginator.paginate(
                        TargetGroupArns=asg["target_group_arns"]
                    ).build_full_result()
                    asg["target_group_names"] = [
                        tg["TargetGroupName"] for tg in tg_result["TargetGroups"]
                    ]
            else:
                asg["target_group_names"] = []
            matched_asgs.append(asg)

    return matched_asgs


# Traceback (botocore.errorfactory.TargetGroupNotFoundException)
Using module file /Library/Python/2.7/site-packages/ansible/modules/cloud/amazon/ec2_asg_facts.py
<127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: mitcholiver
<127.0.0.1> EXEC /bin/sh -c '( umask 77 &amp;&amp; mkdir -p "` echo /tmp/ansible-tmp-1513285750.07-82275835320866 `" &amp;&amp; echo ansible-tmp-1513285750.07-82275835320866="` echo /tmp/ansible-tmp-1513285750.07-82275835320866 `" ) &amp;&amp; sleep 0'
<127.0.0.1> PUT /var/folders/gt/81m_y83x7jz92n4y0402l5mm0000gn/T/tmpRwsrWN TO /tmp/ansible-tmp-1513285750.07-82275835320866/ec2_asg_facts.py
<127.0.0.1> EXEC /bin/sh -c 'chmod u+x /tmp/ansible-tmp-1513285750.07-82275835320866/ /tmp/ansible-tmp-1513285750.07-82275835320866/ec2_asg_facts.py &amp;&amp; sleep 0'
<127.0.0.1> EXEC /bin/sh -c '/usr/bin/python /tmp/ansible-tmp-1513285750.07-82275835320866/ec2_asg_facts.py; rm -rf "/tmp/ansible-tmp-1513285750.07-82275835320866/" > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/var/folders/gt/81m_y83x7jz92n4y0402l5mm0000gn/T/ansible_mg0gVQ/ansible_module_ec2_asg_facts.py", line 410, in <module>
main()
File "/var/folders/gt/81m_y83x7jz92n4y0402l5mm0000gn/T/ansible_mg0gVQ/ansible_module_ec2_asg_facts.py", line 405, in main
results = find_asgs(autoscaling, module, name=asg_name, tags=asg_tags)
File "/var/folders/gt/81m_y83x7jz92n4y0402l5mm0000gn/T/ansible_mg0gVQ/ansible_module_ec2_asg_facts.py", line 373, in find_asgs
tg_result = tg_paginator.paginate(TargetGroupArns=asg['target_group_arns']).build_full_result()
File "/Library/Python/2.7/site-packages/botocore/paginate.py", line 449, in build_full_result
for response in self:
File "/Library/Python/2.7/site-packages/botocore/paginate.py", line 255, in __iter__
response = self._make_request(current_kwargs)
File "/Library/Python/2.7/site-packages/botocore/paginate.py", line 332, in _make_request
return self._method(**current_kwargs)
File "/Library/Python/2.7/site-packages/botocore/client.py", line 317, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/Library/Python/2.7/site-packages/botocore/client.py", line 615, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.TargetGroupNotFoundException: An error occurred (TargetGroupNotFound) when calling the DescribeTargetGroups operation: One or more target groups not found

fatal: [localhost]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/gt/81m_y83x7jz92n4y0402l5mm0000gn/T/ansible_mg0gVQ/ansible_module_ec2_asg_facts.py\", line 410, in <module>\n    main()\n  File \"/var/folders/gt/81m_y83x7jz92n4y0402l5mm0000gn/T/ansible_mg0gVQ/ansible_module_ec2_asg_facts.py\", line 405, in main\n    results = find_asgs(autoscaling, module, name=asg_name, tags=asg_tags)\n  File \"/var/folders/gt/81m_y83x7jz92n4y0402l5mm0000gn/T/ansible_mg0gVQ/ansible_module_ec2_asg_facts.py\", line 373, in find_asgs\n    tg_result = tg_paginator.paginate(TargetGroupArns=asg['target_group_arns']).build_full_result()\n  File \"/Library/Python/2.7/site-packages/botocore/paginate.py\", line 449, in build_full_result\n    for response in self:\n  File \"/Library/Python/2.7/site-packages/botocore/paginate.py\", line 255, in __iter__\n    response = self._make_request(current_kwargs)\n  File \"/Library/Python/2.7/site-packages/botocore/paginate.py\", line 332, in _make_request\n    return self._method(**current_kwargs)\n  File \"/Library/Python/2.7/site-packages/botocore/client.py\", line 317, in _api_call\n    return self._make_api_call(operation_name, kwargs)\n  File \"/Library/Python/2.7/site-packages/botocore/client.py\", line 615, in _make_api_call\n    raise error_class(parsed_response, operation_name)\nbotocore.errorfactory.TargetGroupNotFoundException: An error occurred (TargetGroupNotFound) when calling the DescribeTargetGroups operation: One or more target groups not found\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def find_asgs(conn, module, name=None, tags=None):
    """
    Args:
        conn (boto3.AutoScaling.Client): Valid Boto3 ASG client.
        name (str): Optional name of the ASG you are looking for.
        tags (dict): Optional dictionary of tags and values to search for.

    Basic Usage:
        >>> name = 'public-webapp-production'
        >>> tags = { 'env': 'production' }
        >>> conn = boto3.client('autoscaling', region_name='us-west-2')
        >>> results = find_asgs(name, conn)

    Returns:
        List
        [
            {
                "auto_scaling_group_arn": (
                    "arn:aws:autoscaling:us-west-2:275977225706:autoScalingGroup:58abc686-9783-4528-b338-3ad6f1cbbbaf:"
                    "autoScalingGroupName/public-webapp-production"
                ),
                "auto_scaling_group_name": "public-webapp-production",
                "availability_zones": ["us-west-2c", "us-west-2b", "us-west-2a"],
                "created_time": "2016-02-02T23:28:42.481000+00:00",
                "default_cooldown": 300,
                "desired_capacity": 2,
                "enabled_metrics": [],
                "health_check_grace_period": 300,
                "health_check_type": "ELB",
                "instances":
                [
                    {
                        "availability_zone": "us-west-2c",
                        "health_status": "Healthy",
                        "instance_id": "i-047a12cb",
                        "launch_configuration_name": "public-webapp-production-1",
                        "lifecycle_state": "InService",
                        "protected_from_scale_in": false
                    },
                    {
                        "availability_zone": "us-west-2a",
                        "health_status": "Healthy",
                        "instance_id": "i-7a29df2c",
                        "launch_configuration_name": "public-webapp-production-1",
                        "lifecycle_state": "InService",
                        "protected_from_scale_in": false
                    }
                ],
                "launch_config_name": "public-webapp-production-1",
                "launch_configuration_name": "public-webapp-production-1",
                "load_balancer_names": ["public-webapp-production-lb"],
                "max_size": 4,
                "min_size": 2,
                "new_instances_protected_from_scale_in": false,
                "placement_group": None,
                "status": None,
                "suspended_processes": [],
                "tags":
                [
                    {
                        "key": "Name",
                        "propagate_at_launch": true,
                        "resource_id": "public-webapp-production",
                        "resource_type": "auto-scaling-group",
                        "value": "public-webapp-production"
                    },
                    {
                        "key": "env",
                        "propagate_at_launch": true,
                        "resource_id": "public-webapp-production",
                        "resource_type": "auto-scaling-group",
                        "value": "production"
                    }
                ],
                "target_group_names": [],
                "target_group_arns": [],
                "termination_policies":
                [
                    "Default"
                ],
                "vpc_zone_identifier":
                [
                    "subnet-a1b1c1d1",
                    "subnet-a2b2c2d2",
                    "subnet-a3b3c3d3"
                ]
            }
        ]
    """

    try:
        asgs_paginator = conn.get_paginator("describe_auto_scaling_groups")
        asgs = asgs_paginator.paginate().build_full_result()
    except ClientError as e:
        module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response))

    if not asgs:
        return asgs
    try:
        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(
            module, boto3=True
        )
        elbv2 = boto3_conn(
            module,
            conn_type="client",
            resource="elbv2",
            region=region,
            endpoint=ec2_url,
            **aws_connect_kwargs,
        )
    except ClientError as e:
        # This is nice to have, not essential
        elbv2 = None
    matched_asgs = []

    if name is not None:
        # if the user didn't specify a name
        name_prog = re.compile(r"^" + name)

    for asg in asgs["AutoScalingGroups"]:
        if name:
            matched_name = name_prog.search(asg["AutoScalingGroupName"])
        else:
            matched_name = True

        if tags:
            matched_tags = match_asg_tags(tags, asg)
        else:
            matched_tags = True

        if matched_name and matched_tags:
            asg = camel_dict_to_snake_dict(asg)
            # compatibility with ec2_asg module
            asg["launch_config_name"] = asg["launch_configuration_name"]
            # workaround for https://github.com/ansible/ansible/pull/25015
            if "target_group_ar_ns" in asg:
                asg["target_group_arns"] = asg["target_group_ar_ns"]
                del asg["target_group_ar_ns"]
            if asg.get("target_group_arns"):
                if elbv2:
                    try:
                        tg_paginator = elbv2.get_paginator("describe_target_groups")
                        tg_result = tg_paginator.paginate(
                            TargetGroupArns=asg["target_group_arns"]
                        ).build_full_result()
                        asg["target_group_names"] = [
                            tg["TargetGroupName"] for tg in tg_result["TargetGroups"]
                        ]
                    except ClientError as e:
                        if e.response["Error"]["Code"] == "TargetGroupNotFound":
                            asg["target_group_names"] = []
            else:
                asg["target_group_names"] = []
            matched_asgs.append(asg)

    return matched_asgs