[Git + cron]: Schedule your git commands on AWS EC2

git

03/22/2020


Overview

Last post, [Git + launchd]: Schedule your git commands with launchd, covered how to schedule to run sh commands, but it wouldn't be as efficient as it cannot run while the PC is asleep/off. Since EC2 instance won't hibernate (hopefully), this may be a good place to set up your cron job. In this post, I'll explain how to set up cron job on EC2 instance to run a script—git command as an example.

Follow this section of post to create AWS EC2 instance

Sign in to EC2 instance

BASH
ssh -i ~/some/dir/aws-key.pem ubuntu@<YOUR_PUBLIC_DNS>

Clone your project

Folder structure

TEXT
.
├── opt
| ├── cron-test
| | └── <YOUR_PROJECT>
| └── script.sh
└── ...

Cloning your GitHub Project

BASH
sudo git clone https://github.com/<GITHUB_USERNAME>/<REPO.git> /opt/cron-test

Make changes to your project

Assume that you've made some changes in your project

BASH
sudo vim /opt/cron-test/some_change.html

Create script that will run in the future

BASH
sudo vim /opt/script.sh

/opt/script.sh

BASH
cd /opt/cron-test
git add .
git commit -m "[RELEASE]: 2.0.0" > /tmp/commit-log 2>&1
git push > /tmp/push-log 2>&1

Save

Make it executable

BASH
sudo chmod +x /opt/script.sh

Check the date & time

Your EC2 instance may not have the same time as the location you're at. Use date to check the time of the machine.

BASH{OUTPUTLINES:
date
Sun Mar 22 07:07:50 CDT 2020

Set up crontab

BASH
sudo crontab -e # Then select your favorite editor
BASH
00 7 22 3 * /opt/script.sh
# Minute | Hour | Date | DayOfWeek | Script

That's it!

This cron job will executes /opt/script.sh on 3/22 at 7:00AM every year

Checking logs

On linux, cron job gets logged at

TEXT
/var/log/system.log

Use the following to filter cron jobs

TEXT
grep CRON /var/log/system.log

WRITTEN BY

Keeping a record