GNU/Linux >> Tutoriales Linux >  >> Linux

Cómo agregar y eliminar Cronjobs de instancias EC2 de Linux en AWS mediante scripts de shell

Las operaciones manuales conducen a errores humanos. Agregar 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 de Ubuntu EC2 en AWS. Para realizar estas operaciones necesitará acceso a la instancia EC2. El usuario que usará debe tener acceso a sudo para que pueda cambiar a root y realizar la adición y eliminación de Cronjobs.

Comencemos.

Requisitos previos

  1. Comprensión básica de scripts de Shell y Cronjobs.
  2. Cuenta de AWS (cree si no tiene una).
  3. Instancia EC2 con el usuario que tiene acceso sudo (haga clic aquí para aprender a crear una instancia EC2 si no tiene una o si desea aprender)

Que haremos

  1. Cree un script de shell para agregar Cronjobs.
  2. Ejecute el script de Shell para agregar un Cronjob.
  3. Cree un script de shell para eliminar Cronjobs.
  4. Ejecute el script de Shell para eliminar Cronjob.

Cree un script de shell para agregar Cronjobs

Cree un archivo en su sistema Linux local y agréguele el siguiente código. También puede encontrar el código en mi repositorio 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, verifique si la instancia EC2 tiene Cronjobs existentes

Inicie sesión en la instancia de EC2 y verifique los Cronjobs existentes

ssh -i ~/Downloads/howtoforge-test.pem [email protected]

Enumerar los cronjobs

crontab -l

Ejecute el script de Shell para agregar un Cronjob

Vaya a su máquina Linux local y agregue un Cronjob en la instancia EC2 de Ubuntu 18.04 usando el siguiente comando. Esto creará un Cronjob que se activará cada minuto y escribirá la fecha actual en un archivo. Puede cambiar el Cronjob según sus requisitos.

./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 puede ir a la instancia EC2 para comprobar si se ha añadido o no el Cronjob.

ssh -i ~/Downloads/howtoforge-test.pem [email protected]
sudo -i
crontab -l
cat /tmp/cron_output

En la siguiente captura de pantalla, puede ver que Cronjob se ha agregado y ejecutado cada minuto.

Cree un script de shell para eliminar Cronjobs

Ahora, si cree que necesita eliminar el Cronjob que agregó, puede hacerlo fácilmente usando el script de shell disponible en mi Github.

Cree un nuevo archivo en su 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

Ejecute el script de Shell para eliminar Cronjob

Para eliminar los Cronjobs, ejecute el script de shell. Enumerará todos los Cronjob disponibles en su instancia de Ubuntu 18.04 EC2. A continuación, puede seleccionar el trabajo que se va a eliminar, el script hará la eliminación por usted.

./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, puede ejecutar el mismo script nuevamente para mostrar el 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 puede consultar el Cronjob desde la propia instancia de EC2.

ssh -i ~/Downloads/howtoforge-test.pem [email protected]
sudo -i
crontab -l

Conclusión

En este artículo, vimos scripts de Shell para agregar y eliminar Cronjobs de la instancia de Ubuntu EC2. Esto ayudará a automatizar la tarea manual de agregar o eliminar Cronjobs y también evitará posibles errores humanos que pueden surgir debido a operaciones manuales.


Linux
  1. Cómo agregar o eliminar un usuario de un grupo en Linux

  2. Cómo instalar MongoDB desde la fuente (y usando YUM) en Linux

  3. ¿Cómo extrae direcciones IP de archivos usando una expresión regular en un shell de Linux?

  4. Cómo verificar si existe un grupo y agregarlo si no existe en Linux Shell Script

  5. ¿Cómo eliminar cualquier cadena de un archivo a través de scripts de shell?

Cómo crear un usuario en una instancia EC2 de Linux en AWS y agregarle una clave pública mediante un script de shell

Cómo quitar programas instalados desde la fuente usando GNU Stow en Linux

Cómo quitar un comando del historial en Linux

Cómo quitar (^M) caracteres de un archivo en Linux

Cómo monitorear el servidor Linux y las métricas desde el navegador usando Scout Realtime

Cómo instalar y usar Nu Shell en Linux