We can use Elastic Beanstalk configuration files, .ebextensions, to create cron jobs that run on all Amazon EC2 instances in an Elastic Beanstalk environment.
Here, at Bobcares, we assist our customers with several AWS queries as part of our AWS Support Services.
Today, let us discuss Cron Jobs on Amazon EC2 Instances.
Cron Jobs on Amazon EC2 Instances in Elastic Beanstalk Environment
In the Elastic Beanstalk application zip file, we need to create a directory named .ebextensions. This will contain configuration files that run when we deploy the application to Amazon EC2 instances.
If we have a periodic task to run on one instance, we can use the cron-leaderonly-linux.config file for web environments.
On the other hand, we need to consider periodic tasks if we use a dedicated worker environment.
Moving ahead, let us see how our Support Techs go about this.
Create or update your configuration file
The two keys in the cron-linux.config file is files and commands.
While the files key specifies the location of the myscript.sh file, the commands key specifies a list of commands to run on the instances.
We can download the cron-linux.config template from the AWS GitHub repository.
Another option is to create or update an existing configuration file.
files: "/etc/cron.d/mycron": mode: "000644" owner: root group: root content: | * * * * * root /usr/local/bin/myscript.sh "/usr/local/bin/myscript.sh": mode: "000755" owner: root group: root content: | #!/bin/bash date > /tmp/date # Your actual script content exit 0 commands: remove_old_cron: command: "rm -f /etc/cron.d/mycron.bak"
Make note that multiple configuration files in the .ebextensions directory run in alphabetical order by file name.
So we can name the configuration file cron-linux.config.
This file will create the cron file, /etc/cron.d/mycron. It is configured to run a script every minute.
The myscript.sh script outputs the date and then exits when it runs.
Every time the cron-linux.config apply during deployments, it creates a backup of the /etc/cron.d/mycron file, which is, /etc/cron.d/mycron.bak.
The last command in cron-linux.config cleans up the /etc/cron.d directory by removing /etc/cron.d/mycron.bak.
Create an application source bundle
Our Support Techs recommend these steps to add the configuration file to the application source code of the web application:
- In the root of the application folder, we create a directory, .ebextensions.
- Then we move the cron-linux.config file to the .ebextensions folder.
- In addition, we create a zip folder for the application files, including the new configuration file.
For example, the structure of the .ebextensions directory and cron-linux.config file in the application zip file will be like this:
|-- .ebextensions | |-- cron-linux.config | |-- other .config files |-- other application files
[Need help with the procedures? Feel free to contact us]
In short, we saw how our Support Techs go about Cron Jobs on Amazon EC2 Instances.