# Buggy code
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            user=dict(),
            team=dict(),
            role=dict(
                choices=[
                    "admin",
                    "read",
                    "member",
                    "execute",
                    "adhoc",
                    "update",
                    "use",
                    "auditor",
                ]
            ),
            target_team=dict(),
            inventory=dict(),
            job_template=dict(),
            credential=dict(),
            organization=dict(),
            project=dict(),
            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")

    role_type = module.params.pop("role")
    state = module.params.get("state")

    json_output = {"role": role_type, "state": state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        role = tower_cli.get_resource("role")

        params = update_resources(module, module.params)
        params["type"] = role_type

        try:
            if state == "present":
                result = role.grant(**params)
                json_output["id"] = result["id"]
            elif state == "absent":
                result = role.revoke(**params)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(
                msg="Failed to update role: {0}".format(excinfo), changed=False
            )

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


# Traceback (tower_cli.exceptions.BadRequest)
[...]
TASK [Add myself to the member role] ***********************************************************************                                                                                               [0/1598]
fatal: [localhost]: FAILED! => {
"changed": false,
"rc": 1
}

MSG:

MODULE FAILURE


MODULE_STDERR:

*** DETAILS: Getting the record. **********************************************
GET http://localhost:8087/api/v2/users/
Params: {'username': 'pierre'}

*** DETAILS: Getting the record. **********************************************
GET http://localhost:8087/api/v2/teams/
Params: {'name': 'backend'}

*** DETAILS: Checking if role exists. *****************************************
GET http://localhost:8087/api/v2/teams/1/object_roles/
Params: {'tower_verify_ssl': True, 'state': 'present', 'tower_config_file': 'awx_cli.cfg', 'role_field': 'member_role'}

Traceback (most recent call last):
File "/tmp/ansible_0DBZC3/ansible_module_tower_role.py", line 177, in <module>
main()
File "/tmp/ansible_0DBZC3/ansible_module_tower_role.py", line 164, in main
result = role.grant(**params)
File "/usr/local/lib/python2.7/dist-packages/tower_cli/resources/role.py", line 364, in grant
return self.role_write(fail_on_found=fail_on_found, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tower_cli/resources/role.py", line 241, in role_write
fail_on_multiple_results=True, **data)
File "/usr/local/lib/python2.7/dist-packages/tower_cli/models/base.py", line 288, in read
r = client.get(url, params=kwargs)
File "/home/piroux/.local/lib/python2.7/site-packages/requests/sessions.py", line 521, in get
return self.request('GET', url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tower_cli/api.py", line 286, 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 http://localhost:8087/api/v2/teams/1/object_roles/
Params: {'tower_verify_ssl': True, 'state': 'present', 'tower_config_file': 'awx_cli.cfg', 'role_field': 'member_role'}
Data: None

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


to retry, use: --limit @/home/piroux/project_first_week/tut_ansible/qusible/awx_init.retry

PLAY RECAP *************************************************************************************************

# Fixed code
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            user=dict(),
            team=dict(),
            role=dict(
                choices=[
                    "admin",
                    "read",
                    "member",
                    "execute",
                    "adhoc",
                    "update",
                    "use",
                    "auditor",
                ]
            ),
            target_team=dict(),
            inventory=dict(),
            job_template=dict(),
            credential=dict(),
            organization=dict(),
            project=dict(),
            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")

    role_type = module.params.pop("role")
    state = module.params.pop("state")

    json_output = {"role": role_type, "state": state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        role = tower_cli.get_resource("role")

        params = update_resources(module, module.params)
        params["type"] = role_type

        try:
            if state == "present":
                result = role.grant(**params)
                json_output["id"] = result["id"]
            elif state == "absent":
                result = role.revoke(**params)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(
                msg="Failed to update role: {0}".format(excinfo), changed=False
            )

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