Search code examples
dockercron

crontab sudo docker permission denied


I have a bash script that works fine and I'm trying to run it using crontabs.

The main issue is that when I run the script it asks me for my sudo password in order to execute the docker command. Therefore, when I'm trying to execute the script using crontabs I get the following errors:

Permission denied

or

Got permission denied while trying to connect to the Docker daemon

This is my bash script:

PG_USERNAME=username
PG_DB=example-db
echo "Removing 7 days inactive users..."
sudo docker exec -it example-app psql -U $PG_USERNAME $PG_DB \
-c "DELETE from users where created_at <= current_date at time zone 'UTC' - interval '7 days' and is_activated = false;" \
&& echo "Users removed!" \
|| echo "failed to run command"

and this is what I'm running inside crontab -e:

* * * * * /home/user/Desktop/Projects/example/remove-inactive-users.sh >> /home/user/Desktop/Projects/example/log.log 2>&1

I have tried changing file permissions without success:

sudo chown root:root /home/user/Desktop/Projects/example/remove-inactive-users.sh
sudo chmod u+x /home/user/Desktop/Projects/example/remove-inactive-users.sh

Solution

  • I found the solution.

    I changed the bash script file permissions:

    sudo chmod 715 remove-inactive-users.sh
    

    then I got the error: the input device is not a TTY

    and I solved it changing the docker exec line from the script into this:

    docker exec example-app psql...