Cómo añadir y eliminar Cronjobs de las instancias EC2 de Linux en AWS utilizando scripts de shell
Las operaciones manuales conducen a errores humanos. Añadir y eliminar Cronjobs con frecuencia puede ser una tarea que consume mucho tiempo. En este artículo, crearemos scripts de Shell que automaticen la adición y eliminación de Cronjobs de instancias EC2 de Ubuntu en AWS. Para realizar estas operaciones necesitarás acceso a la instancia EC2. El usuario que utilizarás necesita tener acceso sudo para que el usuario pueda cambiar a root y realizar la adición y eliminación de Cronjobs.
Vamos a empezar.
Requisitos previos
- Conocimiento básico de los scripts de Shell y de los Cronjobs.
- Cuenta de AWS(crearla si no la tienes).
- Instancia EC2 con el usuario con acceso sudo (Haz clic aquí para aprender a crear una instancia EC2 si no tienes una o si quieres aprender )
Qué haremos
- Crear un script de shell para añadir Cronjobs.
- Ejecutar el script de shell para añadir un Cronjob.
- Crear un script de shell para eliminar Cronjobs.
- Ejecuta el script de Shell para eliminar el Cronjob.
Crear un script de shell para añadir Cronjobs
Crea un archivo en tu sistema Linux local y añade el siguiente código. También puedes encontrar el código en mi repo de Github en el siguiente enlace.
Github Link: https://github.com/shivalkarrahul/DevOps/blob/master/aws/shell-scripts/aws-ec2-add-remove-cron-job/add-cronjob.sh
File: add-cronjob.sh
#!/bin/bash
helpFunction()
{
echo ""
printf "\033[1;32mUsage: $0 -K <internal.pem> -U <internal-user> -I <internal-ip> -a <cron-to-be-added>"
echo ""
echo -e "\t-K \".pem key of the server on which a cron job has to be added\""
echo -e "\t-U UserName of the server on which a cron job has to be added"
echo -e "\t-I IP of the server on which a cron job has to be added"
echo -e "\t-a Name of the cron to be added (in double quotes)"
echo "Add a new Cron Job"
echo "e.g."
echo "./add-cronjob.sh -K /Users/cloudcover/Documents/Rahul/access/rahuls.pem -U ubuntu -I ec2-35-180-234-158.eu-west-3.compute.amazonaws.com -a \"0 5 * * 1 testCronJob\""
echo -e "\033[0m" #reset color
exit 1 # Exit script after printing help
}
while getopts "I:K:U:a:" opt
do
case "$opt" in
K ) internalServerPemKey="$OPTARG" ;;
U ) internalServerUser="$OPTARG" ;;
I ) internalServerIP="$OPTARG" ;;
a ) addCron="$OPTARG" ;;
? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
esac
done
echo "******************"
#echo $listCronJobs
# Print helpFunction in case parameters are empty
if [ -z "$internalServerIP" ] || [ -z "$internalServerPemKey" ] || [ -z "$internalServerUser" ] || [ -z "$addCron" ]
then
printf "\033[1;31m"
echo "Some or all of the parameters are empty";
helpFunction
fi
# Begin script in case all parameters are correct
printf "\033[1;33m------------------------------------------------------------------Before ssh"
echo -e "\033[0m" #reset color
echo ".pem key of the server on which a new user has be created : $internalServerPemKey"
echo "UserName of the server on which a new user has be created : $internalServerUser"
echo "IP of the server on which a new user has be created : $internalServerIP"
echo "Name of the cron to be added : $addCron"
printf "\033[1;31mLogging into: "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
ssh -i "$internalServerPemKey" "$internalServerUser"@"$internalServerIP" << HERE
printf "\033[1;33m------------------------------------------------------------------After ssh"
echo -e "\033[0m" #reset color
#echo "Executing connect_prod_cron_new.sh"
#sh connect_prod_cron_new.sh
#sleep 2
echo "after ssh"
echo "IP Of the Server:"
hostname -I
echo "Hostname of the Server:"
hostname
echo "Changing user to root"
sudo su <><> EOF
echo "User Switched To;"
whoami
printf "\033[1;33m------------------------------------------------------------------List of Cron Jobs Before Addition"
echo -e "\033[0m" #reset color
crontab -l | cat -n
if [ -n "$addCron" ]
then
echo "Inside addCron"
crontab -l >crontab.tmp
printf '%s\n' "$addCron" >>crontab.tmp
crontab crontab.tmp && rm -f crontab.tmp
fi
printf "\033[1;33m------------------------------------------------------------------Updated List of Cron Jobs"
echo -e "\033[0m" #reset color
crontab -l | cat -n
printf "\033[1;31mExiting from ---> "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
#echo "Existing user ---> $userName"
EOF
HERE
Antes de crear un nuevo Cronjob, comprueba si la instancia EC2 tiene algún Cronjob existente
Accede a la instancia EC2 y comprueba los Cronjobs existentes
ssh -i ~/Downloads/howtoforge-test.pem [email protected]
Enumera los Cronjobs
crontab -l
Ejecuta el script de Shell para añadir un Cronjob
Ve a tu máquina Linux local y añade un Cronjob en la instancia EC2 de Ubuntu 18.04 utilizando el siguiente comando. Esto creará un Cronjob que se activará cada minuto y escribirá la fecha actual en un archivo. Puedes cambiar el Cronjob según tus necesidades.
./add-cronjob.sh -K ~/Downloads/howtoforge-test.pem -U ubuntu -I ec2-15-236-64-128.eu-west-3.compute.amazonaws.com -a "* * * * * /bin/date >> /tmp/cron_output"

Ahora, también puedes ir a la instancia EC2 para comprobar si el Cronjob se ha añadido o no.
ssh -i ~/Downloads/howtoforge-test.pem [email protected]
sudo -i
crontab -l
cat /tmp/cron_output
En la siguiente captura de pantalla, puedes ver que el Cronjob ha sido añadido y ejecutado cada minuto.

Crea un script de shell para eliminar Cronjobs
Ahora, si crees que necesitas eliminar el Cronjob que has añadido, puedes hacerlo fácilmente utilizando el script de shell disponible en mi Github.
Crea un nuevo archivo en tu sistema local con el siguiente código.
Github Link: https://github.com/shivalkarrahul/DevOps/blob/master/aws/shell-scripts/aws-ec2-add-remove-cron-job/remove-cronjob.sh
File: remove-cronjob.sh
#!/bin/bash
helpFunction()
{
echo ""
printf "\033[1;32mUsage: $0 -K <internal.pem> -U <internal-user> -I <internal-ip> -l <yes/no>"
echo ""
echo -e "\t-K \".pem key of the server on which a cron job has to be removed\""
echo -e "\t-U UserName of the server on which a cron job has to be removed"
echo -e "\t-I IP of the server on which a cron job has to be removed"
echo -e "\t-l List the existing Cron Jobs, provide \"yes\" as a parameter. Get a list first and then specify job no which needs to be removed"
echo -e "e.g."
echo "Remove a new Cron Job"
echo "./remove-cronjob.sh -K /Users/cloudcover/Documents/Rahul/access/rahuls.pem -U ubuntu -I ec2-52-47-90-247.eu-west-3.compute.amazonaws.com -l yes"
echo -e "\033[0m" #reset color
exit 1 # Exit script after printing help
}
while getopts "I:K:U:l:" opt
do
case "$opt" in
K ) internalServerPemKey="$OPTARG" ;;
U ) internalServerUser="$OPTARG" ;;
I ) internalServerIP="$OPTARG" ;;
l ) showListOfJobs="$OPTARG" ;;
? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
esac
done
echo "******************"
echo $listCronJobs
# Print helpFunction in case parameters are empty
if [ -z "$internalServerIP" ] || [ -z "$internalServerPemKey" ] || [ -z "$internalServerUser" ] || [ -z "$showListOfJobs" ]
then
printf "\033[1;31m"
echo "Some or all of the parameters are empty";
helpFunction
fi
# Begin script in case all parameters are correct
printf "\033[1;33m------------------------------------------------------------------Before ssh"
echo -e "\033[0m" #reset color
echo ".pem key of the server on which a new user has be created : $internalServerPemKey"
echo "UserName of the server on which a new user has be created : $internalServerUser"
echo "IP of the server on which a new user has be created : $internalServerIP"
if [ $showListOfJobs == "yes" ]
then
printf "\033[1;31mLogging into: "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
ssh -i "$internalServerPemKey" "$internalServerUser"@"$internalServerIP" << HERE
printf "\033[1;33m------------------------------------------------------------------After ssh"
echo -e "\033[0m" #reset color
echo "after ssh"
hostname -I
hostname
echo "Changing user to root"
sudo su << EOF
echo "User Switched To;"
whoami
printf "\033[1;33m------------------------------------------------------------------List of Cron Jobs Before Deletion"
echo -e "\033[0m" #reset color
crontab -l | cat -n
printf "\033[1;31mExiting from ---> "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
EOF
HERE
fi
echo "Enter Cron Job Line Number to be removed"
read lineNumber
printf "\033[1;31mLogging into: "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
ssh -i "$internalServerPemKey" "$internalServerUser"@"$internalServerIP" << HERE
printf "\033[1;33m------------------------------------------------------------------After ssh"
echo -e "\033[0m" #reset color
echo "after ssh"
hostname -I
hostname
#sleep 2
echo "Changing user to root"
sudo su << EOF
echo "User Switched To;"
whoami
printf "\033[1;33m------------------------------------------------------------------List of Cron Jobs Before Deletion"
echo -e "\033[0m" #reset color
crontab -l | cat -n
crontab -l | sed -e "$lineNumber"d >crontab.tmp
crontab crontab.tmp && rm -f crontab.tmp
printf "\033[1;33m------------------------------------------------------------------Updated List of Cron Jobs"
echo -e "\033[0m" #reset color
crontab -l | cat -n
printf "\033[1;31mExiting from ---> "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
EOF
HERE
Ejecuta el script de Shell para eliminar el Cronjob
Para eliminar los Cronjobs, ejecuta el script de shell. Se listarán todos los Cronjob disponibles en tu instancia EC2 de Ubuntu 18.04. A continuación, puedes seleccionar el trabajo a eliminar, el script hará la eliminación por ti.
./remove-cronjob.sh -K ~/Downloads/howtoforge-test.pem -U ubuntu -I ec2-15-236-64-128.eu-west-3.compute.amazonaws.com -l yes

Ahora, puedes ejecutar el mismo script de nuevo para listar los Cronjob en la instancia EC2.
./remove-cronjob.sh -K ~/Downloads/howtoforge-test.pem -U ubuntu -I ec2-15-236-64-128.eu-west-3.compute.amazonaws.com -l yes

También puedes comprobar el Cronjob desde la propia instancia EC2.
ssh -i ~/Downloads/howtoforge-test.pem [email protected]
sudo -i
crontab -l

Conclusión
En este artículo, hemos visto scripts de Shell para añadir y eliminar Cronjobs de la instancia EC2 de Ubuntu. Esto ayudará a automatizar la tarea manual de añadir o eliminar Cronjobs y también a evitar los posibles errores humanos que pueden producirse debido a las operaciones manuales.