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
CodePudding user response:
I assume your are runing under user $USER
You should ensure /etc/sudoers
allows your script to be run by the cron user without password (NOPASSWORD option), something like :
$USER ALL=NOPASSWD:/home/user/Desktop/Projects/example/remove-inactive-users.sh
alternatively, you could also give the right to that username to call docker directly (not with sudo) :
sudo usermod -aG docker $USER && exec sg docker newgrp $(id -gn) && sudo systemctl restart docker
CodePudding user response:
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...
CodePudding user response:
Suggestion from @Julien is correct at the sudo
realm.
A more fundamental approach is to create a dedicated technical user for running the cron job.
The approach of dedicated user provide additional benefits for logging and process capabilities isolation.
See Docker official documentation here , and this helpful article.
Use a technical user with no shell and additional groups docker and wheel.
sudo useradd -M -G docker,wheel docker_user_5
After testing docker_user_5
to run docker from cli.
Add crontab task to docker_user_5