Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elastic Beanstalk - Cron job is running but not executing

This is my very first time running a cron job on Elastic Beanstalk (EB). After deploying my code, it seems the cron job is created and running but the PHP script is not executing correctly. Here's my set-up.

In my .ebextensions folder I have a file called 01run.config.

container_commands:
  01_remove_old_cron_jobs:
    command: "crontab -r || exit 0"
  02_cronjobs:
    command: "cat .ebextensions/cron_jobs.txt > /etc/cron.d/cron_job && chmod 644 /etc/cron.d/cron_job"
    leader_only: true

In my .ebextensions folder I also have a cron_jobs.txt file. Please note that I have an line break at the end of this file as instructed by another stackoverflow post. In my example below I am running the command as ec2-user but I also tried root.

* * * * * ec2-user /usr/bin/php -q /var/app/current/tests/cron.php

After deploying my code, I can see that the file /etc/cron.d/cron_job has been created. I can also see the cron job running every minute when I run sudo tail /var/log/cron.

[ec2-user@ip-xxx-xxx-xxx-xxx ~]$ sudo tail /var/log/cron
Apr 13 12:54:53 ip-xxx-xxx-xxx-xxx crontab[26093]: (root) DELETE (root)
Apr 13 12:55:01 ip-xxx-xxx-xxx-xxx crond[1230]: (*system*) RELOAD (/etc/cron.d/cron_job)
Apr 13 12:55:01 ip-xxx-xxx-xxx-xxx CROND[26128]: (ec2-user) CMD (/usr/bin/php -q /var/app/current/tests/cron.php)
Apr 13 12:56:01 ip-xxx-xxx-xxx-xxx CROND[26139]: (ec2-user) CMD (/usr/bin/php -q /var/app/current/tests/cron.php)

Within /var/app/current/tests/cron.php I have some code that adds a row to a MySQL database (hosted on RDS). But nothing is being added to the database.

I then tried running the cron command directly through my terminal window:

$ /usr/bin/php -q /var/app/current/tests/cron.php

And it runs without error and adds the record to the database. I am logged in as ec2-user in terminal.

Have I missed something? Or is my cron job code set-up incorrectly?

like image 886
Ben Sinclair Avatar asked Mar 19 '23 21:03

Ben Sinclair


1 Answers

I had a similar problem with a php script that was trying to access an AWS RDS database. Is your php script getting the database details with $_SERVER['RDS_xxxx']? If so, those RDS_xxxx variables don't exist in the environment when the php script is run by cron.

In order to fix this, I added the variables to the beginning of the cron file:

RDS_HOSTNAME=<my_database_hostname>
RDS_PORT=<my_database_port>
RDS_USERNAME=<my_database_username>
RDS_PASSWORD=<my_database_password>
RDS_DB_NAME=<my_database_name>

* * * * * php /path/to/my/script.php
like image 93
lari Avatar answered Apr 01 '23 19:04

lari