We got the The import failed due to the following reasons: Deleted and replaced configuration entity ...
error during the early development on a new project when a lot of entities and fields got created at once. The fix usually was to simply run drush cim
again. So our updated build routine now has cim
twice in it to circumvent failing builds.
drush cim -y || true
drush cim -y
Of course, finding and fixing the actual root cause that makes the import fail at the first place as suggested by @kenorb would be the preferred solution. But sometimes during early development you simply want things to move forward and the workaround above helped us to get that done.
Turned out that in my case a custom profile's implementation of hook_entity_bundle_create()
where some defaults for newly created bundles were set has caused the error. Adding the following few lines in the beginning of these implementations fixed it for us. Credits: @hchonov
// If we are currently importing configuration we expect it to be complete and
// therefore we should not try to create configuration here as if we do and
// that configuration is also part of the import then the import will fail
// with "Deleted and replaced configuration entity "@name"".
// @see \Drupal\Core\Config\ConfigImporter::checkOp().
/** @var \Drupal\Core\Config\ConfigInstallerInterface $config_installer */
$config_installer = \Drupal::service('config.installer');
if ($config_installer->isSyncing()) {
return;
}