# Buggy code
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            description=dict(),
            inventory=dict(required=True),
            variables=dict(),
            credential=dict(),
            source=dict(
                choices=[
                    "manual",
                    "file",
                    "ec2",
                    "rax",
                    "vmware",
                    "gce",
                    "azure",
                    "azure_rm",
                    "openstack",
                    "satellite6",
                    "cloudforms",
                    "custom",
                ],
                default="manual",
            ),
            source_regions=dict(),
            source_vars=dict(),
            instance_filters=dict(),
            group_by=dict(),
            source_script=dict(),
            overwrite=dict(type="bool", default=False),
            overwrite_vars=dict(),
            update_on_launch=dict(type="bool", default=False),
            state=dict(choices=["present", "absent"], default="present"),
        )
    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

    if not HAS_TOWER_CLI:
        module.fail_json(msg="ansible-tower-cli required for this module")

    name = module.params.get("name")
    inventory = module.params.get("inventory")
    credential = module.params.get("credential")
    state = module.params.get("state")

    variables = module.params.get("variables")
    if variables:
        if variables.startswith("@"):
            filename = os.path.expanduser(variables[1:])
            variables = module.contents_from_file(filename)

    json_output = {"group": name, "state": state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        group = tower_cli.get_resource("group")
        try:
            params = module.params.copy()
            params["create_on_missing"] = True
            params["variables"] = variables

            inv_res = tower_cli.get_resource("inventory")
            inv = inv_res.get(name=inventory)
            params["inventory"] = inv["id"]

            if credential:
                cred_res = tower_cli.get_resource("credential")
                cred = cred_res.get(name=credential)
                params["credential"] = cred["id"]

            if state == "present":
                result = group.modify(**params)
                json_output["id"] = result["id"]
            elif state == "absent":
                result = group.delete(**params)
        except exc.NotFound as excinfo:
            module.fail_json(
                msg="Failed to update the group, inventory not found: {0}".format(
                    excinfo
                ),
                changed=False,
            )
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(
                msg="Failed to update the group: {0}".format(excinfo), changed=False
            )

    json_output["changed"] = result["changed"]
    module.exit_json(**json_output)


# Traceback (tower_cli.exceptions.BadRequest)
TASK [tower-manage : Add user to team] *************************************************************************
task path: /home/ikanse/Ansible/ansible-tower-manage-playbook/roles/tower-manage/tasks/main.yml:24
Using module file /usr/lib/python2.7/site-packages/ansible/modules/web_infrastructure/ansible_tower/tower_role.py
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: ikanse
<localhost> EXEC /bin/sh -c 'echo ~ &amp;&amp; sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 &amp;&amp; mkdir -p "` echo /home/ikanse/.ansible/tmp/ansible-tmp-1520232438.17-217702889247684 `" &amp;&amp; echo ansible-tmp-1520232438.17-217702889247684="` echo /home/ikanse/.ansible/tmp/ansible-tmp-1520232438.17-217702889247684 `" ) &amp;&amp; sleep 0'
<localhost> PUT /tmp/tmpxkOOCO TO /home/ikanse/.ansible/tmp/ansible-tmp-1520232438.17-217702889247684/tower_role.py
<localhost> EXEC /bin/sh -c 'chmod u+x /home/ikanse/.ansible/tmp/ansible-tmp-1520232438.17-217702889247684/ /home/ikanse/.ansible/tmp/ansible-tmp-1520232438.17-217702889247684/tower_role.py &amp;&amp; sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python /home/ikanse/.ansible/tmp/ansible-tmp-1520232438.17-217702889247684/tower_role.py; rm -rf "/home/ikanse/.ansible/tmp/ansible-tmp-1520232438.17-217702889247684/" > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_9eTSgJ/ansible_module_tower_role.py", line 220, in <module>
main()
File "/tmp/ansible_9eTSgJ/ansible_module_tower_role.py", line 207, in main
result = role.grant(**params)
File "/usr/lib/python2.7/site-packages/tower_cli/resources/role.py", line 359, in grant
return self.role_write(fail_on_found=fail_on_found, **kwargs)
File "/usr/lib/python2.7/site-packages/tower_cli/resources/role.py", line 236, in role_write
fail_on_multiple_results=True, **data)
File "/usr/lib/python2.7/site-packages/tower_cli/models/base.py", line 286, in read
r = client.get(url, params=kwargs)
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 521, in get
return self.request('GET', url, **kwargs)
File "/usr/lib/python2.7/site-packages/tower_cli/api.py", line 236, in request
kwargs.get('data', None), r.content.decode('utf8'))
tower_cli.exceptions.BadRequest: The Tower server claims it was sent a bad request.

GET https://13.126.199.60/api/v2/teams/1/object_roles/
Params: {'state': 'present', 'tower_verify_ssl': True, 'role_field': 'member_role'}
Data: None

Response: {"detail":"Role has no field named 'state'"}

fatal: [localhost]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_9eTSgJ/ansible_module_tower_role.py\", line 220, in <module>\n    main()\n  File \"/tmp/ansible_9eTSgJ/ansible_module_tower_role.py\", line 207, in main\n    result = role.grant(**params)\n  File \"/usr/lib/python2.7/site-packages/tower_cli/resources/role.py\", line 359, in grant\n    return self.role_write(fail_on_found=fail_on_found, **kwargs)\n  File \"/usr/lib/python2.7/site-packages/tower_cli/resources/role.py\", line 236, in role_write\n    fail_on_multiple_results=True, **data)\n  File \"/usr/lib/python2.7/site-packages/tower_cli/models/base.py\", line 286, in read\n    r = client.get(url, params=kwargs)\n  File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 521, in get\n    return self.request('GET', url, **kwargs)\n  File \"/usr/lib/python2.7/site-packages/tower_cli/api.py\", line 236, in request\n    kwargs.get('data', None), r.content.decode('utf8'))\ntower_cli.exceptions.BadRequest: The Tower server claims it was sent a bad request.\n\nGET https://13.126.199.60/api/v2/teams/1/object_roles/\nParams: {'state': 'present', 'tower_verify_ssl': True, 'role_field': 'member_role'}\nData: None\n\nResponse: {\"detail\":\"Role has no field named 'state'\"}\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            description=dict(),
            inventory=dict(required=True),
            variables=dict(),
            credential=dict(),
            source=dict(
                choices=[
                    "manual",
                    "file",
                    "ec2",
                    "rax",
                    "vmware",
                    "gce",
                    "azure",
                    "azure_rm",
                    "openstack",
                    "satellite6",
                    "cloudforms",
                    "custom",
                ],
                default="manual",
            ),
            source_regions=dict(),
            source_vars=dict(),
            instance_filters=dict(),
            group_by=dict(),
            source_script=dict(),
            overwrite=dict(type="bool", default=False),
            overwrite_vars=dict(),
            update_on_launch=dict(type="bool", default=False),
            state=dict(choices=["present", "absent"], default="present"),
        )
    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

    if not HAS_TOWER_CLI:
        module.fail_json(msg="ansible-tower-cli required for this module")

    name = module.params.get("name")
    inventory = module.params.get("inventory")
    credential = module.params.get("credential")
    state = module.params.get("state")

    variables = module.params.get("variables")
    if variables:
        if variables.startswith("@"):
            filename = os.path.expanduser(variables[1:])
            with open(filename, "r") as f:
                variables = f.read()

    json_output = {"group": name, "state": state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        group = tower_cli.get_resource("group")
        try:
            params = module.params.copy()
            params["create_on_missing"] = True
            params["variables"] = variables

            inv_res = tower_cli.get_resource("inventory")
            inv = inv_res.get(name=inventory)
            params["inventory"] = inv["id"]

            if credential:
                cred_res = tower_cli.get_resource("credential")
                cred = cred_res.get(name=credential)
                params["credential"] = cred["id"]

            if state == "present":
                result = group.modify(**params)
                json_output["id"] = result["id"]
            elif state == "absent":
                result = group.delete(**params)
        except exc.NotFound as excinfo:
            module.fail_json(
                msg="Failed to update the group, inventory not found: {0}".format(
                    excinfo
                ),
                changed=False,
            )
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(
                msg="Failed to update the group: {0}".format(excinfo), changed=False
            )

    json_output["changed"] = result["changed"]
    module.exit_json(**json_output)