I found only a hacky way with a different configuration file and preference in di.xml
. The alternative way is to use a plugin for connection.
app/code/Vendor/Module/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Config\File\ConfigFilePool">
<arguments>
<argument name="additionalConfigFiles" xsi:type="array">
<item name="app_cronenv" xsi:type="string">cronenv.php</item>
</argument>
</arguments>
</type>
</config>
app/etc/cronenv.php
<?php
try {
/** @var \Magento\Framework\ObjectManagerInterface $om */
$om = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Framework\App\State $state */
$state = $om->get('Magento\Framework\App\State');
if ($state->getAreaCode() === \Magento\Framework\App\Area::AREA_CRONTAB) {
return [
'db' =>
[
'connection' =>
[
'default' =>
[
'username' => 'cronUser',
'password' => 'cronPass'
],
],
],
];
} else {
return [];
}
} catch (\Exception $exception) {
return [];
}
Another way: add some param in request during call bin/magento
from crontab and make a plain check in the main env.php
file.
PS: validation by area code in the main env.php
is unavailable, because it must be loaded before we trying to load OM and check area code (recursion).
PPS: I suppose there must be a regular way to update env.php
settings (connection config) in runtime. It will be good if someone write an proper answer :)