Created
June 2, 2022 10:02
-
-
Save vuthaihoc/587d8d1b2c7719f534819eeeab19719c to your computer and use it in GitHub Desktop.
create db deployer task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Deployer; | |
use Dotenv\Dotenv; | |
task('db:create', function(){ | |
$region = get('region'); | |
if(!$region){ | |
$region = ask("Region", ""); | |
}else{ | |
writeln("Region : " . $region); | |
} | |
$domain = ask("Domain", ""); | |
$env = server_path($domain, $region, '.env'); | |
if(!file_exists($env)){ | |
throw new \Exception("Can not find .env"); | |
} | |
$env = Dotenv::parse(file_get_contents($env)); | |
$db_name = $env['DB_DATABASE']; | |
$db_host = $env['DB_HOST']; | |
$db_user = $env['DB_USERNAME']; | |
$db_pass = $env['DB_PASSWORD']; | |
foreach ([$db_user, $db_host, $db_name, $db_pass] as $v){ | |
if(empty($v)){ | |
throw new \Exception("Not enough info"); | |
} | |
} | |
if($db_host == 'localhost' || $db_host == '127.0.0.1'){ | |
$db_granted_host = $db_host; | |
}else{ | |
$db_granted_host = preg_replace("/\.\d+$/", ".%", $db_host); | |
} | |
if(empty($db_granted_host)){ | |
throw new \Exception("DB_GRANTED_HOST is required"); | |
} | |
$root_pass = askHiddenResponse("Mysql root pass "); | |
$command = "CREATE DATABASE IF NOT EXISTS ".$db_name.";"; | |
$command .= "CREATE USER IF NOT EXISTS '$db_user'@'$db_granted_host' IDENTIFIED WITH mysql_native_password BY '$db_pass';"; | |
$command .= "GRANT ALL PRIVILEGES ON $db_name.* TO '$db_user'@'$db_granted_host' WITH GRANT OPTION;"; | |
$command .= "FLUSH PRIVILEGES;"; | |
$command = "mysql -u root --password='$root_pass' -e \"$command\" ; history -d 1"; | |
run($command,['tty' => true, 'timeout' => null]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment