def replace_template_variables(obj, terms):
    """
    Recursively replaces the values of any keys in obj which are defined in the terms dictionary.
    Terms must be a dictionary.
    :param obj: Any object.
    :param terms: A dictionary of values to replace.
    :return: the given obj, with any terms replaced.
    """
    if not isinstance(terms, dict):
        raise TypeError('Terms must be of type dictionary')
    if isinstance(obj, dict):
        for key, value in obj.items():
            new_key = replace_template_variables(key, terms)
            new_value = replace_template_variables(value, terms)
            if new_key != key:
                obj.pop(key)
            obj[new_key] = new_value
        return obj
    elif isinstance(obj, list):
        return [replace_template_variables(element, terms) for element in obj]
    else:
        for key, value in terms.items():
            if key in obj:
                return obj.replace(key, value)
    return obj