Wednesday, 31 December 2014

Git authentication for automation script

Git authentication

When you write some kind of automation (script) which needs to interact with git and clone/pull data and perform some action. And if its behind authentication layer then you need a way to automate the authentication that can let you pass credentials and automation can run without any interruption.

Either you can use ssh keys to authentication and use git@ URL to access your git repo.
But if you want to access (or force to) git via https URL you need to pass credential explicitly.
There are 2 ways to achieve this task for http protocol.

    1) Store authentication credential in the file in your home location.
Create a file under your/user's home location (.git-credentials).
$vi .git-credentials

Add following entry in the file

user - > user name
password -> password for the user
yourserver-domain -> your git server and domain name.

To Implement this You will need to checkout the repo first with user name and password and then run following command once.

$git config push.default simple
$git config credential.helper store

Above command will change the .git/config to accept the password from .git-credentials file now onward.

Whenever your script access the git (, credentials will be passed for authentication via this file and will let you/script access git .

Data stored in this file is simple text. This is flat file and you need to make sure that this file does't have permission to read by any other user. Although super user can still read it.

    2) Create a git credential cache demon
Create a file under your/user's home location (.gitconfig)
$vi .gitconfig

Add following entry in the file

        name = <ID>
        email = <Email>
        helper = cache --timeout=36000000

[user] -> is the section for user information
name = <ID> -> is the section to provide user id
email = <Email> -> email of the user
[credential] -> this is the section which will take care of credential part
helper = cache --timeout=360000 -> this section is to cache the credential for give time (360000 seconds)
[http] - > used for http access

You have to access your git repo once and provide the credential, This configuration will take your credential and cache it in form of process for the duration of  --timeout=360000 seconds ( you can give bigger number). whenever you try to access your git server this process will take care of passing credential to git automatically.

Once process is started it will stay in memory and act as any other normal process. You will be able to see the process which will look like

$ ps -aef | grep git
user   9156     1  0 Jan05 ?        00:00:00 git-credential-cache--daemon /home/user/.git-credential-cache/socket

Benefit is that you don't need to store credential in any file in plan text format.
Once time is elapsed (or process got killed), you need to start the process again by accessing git and passing credential once again.