Pure CI/CD: Trigger CronJobs from Containers
Having all CronJobs (such as CI/CD procedures) in an isolated container is cool, isn’t it?
Defining a new CronJob on your host machine (in this case Ubuntu) is as simple as running the command crontab -e
. This will verify and save a file inside /etc/cron.d/your_username
.
So if we mount our cron.d
directory to the guest container, it will allow us to edit it from the inside. But there is an issue which is a feature at the same time. We know that crontab
will run CronJobs with the same username. Then we can treat this as a feature to only allow the host to run the CronJobs.
The main difference between crontab -e
and directly editing /etc/crond.d/<your_username>
in syntax is the necessity of adding a related username to the definition of the command. etc:
*/30 * * * * ubuntu ./cicd.sh
Crontab UI is a web-based graphical user interface that allows us to simply edit CronJobs without direct access to the shell, which is a nice project by the way.
It can simply be done by creating the files below and running docker compose up -d
:
variables.env
BASIC_AUTH_USER=tayyebi
BASIC_AUTH_PWD=my_voice_is_my_pa55p0rt
docker-compose.yml
version: '3.7'
services:
crontab-ui:
container_name: crontab-ui
image: alseambusher/crontab-ui
network_mode: bridge
ports:
- 8000:8000
env_file: variables.env
volumes:
- /etc/cron.d:/etc/crontabs
- ./data/crontabs:/crontab-ui/crontabs
There is a simple way to test the installation, and that is to create a CronJob wall $(date)
with the username taken from the host machine every minute (* * * *
). The wall
command is somehow the same to echo
, but it will also let the user broadcast a message on all active terminals.
Finally, it is possible to create a cicd.sh
bash file and put all git pull
and docker ... --build
commands inside that. Please don’t forget to navigate to your working directory (dirname
) before any commands in the bash script.