How to Run a Cron Job in AWS Elastic Beanstalk?

To run a cron task periodically, create a folder at the root of your application called .ebextensions. Then create a config file inside the .ebextensions folder with this:

container_commands:
  01_cron_job:
    command: "cat .ebextensions/cron_job.txt > /etc/cron.d/cron_job && chmod 644 /etc/cron.d/cron_job"
    leader_only: true

leader_only key ensures the command is only run on the EC2 instance that is considered the leader & not on every instance you have running.

Put your cron jobs in .ebextensions/cron_job.txt:

# The newline at the end of this file is extremely important.
# Cron won't run without it.
* * * * * root /usr/bin/bash some-script > /dev/null

NOTE β€” You’ll lose your running cron job if the instance running the job gets terminated in a scale down! To avoid this, enable protection against automatic instance termination on the leader in Beanstalk settings.

Elastic Beanstalk Worker Environments

You can also use worker environments to schedule jobs:

You can define periodic tasks in a file named cron.yaml in your source bundle to add jobs to your worker environment’s queue automatically at a regular interval.

β€” Periodic tasks β€” Beanstalk documentation

Example cron.yaml:

version: 1
cron:
 - name: "backup-job"
   url: "/backup"
   schedule: "0 */12 * * *"
 - name: "audit"
   url: "/audit"
   schedule: "0 23 * * *"

Also see:

If using OpsWorks, you can accomplish the same β€” Running Cron Jobs on Linux Instances.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.