Repository: ansible/ansible

Issue:
elb_target_group fails with "KeyError: 'Port'" on target group creation
<!---
Verify first that your issue/request is not already reported on GitHub.
Also test if the latest release, and devel branch are affected too.
Always add information AFTER of these html comments.
-->

##### ISSUE TYPE
<!--- Pick one below and delete the rest -->
 - Bug Report


##### COMPONENT NAME
<!---
Insert below this comment the name of the module, plugin, task or feature.
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path
-->
elb_target_group

##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes below -->
```
ansible 2.5.0
  config file = /home/vagrant/repo/v2-ansible/ansible.cfg
  configured module search path = [u'/home/vagrant/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 2.7.13 (default, Nov 24 2017, 17:33:09) [GCC 6.3.0 20170516]

```

##### CONFIGURATION
<!---
If using Ansible 2.4 or above, paste the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).
-->
```
ANSIBLE_SSH_ARGS(/home/vagrant/repo/v2-ansible/ansible.cfg) = -C -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
DEFAULT_HOST_LIST(/home/vagrant/repo/v2-ansible/ansible.cfg) = [u'/home/vagrant/repo/v2-ansible/environment/test']
DEFAULT_REMOTE_USER(/home/vagrant/repo/v2-ansible/ansible.cfg) = {{ ansible_username | default('ansible') }}
HOST_KEY_CHECKING(/home/vagrant/repo/v2-ansible/ansible.cfg) = False
RETRY_FILES_ENABLED(/home/vagrant/repo/v2-ansible/ansible.cfg) = False

```
##### OS / ENVIRONMENT
<!---
Mention the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.
-->
Debian 9.3 
`Linux stretch 4.9.0-4-amd64 #1 SMP Debian 4.9.65-3 (2017-12-03) x86_64 GNU/Linux`

##### SUMMARY
<!--- Explain the problem briefly -->
elb_target_group module fails to create/update target group.

##### STEPS TO REPRODUCE
<!---
For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used.
-->
Create ELB target group and specify the `port` parameter with `state: present`.

<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: Create/update Foo ELB target group
  elb_target_group:
    name: "{{ foo_name }}"
    protocol: http
    port: "{{ foo_port }}"
    targets: "{{ foo_targets }}"
    tags:
      Name: "{{ foo_name }}"
    vpc_id: "{{ vpc.vpcs.0.id }}"
    region: "{{ ec2_region }}"
    state: present
```
my `{{ foo_targets }}` looks like:
```
ok: [localhost] => {
    "ansible_facts": {
        "foo_targets": [
            {
                "Id": "i-0ee19f7966cf30056"
            }, 
            {
                "Id": "i-094756058d65990da"
            }
        ]
    }, 
    "changed": false
}
```
<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
The ELB target group gets created. This was working in 2.4.3.

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->
MODULE FAILURE

<!--- Paste verbatim command output between quotes below -->
```
The full traceback is:
Traceback (most recent call last):
  File "/tmp/ansible_GCRxtK/ansible_module_elb_target_group.py", line 717, in <module>
    main()
  File "/tmp/ansible_GCRxtK/ansible_module_elb_target_group.py", line 712, in main
    create_or_update_target_group(connection, module)
  File "/tmp/ansible_GCRxtK/ansible_module_elb_target_group.py", line 505, in create_or_update_target_group
    instances_to_add.append({'Id': target['Id'], 'Port': int(target['Port'])})
KeyError: 'Port'

fatal: [localhost]: FAILED! => {
    "changed": false, 
    "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_GCRxtK/ansible_module_elb_target_group.py\", line 717, in <module>\n    main()\n  File \"/tmp/ansible_GCRxtK/ansible_module_elb_target_group.py\", line 712, in main\n    create_or_update_target_group(connection, module)\n  File \"/tmp/ansible_GCRxtK/ansible_module_elb_target_group.py\", line 505, in create_or_update_target_group\n    instances_to_add.append({'Id': target['Id'], 'Port': int(target['Port'])})\nKeyError: 'Port'\n", 
    "module_stdout": "", 
    "msg": "MODULE FAILURE", 
    "rc": 1
}

```



Discussion:
Files identified in the description:
* [lib/ansible/modules/cloud/amazon/elb_target_group.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/amazon/elb_target_group.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 --->
Can you confirm by running this code against 2.4.3 now? - nothing in the code appears to have changed in this area.

It looks like your `foo_targets` should both contain a `Port` key, and that's why you're getting this error.
Sorry, it looks like this was working in `2.4.1`, not `2.4.3` as I stated. It also fails in `2.4.2`, so it appears the changes are there.

I can try and append the `Port` key to my targets, but what about the module's `port` parameter then?
Certainly that's what the docs suggest should happen, you're right. 

This is definitely a bug - providing `Port` will offer a workaround until it's fixed, but we should restore 2.4.1 behaviour. Thanks for clarifying the version.

Resolving patch:
diff --git a/lib/ansible/modules/cloud/amazon/elb_target_group.py b/lib/ansible/modules/cloud/amazon/elb_target_group.py
--- a/lib/ansible/modules/cloud/amazon/elb_target_group.py
+++ b/lib/ansible/modules/cloud/amazon/elb_target_group.py
@@ -502,7 +502,7 @@ def create_or_update_target_group(connection, module):
                     instances_to_add = []
                     for target in params['Targets']:
                         if target['Id'] in add_instances:
-                            instances_to_add.append({'Id': target['Id'], 'Port': int(target['Port'])})
+                            instances_to_add.append({'Id': target['Id'], 'Port': int(target.get('Port', module.params.get('port')))})
 
                     changed = True
                     try:


Test patch: