The following procedure adds a cron job that executes at the same moment to all the EC2 instances in your Elastic Beanstalk environment.
Note: If you have a period task that requires execution on only one instance, consider using worker tier periodic tasks instead.
Create the .ebextensions directory structure
Create a directory named “.ebextensions” in the Elastic Beanstalk application zip file. For the purposes of the following example, the Elastic Beanstalk application zip file is named “myapp.zip”, and the configuration file is named “cronjob.config”.
Note: You can name the configuration file anything you like, but if there are multiple configuration files in the .ebextensions directory, they are executed in alphabetical order.
The below example illustrates the structure of the .ebextensions directory and cronjob.config file in the application zip file:
| |-- cronjob.config
| |-- other .config files
|-- other application files
Update the contents of the configuration file
There are two sections in the cronjob.config file:
files: This section specifies the location to create the “myscript.sh” file on the Elastic Beanstalk instances, as well as the permissions of the file as required. Choose a location and permissions set that supports your use case.
commands: This section specifies a list of commands to run on the instances.
Here is a general illustration of the structure of a configuration file:
* * * * * root /usr/local/bin/myscript.sh
date > /tmp/date
# Your actual script content
command: "rm -f /etc/cron.d/*.bak"
This example illustrates a file with a command that removes the old cron file if any changes are made (for example, to the cron schedule).
After you finish creating the configuration file, add it to the “.ebextensions” directory in the application’s zip file. Configuration files in the .ebextensions directory are executed every time the application is deployed on the Elastic Beanstalk instances.
For more information about customizing your environment using .ebextensions, see Advanced Environment Customization with Configuration Files.