Skip to content

Instantly share code, notes, and snippets.

@1k-off
Created May 3, 2023 11:00
Show Gist options
  • Save 1k-off/14edafc54935b70091fbbb91b76a91c6 to your computer and use it in GitHub Desktop.
Save 1k-off/14edafc54935b70091fbbb91b76a91c6 to your computer and use it in GitHub Desktop.
Script for removal all users except a list from all repos in a file. Do not forget to update vars section.
#!/usr/bin/env bash
###
# You will need a file `repos` with the list of repos in the next format:
# https://bitbucket.org/workspace/repo-slug/src/master/
###
### VARS ###
clientId="wu" # get from bb oauth consumer
clientSecret="TY" # get from bb oauth consumer
callbackUrL="http://localhost:8000/callback" # do not touch. Set this as a callback url in the bitbucket oauth consumer.
appPassword="ATBB" # get from bb personal settings
username="username" # bb username
workspace="workspace" # bb workspace (organization)
# User1, User2
adminIds=(userid1 userid2) # IDs of users that need to be left in all repositories
bitbucketUrl="https://api.bitbucket.org/2.0" # do not touch
### END VARS ###
# authenticate
resp=$(curl -s -X POST -u "${clientId}:${clientSecret}" \
https://bitbucket.org/site/oauth2/access_token \
-d grant_type=client_credentials \
-d redirect_uri="${callbackUrl}")
accessToken=$(echo $resp | jq .access_token | sed 's/"//g')
# get all repo slugs
repos=($(awk -F "$workspace" '{print $(2)}' ./repos | awk -F '/' {'print $2'}))
for repo in "${repos[@]}"
do
# get all users in repo
repoSlug="$repo"
usersInRepoEndpoint="/repositories/$workspace/$repoSlug/permissions-config/users"
resp=$(curl --request GET \
--url "$bitbucketUrl$usersInRepoEndpoint" \
--header "Authorization: Bearer $accessToken" \
--header "Accept: application/json")
echo $resp | jq
output=$(echo $resp | jq .values[].user.account_id)
output=$(echo "${output}" | tr -d '"')
mapfile -t uuids <<< "${output}"
#for uuid in "${uuids[@]}"; do
# if [[ ! " ${adminIds[*]} " =~ " $uuid " ]]; then
# nonAdminUuids+=("$uuid")
# fi
#done
#printf '%s\n' "${nonAdminUuids[@]}"
# delete not admin users
for uuid in "${uuids[@]}"; do
if [[ ! " ${adminIds[*]} " =~ " $uuid " ]]; then
userId="$uuid"
deleteUserFromRepoEndpoint="/repositories/$workspace/$repoSlug/permissions-config/users/$userId"
curl --request DELETE \
--url "$bitbucketUrl$deleteUserFromRepoEndpoint" \
--user "$username:$appPassword"
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment