The so-called automated deployment, as I understand it, is a means to quickly and automatically deploy the code to the target server on the premise that the user guarantees the quality of the code.

Realize the principle of

Local push code -> code base -> Webhook notification server -> automatic pull code base

Generate and deploy the public key

For details, see Configuring SSH Public Keys

1) Generate a public key



Generate a public/private RSA key with the given email
SSH /config if not the default address is used
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"Copy the code

2) Add public key to coding

The deployment public Yue is displayed



$ cat coding.pubCopy the code

Partially deploy the public key on the Git management side

3) Configure the config file

Edit the ~/.ssh/config file



Host git.coding.net
User xxxx@email.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/coding_rsa  // Generated public key storage point with non-default addressCopy the code

4) Test whether you can link to [email protected] server



Note that git.coding.net is connected to the CDN and resolves multiple host IP addresses
$ ssh -T [email protected]
The authenticity of host 'git.coding.net (123.59.85.184)' can't be established

RSA key fingerprint is 98:ab:2b:30:60:00:82:86:bb:85:db:87:22:c4:4f:b1.

Are you sure you want to continue connecting (yes/no)? 

# here we enter yes as prompted
Warning: Permanently added 'git.coding.net, 123.59.85.184' (RSA) to the list of known hosts.Hello Duoli, You've connected to Coding.net via SSH. This is a deploy key.Hello Duoli, you have authenticated the Coding.net service through the SSH protocol, which is a deployment public keyCopy the code

Set the webhook

Instruct the server to receive code updates when the code base receives notifications.

This Webhook approach is used to receive deployable requests using the POST method

PHP receive Deployment

Because PHP script code execution may have interruption of service (such as execution time), it may not be practical, so plan to use script calls.

Receive the request -> Queue -> script listens to the processing queue

Thanks to the Laravel framework, after receiving the notification, it is stored in the queue. Since the queue uses the command line listening, there is no interruption when the command line is executed.

Users who need to be configured to run the code before then have access to Git’s servers. If your code runs on www-data, use the role of www-data to access the [email protected] server. Otherwise, the deployment cannot be implemented because the key does not match and the user does not have permission to obtain the content.

1) Queue code settingapp/Jobs




         
namespace App\Jobs;

use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Symfony\Component\Process\Process;

class WebDeploy extends Job implements SelfHandling.ShouldQueue
{

    private $shellPath;

    /** * Create a new job instance. */
    public function __construct(a)
    {
        $this->shellPath = dirname(dirname(__DIR__));
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle(a)
    {
        if(! env('LM_DEPLOY_BRANCH')) {
            echo 'ERR > ' . 'No branch Set'."\n";
        }
        $shell   = "/bin/bash " . base_path('resources/shell/deploy.sh').' ' . base_path() . ' ' . env('LM_DEPLOY_BRANCH'.'master');
        $process = new Process($shell);
        $process->start();
        $process->wait(function ($type, $buffer) {
            if (Process::ERR === $type) {
                echo 'ERR > ' . $buffer;
            }
            else {
                echo 'OUT > '. $buffer; }}); }}Copy the code

2) Trigger the queue



dispatch(new WebDeploy());Copy the code

3) Deploy shell scripts



#! /bin/bash
aim_path=The $1
branch=$2
cd ${aim_path}
echo $PWD
/usr/bin/git pull origin ${branch} >/dev/null 2>&1
if[$?-eq0];then
echo "OK"
else
   /usr/bin/git fetch -f
   /usr/bin/git reset --hard
   /usr/bin/git pull origin ${branch}
fi
Copy the code

4) Use supervisor to monitor queue execution and queue tasks

File location/etc/supervisord. D/project. Ini



[program:project_name]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/project/artisan queue:work  --sleep=3 --tries=3 --daemon
autostart=true
autorestart=true
user=apache
numprocs=1
redirect_stderr=true
stdout_logfile=/webdata/logs/project.log
environment=QUEUE_DRIVER=databaseCopy the code

Pay attention to the point

It took a long time to study the automatic deployment with my colleagues, and there was a little doubt about whether PHP was capable of this function. The code was able to be deployed on the LAN before, but failed in the rest of the tests. This time, instead, I found a way to run the script. In theory, there is no execution failure until you see an error like this:



OUT > /webdata/www/sour-lemon.com
ERR > Could not create directory '/usr/share/httpd/.ssh'.
ERR > Host key verification failed.
ERR > fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.Copy the code

Could not create directory ‘/usr/share/httpd/.ssh’, Consider setting up automated deployment of SSH with Apache permissions.

The Apache user is not allowed to log in. Therefore, you need to allow the Apache user to log in and then set the SSH key.

Change the /etc/passwd file to allow the user to log in



/sbin/nologin
apache:x:48:48:Apache:/usr/share/httpd:/bin/bashCopy the code

Then switch to apache user to set SSH key, so after the test, pass.

Refer to the article

  • [error] Permission denied (public key)
  • Configuring an SSH Public Key
  • gist.github.com/jexch… Click preview
  • www.freebsd.org/cgi/m…
  • help.github.com/artic…
  • callmepeanut.blog.51ct…
  • www.huamanshu.com/wall…
  • walle-web.io/
  • Github.com/meolu/wall….
  • www.phptesting.org/in…