Ubuntu – Jenkins: use ssh-agent and git plugins together

gitgithubJenkinsssh-agentUbuntu

So, I have the following situation: a server with dedicated users for each project (e.g. foo) and a jenkins server which runs as a jenkins user.
I've generated an SSH key pair for my foo user and added the public one as a deploy key to a github repo. (I verified I can clone the repo with the foo user)

In Jenkins I setup authentication in "Manage Jenkins" > "Manage Credentials" as a "SSH username with private key" with Username "foo" and foo's private key in a "Global" scope.

So I configured my Jenkins job with the correct workspace (e.g. /home/foo/deployment with full ownership for user foo obviously) and using the credentials "foo". For "Source code management" I wanted to use the SSH URL of my repo (e.g. git@github.com:foo/foo.git)
However it immediately notifies me there's a permission problem:

Failed to connect to repository : Command "git -c core.askpass=true ls-remote -h git@github.com:foo/foo.git HEAD" returned status code 128:
stdout: 
stderr: Permission denied (publickey). 
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

If I use the https version of the URL (https://github.com/foo/foo.git) the error disappears, but when I run the job I get the following errors in the console output:

Started by user developer
[EnvInject] - Loading node environment variables.
Building in workspace /home/foo/deployment
Cloning the remote Git repository
Cloning repository https://github.com/foo/foo.git
 > git init /home/foo/deployment # timeout=10
ERROR: Error cloning remote repo 'origin'
hudson.plugins.git.GitException: Could not init /home/foo/deployment
    [long stacktrace]
Caused by: hudson.plugins.git.GitException: Command "git init /home/foo/deployment" returned status code 1:
stdout: 
stderr: /home/foo/deployment/.git: Permission denied
    [long stacktrace]
ERROR: null
Finished: FAILURE

The key pair doesn't use a passphrase, I'd like to add one though if I get this working first.
Jenkins runs on a Ubuntu 14.04.2 LTS (GNU/Linux 3.13.0-65-generic x86_64) box.

What am I missing here? It appears the credentials I provided aren't being used, which explains why it explodes on permissions. But I don't understand why they're not being used? And why can't use the git@ URL?

Since it chokes on a permission problem with git init I ran that manually in /home/foo/deployment, but rerunning the Jenkins job it chokes on git fetch, again with permissions problems.

Best Answer

Ah yes, very silly me. The SSH user agent obviously only allows the jenkins user to connect to the remote repo as foo, but doesn't grant it permissions to write to the local file system...