Report this

What is the reason for this report?

DOCTL While Loop Not Working in CRON

Posted on January 12, 2020

When I run the following manually via the command line, it work beautifully.

However, when I run this same script via sudo crontab, it just deletes everything. What could I be doing wrong:

Assumption: There are 10 snapshots for this specific droplet.

Script:

#!/bin/bash
DROPLETID=XXXXXXXXX
NUMRETAIN=5

SNAPSHOTS=$(sudo /snap/bin/doctl compute image list-user --format "ID,Type" --no-header | grep snapshot | wc -l)

# Deleting all snapshots beyond $NUMRETAIN
while [[ "$SNAPSHOTS" -gt "$NUMRETAIN" ]]
	do 
		OLDEST=$(sudo /snap/bin/doctl compute image list-user --format "ID,Type" --no-header | grep -e '$DROPLETID\|snapshot' | awk '{print$1}' | head -n 1)
		OLDESTNAME=$(sudo /snap/bin/doctl compute snapshot list --format "ID,Name,ResourceId" | grep $DROPLETID | awk '{print$2}' | head -n 1)
		echo "Deleting "$OLDESTNAME""
		sudo /snap/bin/doctl compute image delete $OLDEST --force 
		SNAPSHOTS=$(sudo /snap/bin/doctl compute snapshot list --format "ID,Name,ResourceId" --no-header | grep $DROPLETID | awk '{print$1}' | wc -l)
done

sudo crontab -e:

50 12 * * *  /bin/bash /home/aaron/projects/DOCTL-Remote-Snapshot/auto_snapshot.bash


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
0

Accepted Answer

Hello,

Have you allowed the sudo /snap/bin/doctl command to be executed without a password? You could do that by editing your sudoers file with the visudo command and adding something like:

your_user host = (root) NOPASSWD: /snap/bin/doctl

Otherwise, the script looks absolutely correct. Besieds that I have 2 other suggestions, enable debug by adding set -x after the #!/bin/bash, and also try to output the STDOUT and STRERR to a log file so that you could check the output for any errors and strange values:

50 12 * * *  /bin/bash /home/aaron/projects/DOCTL-Remote-Snapshot/auto_snapshot.bash > /path/to/log.txt 2>&1

Hope that this helps! Regards, Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.