Question

Is it possible to run Magento 2 cron tasks under a different database user? This user will be able to connect to the same database as the website itself, and have exactly the same privileges; perhaps the only difference is that it may use a different password.

The main reason why I want to do this is to analyse the SQL queries that Magento are calling, and want to separate these between generic website usage, and background usage that are called via cron, and filtering these via the connected user will be the easiest approach.

If for whatever reason this is a bad approach, then please say so with your reasons.

Thank you!

No correct solution

OTHER TIPS

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 :)

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top