Repository: ansible/ansible

Issue:
botocore.errorfactory.TargetGroupNotFoundException executing ec2_asg_facts
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
ec2_asg_facts

##### ANSIBLE VERSION
```
$ ansible --version
ansible 2.4.2.0
  config file = /Users/mitcholiver/dev/ansible/ansible.cfg
  configured module search path = [u'/Users/mitcholiver/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /Library/Python/2.7/site-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 2.7.10 (default, Feb  7 2017, 00:08:15) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)]
```

##### CONFIGURATION
```
$ ansible-config dump --only-changed
DEFAULT_FILTER_PLUGIN_PATH(/Users/mitcholiver/dev/ansible/ansible.cfg) = [u'/Users/mitcholiver/dev/ansible/plugins/filter_plugins']
DEFAULT_REMOTE_TMP(/Users/mitcholiver/dev/ansible/ansible.cfg) = /tmp
HOST_KEY_CHECKING(/Users/mitcholiver/dev/ansible/ansible.cfg) = False
```

##### OS / ENVIRONMENT
Controller OS: Mac OS 10.12.6

##### SUMMARY
Gathering facts for an EC2 Autoscaler Group that was assigned to a deleted application load balancer target group results in an exception.

##### STEPS TO REPRODUCE
Create an ELB target group (using elb_target_group module)
Create an ELB application load balancer (using elb_application_lb module)
Create EC2 Autoscaler group associated with above created target group (using ec2_asg module)
Delete above created application load balancer
Delete above created target group
Gather facts about above created autoscaler group (using ec2_asg_facts module)

```yaml
- elb_target_group:
  name: "test-target-group"
  protocol: "http"
  region: "us-east-1"
  port: 80
  vpc_id: {{ your_vpc_id_here }}
  state: "present"

- elb_application_lb:
  name: "test-alb"
  state: "present"
  region: "us-east-1"
  security_groups: "{{ your_sg_ids_here }}"
  subnets: "{{ your_subnet_ids_here }}"
  scheme: "internal"
  listeners:
    - Protocol: "HTTP"
      Port: 80
      DefaultActions:
        - Type: "forward"
          TargetGroupName: "test-target-group"

- elb_target_group_facts:
    names:
      - "test-target-group"
  register: target_groups

- ec2_asg:
  name: "test-asg"
  launch_config_name: "{{ your_lc_name_here }}"
  target_group_arns: ["{{ target_groups.target_groups[0].target_group_arn }}"]
  desired_capacity: 1
  min_size: 1
  max_size: 2
  health_check_type: "ELB"
  heath_check_period: 300
  state: "present"
  vpc_zone_identifier: "{{ your_subnet_ids_here }}"
  wait_timeout: 750

# Delete "test-alb" from the AWS console
# Delete "test-target-group" from the AWS console

- ec2_asg_facts:
  region: "us-east-1"
  name: "test-asg"
register: facts_of_asg
```

##### EXPECTED RESULTS
I expected to get the details about the specified Autoscaler group

##### ACTUAL RESULTS
```
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 && mkdir -p "` echo /tmp/ansible-tmp-1513285750.07-82275835320866 `" && echo ansible-tmp-1513285750.07-82275835320866="` echo /tmp/ansible-tmp-1513285750.07-82275835320866 `" ) && 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 && 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>&1 && 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
}
```



Discussion:
Files identified in the description:
* [lib/ansible/modules/cloud/amazon/ec2_asg_facts.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/amazon/ec2_asg_facts.py)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @willthames @wimnat
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->

Resolving patch:
diff --git a/lib/ansible/modules/cloud/amazon/ec2_asg_facts.py b/lib/ansible/modules/cloud/amazon/ec2_asg_facts.py
--- a/lib/ansible/modules/cloud/amazon/ec2_asg_facts.py
+++ b/lib/ansible/modules/cloud/amazon/ec2_asg_facts.py
@@ -370,9 +370,13 @@ def find_asgs(conn, module, name=None, tags=None):
                 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']]
+                    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)


Test patch: