Drupal - How to override configuration from a file?

To override config on code is simple. Above is an exemple how you get, set and save any config (that you just installed via .yml and from core).

On .install or .module file

  //Getting editable configs
  $module_cfg = \Drupal::configFactory()->getEditable('your.module.file');
  $settings = \Drupal::configFactory()->getEditable('any_core.settings');
  //Getting values
  $a_value = $settings->get('key_from_core');
  //Setting and save configs
  $module_cfg->set('any.key', $a_value)->save();
  $settings->set('key', 'new_value')->save();

From hook_install docs:

Implementations of this hook are by convention declared in the module's .install file.

For further information see ConfigFactory docs.

There is a module called Features that helps if you want keep on track of your configs. I'm currently using this module for code-driven development, maybe is this what you're looking for.

Edit 1 - Replace entire config

First of all, you need to provide which config you pretend to override.

On my.custom.config.yml file

# Make sure this config exists in your database
target: 'config.to.override'
... # all your data (CAUTION with 'dependencies')

On .install file

function module_install() {
  //Get your custom config
  $cfg = \Drupal::configFactory()->getEditable('my.custom.config');
  //Get config name to override
  $target = $cfg->get('target');
  //Get Config object
  $settings = \Drupal::configFactory()->getEditable($target);
  //Override all data that can be overridden
  $settings->setData($cfg->get())->save();
  //If you won't store any previous state, get rid of your custom config
  $cfg->delete();
}

This was tested in my development environment.


I leave here another example, in addition to @Vagner's answer, in case it is useful.

The scenario is as follows: I would like to override addtoany's settings.

The module's settings are located at modules/contrib/addtoany/config/install/addtoany.settings.yml.

In order to override them, create a custom module foobar and a file modules/custom/foobar/config/install/foobar.addtoany.settings.yml:

buttons_size: 32
additional_html: |
  <a class="a2a_button_facebook"></a>
  <a class="a2a_button_twitter"></a>
additional_css: ''
additional_js: ''
universal_button: none
custom_universal_button: ''
universal_button_placement: before
no_3p: false

In modules/custom/foobar/foobar.install, apply the new settings:

<?php

function foobar_install()
{
  // Get your custom config
  $cfg = \Drupal::configFactory()->getEditable('foobar.addtoany.settings');
  // Get Config object
  $settings = \Drupal::configFactory()->getEditable('addtoany.settings');
  // Override all data that can be overridden
  $settings->setData($cfg->get())->save();
  // Get rid of your custom config
  $cfg->delete();
}