# Buggy code
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            description=dict(),
            job_type=dict(choices=["run", "check", "scan"], required=True),
            inventory=dict(),
            project=dict(required=True),
            playbook=dict(required=True),
            machine_credential=dict(),
            cloud_credential=dict(),
            network_credential=dict(),
            forks=dict(type="int"),
            limit=dict(),
            verbosity=dict(choices=["verbose", "debug"]),
            job_tags=dict(),
            skip_tags=dict(),
            host_config_key=dict(),
            extra_vars_path=dict(type="path", required=False),
            ask_extra_vars=dict(type="bool", default=False),
            ask_limit=dict(type="bool", default=False),
            ask_tags=dict(type="bool", default=False),
            ask_job_type=dict(type="bool", default=False),
            ask_inventory=dict(type="bool", default=False),
            ask_credential=dict(type="bool", default=False),
            become_enabled=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")
    state = module.params.get("state")
    json_output = {"job_template": name, "state": state}

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

        params = update_resources(module, module.params)
        params = update_fields(params)
        params["create_on_missing"] = True

        try:
            if state == "present":
                result = jt.modify(**params)
                json_output["id"] = result["id"]
            elif state == "absent":
                result = jt.delete(**params)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(
                msg="Failed to update job template: {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(
            name=dict(required=True),
            description=dict(),
            job_type=dict(choices=["run", "check", "scan"], required=True),
            inventory=dict(),
            project=dict(required=True),
            playbook=dict(required=True),
            machine_credential=dict(),
            cloud_credential=dict(),
            network_credential=dict(),
            forks=dict(type="int"),
            limit=dict(),
            verbosity=dict(choices=["verbose", "debug"]),
            job_tags=dict(),
            skip_tags=dict(),
            host_config_key=dict(),
            extra_vars_path=dict(type="path", required=False),
            ask_extra_vars=dict(type="bool", default=False),
            ask_limit=dict(type="bool", default=False),
            ask_tags=dict(type="bool", default=False),
            ask_job_type=dict(type="bool", default=False),
            ask_inventory=dict(type="bool", default=False),
            ask_credential=dict(type="bool", default=False),
            become_enabled=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")
    state = module.params.pop("state")
    json_output = {"job_template": name, "state": state}

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

        params = update_resources(module, module.params)
        params = update_fields(params)
        params["create_on_missing"] = True

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

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