We use AWS Elastic Beanstalk for quite a few projects and its’ rapid deployment models make it indispensable.

Laravel 5 (5.1) includes a powerful Task Scheduling model that can be used to automate any part of your Laravel application using just one cron that runs an artisan command.

If you’re setting environment variables directly through the Elastic Beanstalk console, there are a few tricks you’ll need to use to get Task Scheduling working properly with Elastic Beanstalk.

As any Laravel 5 user knows, environment variables are set through the .env file located in the root of the project. Elastic Beanstalk has the ability to define environment variables at the instance level, so there’s no need to commit the env file to the git repo, which is convenient. Elastic Beanstalk builds an environment config file that is auto loaded into the environment when the instance is provisioned. This gives Apache/PHP knowledge of these environments variables so everything just works. Great.

I ran into a problem. For some reason, every time the scheduled cron would run php artisan schedule:run , it would log MySQL not found errors. The job would begin but would fail out because it couldn’t find the database. After dumping the environment variables that PHP could see, I realized that cron was setting up a very minimal environment in which to run. None of the environment vars set in Elastic Beanstalk were being loaded into the cron shell.

Lucky for us, Elastic Beanstalk creates a file /opt/elasticbeanstalk/support/envvars containing all of the SETENV flags we need.

So here is the working crontab that I ended up with:

* * * * * . /opt/elasticbeanstalk/support/envvars && /usr/bin/php /var/www/html/artisan schedule:run 1>> /dev/null 2>&1

This first loads in the environment variables from the file, and then calls the artisan scheduler to start.