Skip to content

Instantly share code, notes, and snippets.

@rudolfbyker
Created February 18, 2020 14:23
Show Gist options
  • Save rudolfbyker/2bf720dcf67f2c0b9b860cae2ede854e to your computer and use it in GitHub Desktop.
Save rudolfbyker/2bf720dcf67f2c0b9b860cae2ede854e to your computer and use it in GitHub Desktop.
Add deploy key to multiple Bitbucket repositories
#!/usr/bin/env python
import argparse
import requests
import os
import getpass
parser = argparse.ArgumentParser(description='Add deployment key to bitbucket repository.')
parser.add_argument('-a', '--accountname', help='The team or individual account.', type=str, required=True)
parser.add_argument(
'-r',
'--repo_slug',
help="The repo identifier (not to be confused with the repo's name).",
type=str,
required=True
)
parser.add_argument('-u', '--user', help='Your bitbucket username.', type=str, required=True)
parser.add_argument('-l', '--label', help='A display name for the key.', type=str)
parser.add_argument("file", help="The file containing the public key. (Eg.: ~/.ssh/id_rsa.pub)")
args = parser.parse_args()
password = os.environ['BITBUCKETPASSWORD'] if 'BITBUCKETPASSWORD' in os.environ else getpass.getpass()
response = requests.request(
method='POST',
url=('https://api.bitbucket.org/2.0/repositories/%s/%s/deploy-keys' % (args.accountname, args.repo_slug)),
data={
'key': open(os.path.expanduser(args.file)).read(),
'label': args.label,
},
auth=(args.user, password),
)
if response.status_code == 200:
print('success')
elif response.status_code == 200:
print('key already registered')
elif response.status_code == 400:
print('Someone has already registered this key as a deploy key for this repository')
elif response.status_code == 401:
exit('incorrect credentials')
else:
print(response.status_code)
print(response.content)
exit('failed')
#!/usr/bin/env bash
# Stop on errors
set -e
# List your repo slugs here
MODULES=( repo1 repo2 asdf-cow foobar awesome-repo-14 )
# Optionally export your bitbucket password here. Else you will be prompted for it.
#export BITBUCKETPASSWORD=""
# Add the rest of your account details here:
EMAIL=""
ACCOUNT=""
# This file should contain the public key of the server you want to deploy to.
FILE="./id_rsa.pub"
for MOD in ${MODULES[@]}
do
echo "Installing key for $MOD"
python bb-deploy-key.py -a "$ACCOUNT" -r "$MOD" -u "$EMAIL" "$FILE"
done
@rudolfbyker
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment