Skip to content

Instantly share code, notes, and snippets.

@noah
Created November 11, 2016 10:32
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save noah/3ed929858802a474eeff888c9d3a2ac9 to your computer and use it in GitHub Desktop.
Save noah/3ed929858802a474eeff888c9d3a2ac9 to your computer and use it in GitHub Desktop.
Programmatically create deploy keys, on server and GitHub, for an existing git repository
#!/bin/sh
KEYDIR=~/.ssh/keys.d/github-deploy
CONFDIR=~/.ssh/config.d/github-deploy
github_username=noah
github_access_token=$(cat ~/.secret/github_access_token)
rp=$(git rev-parse --is-inside-work-tree 2>/dev/null)
if [ $? -eq 0 ] && [ "$rp" = "true" ]; then
url="$(git config --get remote.origin.url)"
reponame="$(echo $url | cut -d/ -f2)"
keyfile=$KEYDIR/$reponame
config=$CONFDIR/$reponame
repo_id="github-deploy-$reponame.github.com"
git remote set-url origin git@$repo_id:$github_username/$reponame
echo "+ config: $config"
cat << EOF > $config
Host $repo_id
HostName github.com
User git
IdentitiesOnly yes
IdentityFile $keyfile
EOF
echo "+ local key: $keyfile"
echo -e 'y\n' | ssh-keygen -t rsa \
-f $keyfile \
-C https://github.com/$github_username/$reponame\
-N ''\
-q 1>/dev/null
# delete all existing deploy keys
curl \
-H"Authorization: token $github_access_token"\
https://api.github.com/repos/noah/$reponame/keys 2>/dev/null\
| jq '.[] | .id ' | \
while read _id; do
echo "- deploy key: $_id"
curl \
-X "DELETE"\
-H"Authorization: token $github_access_token"\
https://api.github.com/repos/noah/$reponame/keys/$_id 2>/dev/null
done
# add the keyfile to github
echo
echo "+ deploy key:"
echo -n ">> "
{
curl \
-i\
-H"Authorization: token $github_access_token"\
--data @- https://api.github.com/repos/noah/$reponame/keys << EOF
{
"title" : "$repo_id $(date)",
"key" : "$(cat $keyfile.pub)",
"read_only" : false
}
EOF
} 2>/dev/null | head -1 # status code should be 201
echo
echo "local key:"
ssh-keygen -lf $keyfile
echo
echo "config:"
cat $config
else
echo 'Not a git repository'
exit
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment