def set_datastore_value_for_config_key(
    pack_name, key_name, value, secret=False, user=None
):
    """
    Set config value in the datastore.

    This function takes care of correctly encoding the key name, serializing the
    value, etc.

    :param pack_name: Pack name.
    :type pack_name: ``str``

    :param key_name: Config key name.
    :type key_name: ``str``

    :param secret: True if this value is a secret.
    :type secret: ``bool``

    :param user: Optional username if working on a user-scoped config item.
    :type user: ``str``

    :rtype: :class:`KeyValuePairDB`
    """

    if user:
        scope = FULL_USER_SCOPE
    else:
        scope = FULL_SYSTEM_SCOPE

    name = get_key_reference(scope=scope, name=key_name, user=user)

    kvp_api = KeyValuePairAPI(name=name, value=value, scope=scope, secret=secret)
    kvp_db = KeyValuePairAPI.to_model(kvp_api)

    # TODO: Obtain a lock
    try:
        existing_kvp_db = KeyValuePair.get_by_scope_and_name(scope=scope, name=name)
    except StackStormDBObjectNotFoundError:
        existing_kvp_db = None

    if existing_kvp_db:
        kvp_db.id = existing_kvp_db.id

    kvp_db = KeyValuePair.add_or_update(kvp_db)
    return kvp_db

    Set config value in the datastore.

    This function takes care of correctly encoding the key name, serializing the
    value, etc.

    :param pack_name: Pack name.
    :type pack_name: ``str``

    :param key_name: Config key name.
    :type key_name: ``str``

    :param secret: True if this value is a secret.
    :type secret: ``bool``

    :param user: Optional username if working on a user-scoped config item.
    :type user: ``str``

    :rtype: :class:`KeyValuePairDB`
    
st2common/st2common/services/config.py