# 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:])
            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)


# 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(),
            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.pop("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)