Skip to content

Instantly share code, notes, and snippets.

@mttjohnson
Created January 14, 2021 16:42
Show Gist options
  • Select an option

  • Save mttjohnson/b2cc4feff0ea2641b3ba99d3840e7f82 to your computer and use it in GitHub Desktop.

Select an option

Save mttjohnson/b2cc4feff0ea2641b3ba99d3840e7f82 to your computer and use it in GitHub Desktop.
Update Magento 2 env.php Database Credentials from MySQL .my.cnf
# Found this nice mashup Jason Tolhurst posted specifically for updating DB credentials from the current user's .my.cnf
# Get DB Credentials
DB_HOST=$(echo $(grep "^\s*host " ~/.my.cnf | cut -d= -f2 | perl -p -e 's/^\s*(.*?)\s*$/$1/'))
DB_USER=$(echo $(grep "^\s*user " ~/.my.cnf | cut -d= -f2 | perl -p -e 's/^\s*(.*?)\s*$/$1/'))
DB_PASS=$(echo $(grep "^\s*password " ~/.my.cnf | cut -d= -f2 | perl -p -e 's/^\s*(.*?)\s*$/$1/'))
DB_NAME=$(echo $(grep "^\s*database " ~/.my.cnf | cut -d= -f2 | perl -p -e 's/^\s*(.*?)\s*$/$1/'))
# Merge DB configs into existing app/etc/env.php
set +H
PHP_CODE=$(cat <<PHP_CODE_HEREDOC
<?php
\$existing_env = include("app/etc/env.php");
\$db_creds = [
'db' => [
'connection' => [
'default' => [
'username' => '${DB_USER}',
'host' => '${DB_HOST}',
'dbname' => '${DB_NAME}',
'password' => '${DB_PASS}'
],
'indexer' => [
'username' => '${DB_USER}',
'host' => '${DB_HOST}',
'dbname' => '${DB_NAME}',
'password' => '${DB_PASS}'
]
]
]
];
\$combined_env = var_export(array_merge(\$existing_env,\$db_creds), true);
\$export_short_array_syntax = join(PHP_EOL, array_filter(["["] + preg_replace(["/\s*array\s\(\$/", "/\)(,)?\$/", "/\s=>\s\$/"], [NULL, ']\$1', ' => ['], preg_split("/\r\n|\n|\r/", preg_replace("/^([ ]*)(.*)/m", '\$1\$1\$2', \$combined_env)))));
echo "<?php
return " . \$export_short_array_syntax . ";
";
PHP_CODE_HEREDOC
)
set -H
NEW_ENV=$(echo "${PHP_CODE}" | php)
echo "${NEW_ENV}" > app/etc/env.php
php -l app/etc/env.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment