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!
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.