# Buggy code
def get_portchannel(module, netcfg=None):
    command = "show port-channel summary"
    portchannel = {}
    portchannel_table = {}
    members = []

    try:
        body = execute_show_command(command, module)[0]
        pc_table = body["TABLE_channel"]["ROW_channel"]

        if isinstance(pc_table, dict):
            pc_table = [pc_table]

        for pc in pc_table:
            if pc["group"] == module.params["group"]:
                portchannel_table = pc
    except (KeyError, AttributeError, TypeError, IndexError):
        return {}

    if portchannel_table:
        portchannel["group"] = portchannel_table["group"]
        protocol = portchannel_table["prtcl"]
        members_list = get_portchannel_members(portchannel_table)

        if isinstance(members_list, dict):
            members_list = [members_list]

        member_dictionary = {}
        for each_member in members_list:
            interface = each_member["port"]
            members.append(interface)

            pc_member = {}
            pc_member["status"] = str(each_member["port-status"])
            pc_member["mode"] = get_portchannel_mode(
                interface, protocol, module, netcfg
            )

            member_dictionary[interface] = pc_member
            portchannel["members"] = members
            portchannel["members_detail"] = member_dictionary

        # Ensure each member have the same mode.
        modes = set()
        for each, value in member_dictionary.items():
            modes.update([value["mode"]])
        if len(modes) == 1:
            portchannel["mode"] = value["mode"]
        else:
            portchannel["mode"] = "unknown"
    return portchannel


# Traceback (KeyError)
TASK [nxos_portchannel : Check Idempotence] ***************************************************************************************************************
task path: /root/agents-ci/ansible/test/integration/targets/nxos_portchannel/tests/cli/sanity.yaml:53
<n5k-xxx.example.com> connection transport is cli
<n5k-xxx.example.com> using connection plugin network_cli
<n5k-xxx.example.com> socket_path: /root/.ansible/pc/1b4e3e6315
Using module file /root/agents-ci/ansible/lib/ansible/modules/network/nxos/nxos_portchannel.py
<n5k-xxx.example.com> ESTABLISH LOCAL CONNECTION FOR USER: root
<n5k-xxx.example.com> EXEC /bin/sh -c 'echo ~ &amp;&amp; sleep 0'
<n5k-xxx.example.com> EXEC /bin/sh -c '( umask 77 &amp;&amp; mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1506024860.42-117137983875574 `" &amp;&amp; echo ansible-tmp-1506024860.42-117137983875574="` echo /root/.ansible/tmp/ansible-tmp-1506024860.42-117137983875574 `" ) &amp;&amp; sleep 0'
<n5k-xxx.example.com> PUT /tmp/tmppVH_PM TO /root/.ansible/tmp/ansible-tmp-1506024860.42-117137983875574/nxos_portchannel.py
<n5k-xxx.example.com> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp-1506024860.42-117137983875574/ /root/.ansible/tmp/ansible-tmp-1506024860.42-117137983875574/nxos_portchannel.py &amp;&amp; sleep 0'
<n5k-xxx.example.com> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-1506024860.42-117137983875574/nxos_portchannel.py; rm -rf "/root/.ansible/tmp/ansible-tmp-1506024860.42-117137983875574/" > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_uvmlWf/ansible_module_nxos_portchannel.py", line 498, in <module>
main()
File "/tmp/ansible_uvmlWf/ansible_module_nxos_portchannel.py", line 481, in main
commands = state_present(module, existing, proposed, interface_exist, force, warnings)
File "/tmp/ansible_uvmlWf/ansible_module_nxos_portchannel.py", line 408, in state_present
command = get_commands_to_add_members(proposed, existing, force, module)
File "/tmp/ansible_uvmlWf/ansible_module_nxos_portchannel.py", line 300, in get_commands_to_add_members
existing['group'], force, proposed['mode']))
KeyError: 'group'
FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_uvmlWf/ansible_module_nxos_portchannel.py\", line 498, in <module>\n    main()\n  File \"/tmp/ansible_uvmlWf/ansible_module_nxos_portchannel.py\", line 481, in main\n    commands = state_present(module, existing, proposed, interface_exist, force, warnings)\n  File \"/tmp/ansible_uvmlWf/ansible_module_nxos_portchannel.py\", line 408, in state_present\n    command = get_commands_to_add_members(proposed, existing, force, module)\n  File \"/tmp/ansible_uvmlWf/ansible_module_nxos_portchannel.py\", line 300, in get_commands_to_add_members\n    existing['group'], force, proposed['mode']))\nKeyError: 'group'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def get_portchannel(module, netcfg=None):
    command = "show port-channel summary"
    portchannel = {}
    portchannel_table = {}
    members = []

    try:
        body = execute_show_command(command, module)[0]
        pc_table = body["TABLE_channel"]["ROW_channel"]

        if isinstance(pc_table, dict):
            pc_table = [pc_table]

        for pc in pc_table:
            if pc["group"] == module.params["group"]:
                portchannel_table = pc
            elif module.params["group"].isdigit() and pc["group"] == int(
                module.params["group"]
            ):
                portchannel_table = pc
    except (KeyError, AttributeError, TypeError, IndexError):
        return {}

    if portchannel_table:
        portchannel["group"] = portchannel_table["group"]
        protocol = portchannel_table["prtcl"]
        members_list = get_portchannel_members(portchannel_table)

        if isinstance(members_list, dict):
            members_list = [members_list]

        member_dictionary = {}
        for each_member in members_list:
            interface = each_member["port"]
            members.append(interface)

            pc_member = {}
            pc_member["status"] = str(each_member["port-status"])
            pc_member["mode"] = get_portchannel_mode(
                interface, protocol, module, netcfg
            )

            member_dictionary[interface] = pc_member
            portchannel["members"] = members
            portchannel["members_detail"] = member_dictionary

        # Ensure each member have the same mode.
        modes = set()
        for each, value in member_dictionary.items():
            modes.update([value["mode"]])
        if len(modes) == 1:
            portchannel["mode"] = value["mode"]
        else:
            portchannel["mode"] = "unknown"
    return portchannel