5

Hey I am trying to push code to git using a cron job on the Mac. I edit my crontab using crontab -e and have the following inside:

* 12 * * 1 ~/Dropbox/MD/sync.sh
* 12 * * 5 ~/Dropbox/MD/sync.sh

The script is as follows:

#!/bin/bash

cd ~/Dropbox/MD
/usr/bin/git add .
/usr/bin/git commit -m "Docs auto update"
/usr/bin/git push origin master

However the command fails and when I run mail I can check the error message which is: fatal: could not read Username for 'https://github.com': Device not configured. How can I fix this issue? If I run the commands manually from the terminal I have no issues and I am not prompted for user credentials.

Any pointers on this would be much appreciated. Thanks!

Kex
  • 8,023
  • 9
  • 56
  • 129

2 Answers2

6

When automating git tasks using SSH keys is recommended. You can setup SSH keys with push access by following these steps:

  1. get the SSH key of the user(or generate one: ssh-keygen -t rsa -b 4096 -C "your_email@example.com")
  2. copy contents of the public key (cat ~/.ssh/id_rsa.pub)
  3. Go to the project on github.com
  4. Go to project settings
  5. Choose Deploy Keys (https://github.com/user/project/settings/keys)
  6. Choose add deploy key
  7. Add your public key contents
  8. Check Allow write access
  9. Choose Add Key

Please note this will only work for repositories cloned with the following remote: git@github.com:user/project.git

The remote can be updated wit the following steps:

  1. go to the repository folder on the server
  2. run git remote remove origin
  3. run git remote add origin git@github.user/project.git
MaartenDev
  • 5,631
  • 5
  • 21
  • 33
  • This is great thanks! For the first step where you generate the SSH key of the user, is the email the GitHub account email? – Kex Aug 25 '19 at 10:28
  • That isn't required, the email isn't really relevant. I can be any email, it can help with keeping track of where the public key comes from when added to github. @Kex – MaartenDev Aug 25 '19 at 10:29
1

If I run the commands manually from the terminal I have no issues and I am not prompted for user credentials.

That would be the case if your cron job does not run as you.

Git would check the value of git config credential.helper to see if the github.com username/password are cached (typically the OSX Keychain for Mac).
If the cron job is run as, for instance, root, it would not have that setting configured.

Note: check if a plist in $HOME/Library/LaunchAgents would work better, since launchd might replace cron.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250