Ricerca nel sito web

Come aggiungere e rimuovere Cronjob dalle istanze Linux EC2 su AWS utilizzando gli script della shell


Su questa pagina

  1. Prerequisiti
  2. Cosa faremo
  3. Crea uno script di shell per aggiungere Cronjob
  4. Esegui lo script Shell per aggiungere un Cronjob
  5. Crea uno script di shell per rimuovere i Cronjob
  6. Esegui lo script Shell per rimuovere Cronjob
  7. Conclusione

Le operazioni manuali portano a errori umani. L'aggiunta e la rimozione frequenti di Cronjob può richiedere molto tempo. In questo articolo, creeremo script Shell che automatizzano l'aggiunta e l'eliminazione di Cronjob dalle istanze Ubuntu EC2 su AWS. Per eseguire queste operazioni è necessario accedere all'istanza EC2. L'utente che utilizzerai deve disporre dell'accesso sudo in modo che l'utente possa passare a root ed eseguire l'aggiunta e l'eliminazione di Cronjobs.

Iniziamo.

Prerequisiti

  1. Comprensione di base degli script Shell e dei Cronjob.
  2. Account AWS (crea se non ne hai uno).
  3. Istanza EC2 con l'utente che ha accesso sudo (fai clic qui per imparare a creare un'istanza EC2 se non ne hai una o se vuoi imparare)

Che cosa faremo

  1. Crea uno script di shell per aggiungere Cronjob.
  2. Esegui lo script Shell per aggiungere un Cronjob.
  3. Crea uno script di shell per rimuovere i Cronjob.
  4. Esegui lo script Shell per rimuovere Cronjob.

Crea uno script di shell per aggiungere Cronjob

Crea un file sul tuo sistema Linux locale e aggiungi il seguente codice. Puoi anche trovare il codice sul mio repository Github al seguente link.

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

Prima di creare un nuovo Cronjob, verifica se l'istanza EC2 dispone di Cronjob esistenti

Accedi all'istanza EC2 e controlla i Cronjob esistenti

ssh -i ~/Downloads/howtoforge-test.pem 

Elenca i Cronjob

crontab -l

Esegui lo script Shell per aggiungere un Cronjob

Vai alla tua macchina Linux locale e aggiungi un Cronjob sull'istanza di Ubuntu 18.04 EC2 usando il seguente comando. Questo creerà un Cronjob che verrà attivato ogni minuto e scriverà la data corrente in un file. Puoi modificare il Cronjob in base alle tue esigenze.

./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"

Ora puoi anche andare all'istanza EC2 per verificare se il Cronjob è stato aggiunto o meno.

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

Nello screenshot seguente, puoi vedere che il Cronjob è stato aggiunto ed eseguito ogni minuto.

Crea uno script di shell per rimuovere i Cronjob

Ora, se pensi di dover rimuovere il Cronjob che hai aggiunto, puoi farlo facilmente usando lo script di shell disponibile sul mio Github.

Crea un nuovo file sul tuo sistema locale con il seguente codice.

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

Esegui lo script Shell per rimuovere Cronjob

Per rimuovere i Cronjob, eseguire lo script della shell. Elencherà tutti i Cronjob disponibili sulla tua istanza Ubuntu 18.04 EC2. È quindi possibile selezionare il lavoro da eliminare, lo script eseguirà l'eliminazione per te.

./remove-cronjob.sh -K ~/Downloads/howtoforge-test.pem -U ubuntu -I ec2-15-236-64-128.eu-west-3.compute.amazonaws.com -l yes

Ora puoi eseguire nuovamente lo stesso script per elencare il Cronjob nell'istanza 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

Puoi anche controllare il Cronjob dall'istanza EC2 stessa.

ssh -i ~/Downloads/howtoforge-test.pem 
sudo -i
crontab -l

Conclusione

In questo articolo, abbiamo visto gli script Shell per aggiungere e rimuovere Cronjobs dall'istanza Ubuntu EC2. Ciò contribuirà ad automatizzare l'attività manuale di aggiunta o rimozione di Cronjob e anche a evitare potenziali errori umani che possono derivare da operazioni manuali.