Deploying Laravel via Ansible

Fast and easy solution for automatic deployment of Laravel project using Ansible.

There are lots of different ways to deploy you code to production server. Some have bash scripts, others use deployment tools such as Capistrano or Deployer. I’ve even saw people who build deb/rpm packages with their projects and install them directly to servers from custom repositories.

Here I want to present you another solution that is made right for Laravel project and uses Ansible.

This project is built around awesome Ansistrano that can deploy any project in Capistrano way, but but made exclusively for Laravel.

After first deploy you will get this structure on you server:

-- /var/www/laravel
|-- cachetool.phar
|-- composer.phar
|-- current -> /var/www/laravel/releases/20170512131539
|-- releases
|   |-- 20170512131539
|-- repo
|-- shared
|   |-- storage
|   |-- .env
  • cachetool.phar - used to clean you opcache in order to help php switch to the new version (especially for php 7.0)
  • composer.phar - is downloaded to be sure that there is one on you machine
  • current - is a soflink to the current release directory
  • releases - stores all last releases of you app
  • repo - is a directory with you project repository
  • shared - storage for all files that should be shared between your releases (.env file and Laravel storage directory)

Preparations

Clone project to your local machine.

$ git clone https://github.com/mlanin/ansible-laravel.git

Create hosts file for all your environments from example:

$ cp hosts.example production

Create group_vars/laravel.yml from example:

$ cp group_vars/laravel.example.yml group_vars/laravel.yml

Edit it to match your environment and project needs.

Usage

Playbooks:

  • playbook-deploy.yml - Run files deployment
  • playbook-rollback.yml - Rollback deploy
  • playbook-migrate.yml - Run migrations
  • playbook-seed.yml - Run seeding
$ ansible-playbook playbook-deploy.yml -i production -u root

Deployment order

  1. Init directory structure
  2. Update/clone repository
  3. Export a copy of the repo to a new release directory
  4. Copy .env.example to shared/.env if it was absent
  5. Copy storage to shared/storage if it was absent
  6. Remove local .env & storage from release directory
  7. Create soft links to shared .env & storage
  8. Install composer locally
  9. Run composer self-update
  10. Run composer install
  11. Clear Laravel cache
  12. Optimize code
  13. Run npm install and gulp --production if needed
  14. Change soflink to new release
  15. Update chown
  16. Install cachetool to clear opcache
  17. Run cachetool opcache:reset
  18. Restart Laravel queue
  19. Delete old relases

Attention! Don’t forget to update your shared/.env file after first deploy!

Contributing

Please feel free to fork this package and contribute by submitting a pull request to enhance the functionalities.

Star Fork