Search code examples
gitubuntugithubcrongit-fetch

Unable to run git commands with crontab


I am setting up a server, and I want the git repository in my server to be up to date with the origin server(Github). I tried to run a cron job which updates the repository in the server every minute. This was successful in my mac pc.

crontab:

* * * * * bash /home/ubuntu/venv/App/deployer.bash >> /home/ubuntu/venv/App/Logs/deployer.txt 2>&1

Here is the part that fails in the server:

git fetch --all 
git reset --hard origin/master

Error :

Fetching origin
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.
error: Could not fetch origin

Everything works fine outside the crontab. For example : I Can do all git commands within the git repo without sudo. Using sudo I get the same error as in cronjob.

Update :

Figured out what caused the problem:

2>&1 in the crontab expression was writing the standard error and it was very correct. When I ran the commands outside of crontab it never requested for authentication. But on crontab on every execution, the commands are requesting for an authentication

Now can anyone explain why this would cause an error like that?


Solution

  • Adding the ssh key to the ssh-agent every time before executing the git command worked. This is what I did.

    I added the below command in the cronjob :

    eval `ssh-agent -s` && ssh-add ~/.ssh/id_rsa && ssh-add -l
    git fetch --all && sleep 2s && git reset --hard origin/master