Skip to content

Laravel Envoy

Nguồn gốc: Bản dịch từ Laravel Envoy

Giới thiệu (Introduction)

Laravel Envoy là công cụ thực thi các tác vụ phổ biến trên remote server. Sử dụng cú pháp kiểu Blade, bạn có thể dễ dàng thiết lập task cho deployment, Artisan commands và nhiều hơn nữa.

LƯU Ý

Hiện tại Envoy chỉ hỗ trợ Mac và Linux. Windows có thể sử dụng thông qua WSL2.

Cài đặt (Installation)

bash
composer require laravel/envoy --dev

Sau khi cài, binary Envoy có trong vendor/bin:

bash
php vendor/bin/envoy

Viết Tasks (Writing Tasks)

Định nghĩa Tasks

Task là building block cơ bản của Envoy, định nghĩa shell command chạy trên remote server.

Tất cả task được định nghĩa trong file Envoy.blade.php ở root ứng dụng:

blade
@servers(['web' => ['user@192.168.1.1'], 'workers' => ['user@192.168.1.2']])

@task('restart-queues', ['on' => 'workers'])
    cd /home/user/example.com
    php artisan queue:restart
@endtask

Mảng @servers được định nghĩa đầu file, sau đó tham chiếu qua option on trong khai báo task.

Local Tasks

Chạy script trên máy local bằng IP 127.0.0.1:

blade
@servers(['localhost' => '127.0.0.1'])

Import Tasks

blade
@import('vendor/package/Envoy.blade.php')

Variables

Truyền arguments qua command line:

bash
php vendor/bin/envoy run deploy --branch=master

Sử dụng trong task với cú pháp Blade:

blade
@servers(['web' => ['user@192.168.1.1']])

@task('deploy', ['on' => 'web'])
    cd /home/user/example.com

    @if ($branch)
        git pull origin {{ $branch }}
    @endif

    php artisan migrate --force
@endtask

Stories

Stories nhóm nhiều task dưới một tên tiện lợi:

blade
@servers(['web' => ['user@192.168.1.1']])

@story('deploy')
    update-code
    install-dependencies
@endstory

@task('update-code')
    cd /home/user/example.com
    git pull origin master
@endtask

@task('install-dependencies')
    cd /home/user/example.com
    composer install
@endtask

Chạy story:

bash
php vendor/bin/envoy run deploy

Hooks

Envoy hỗ trợ hooks @before, @after, @error@success để thực thi logic trước/sau task.

Chạy Tasks (Running Tasks)

bash
php vendor/bin/envoy run deploy

Xác nhận thực thi

Thêm directive @confirm để yêu cầu xác nhận trước khi chạy task.

Thông báo (Notifications)

Envoy hỗ trợ gửi thông báo sau khi task hoàn thành đến:

  • Slack@slack
  • Discord@discord
  • Telegram@telegram
  • Microsoft Teams@microsoftTeams