import operator


def get_latest_task_definition(client, cluster, service):
    """
    Given the name of a cluster and a service, return the ARN
    for its latest task definition.
    """
    resp = client.describe_services(cluster=cluster, services=[service])

    # The top-level structure of a describeServices API response is of the form
    #
    #     {
    #       "failures": [],
    #       "services": [
    #         ...
    #       ]
    #     }
    #
    # Because we only asked for a description of a single service, we expect
    # there to only be a single service.
    services = resp['services']
    assert len(services) == 1, resp
    service = services[0]

    # Within a 'service' description, the following structure is what we're
    # interested in:
    #
    #     "deployments": [
    #       {
    #         "createdAt": <date>,
    #         "taskDefinition": <task definition ARN>,
    #         "updatedAt": <date>
    #         ...
    #       },
    #       ... other running tasks
    #     ],
    #
    # Each "deployment" corresponds to a running task, so we pick the
    # container with the most recent creation date.
    deployments = service['deployments']
    assert len(deployments) > 0, resp
    newest_deployment = max(deployments, key=operator.itemgetter('createdAt'))

    return newest_deployment['taskDefinition']