def merge(a, b):
    """
    Recursively merges hash b into a so that keys from b take precedence over keys from a
    See: https://github.com/ansible/ansible/blob/6787fc70a643fb6e2bdd2c6a6202072d21db72ef/lib/ansible/utils/vars.py
    """

    # if a is empty or equal to b, return b
    if a == {} or a == b:
        return b.copy()

    # if b is empty the below unfolds quickly
    result = a.copy()

    # next, iterate over b keys and values
    for k, v in b.iteritems():
        # if there's already such key in a
        # and that key contains a MutableMapping
        if k in result and isinstance(result[k], dict) and isinstance(v, dict):
            # merge those dicts recursively
            result[k] = merge(result[k], v)
        else:
            # otherwise, just copy the value from b to a
            result[k] = v

    return result