Created
September 23, 2019 14:08
-
-
Save OlegGorj/e7d9744a66a4c4b9ea457ca22071f84e to your computer and use it in GitHub Desktop.
Programmatically create deploy keys, on server and GitHub, for an existing git repository
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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