Le operazioni manuali portano a errori umani. L'aggiunta e la rimozione frequenti di Cronjob può essere un'attività che richiede molto tempo. In questo articolo creeremo script Shell che automatizzano l'aggiunta e l'eliminazione di Cronjobs dalle istanze EC2 di Ubuntu 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
- Conoscenza di base di script di Shell e Cronjobs.
- Account AWS (crea se non ne hai uno).
- 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 )
Cosa faremo
- Crea uno script di shell per aggiungere Cronjobs.
- Esegui lo script Shell per aggiungere un Cronjob.
- Crea uno script di shell per rimuovere i Cronjob.
- Esegui lo script Shell per rimuovere Cronjob.
Crea uno script di shell per aggiungere Cronjobs
Crea un file sul tuo sistema Linux locale e aggiungi il codice seguente. 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, controlla se l'istanza EC2 ha dei Cronjob esistenti
Accedi all'istanza EC2 e controlla i Cronjob esistenti
ssh -i ~/Downloads/howtoforge-test.pem [email protected]
Elenca i Cronjobs
crontab -l
Esegui lo script Shell per aggiungere un Cronjob
Vai alla tua macchina Linux locale e aggiungi un Cronjob sull'istanza EC2 di Ubuntu 18.04 usando il comando seguente. Questo creerà un Cronjob che verrà attivato ogni minuto e scriverà la data corrente su un file. Puoi modificare il Cronjob secondo le 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 [email protected]
sudo -i
crontab -l
cat /tmp/cron_output
Nella schermata seguente, puoi vedere che il Cronjob è stato aggiunto ed eseguito ogni minuto.

Crea uno script di shell per rimuovere i Cronjobs
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 codice seguente.
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 EC2 Ubuntu 18.04. Puoi quindi 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 di nuovo 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 [email protected]
sudo -i
crontab -l

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