Instead of defining a Bitbucket Cloud workspace variable that can be used by all the repos in the workspace, someone defined it in each repo, but not in all of them, of the workspace. Now I want to remove the variable in the individual repos, and define it in the workspace.
Is there a Bitbucket API that would do this pseudo-code?
def bb = Bitbucket.getInstance()
String workspace = "MyWorkspace"
String myVariable = "NEXUS_USER"
List<Repository> reposInWorkspace = bb.getWorkspace(workspace).getAllReposInWorkspace()
reposInWorkspace.each { repo ->
if (repo.hasVariable(myVariable)) {
println repo.name
}
}
I put a Bitbucket support ticket, and a sharp Atlassian support person gave me this Python3 script
from requests import Session
from time import sleep
username = 'your_username_not_email'
password = 'app_pw_not_bb_user_pw'
workspace = 'your_workspace'
variable_name = 'your_variable'
URL = f'https://api.bitbucket.org/2.0/repositories/{workspace}'
session = Session()
session.auth = (username, password)
def get_repos(page=None):
while True:
params = {'page': page, 'pagelen': 100}
r = session.get(URL, params=params)
while r.status_code == 429:
print("Hit the API rate limit. Sleeping for 10 sec...")
sleep(10)
print("Resuming...")
r = session.get(URL, params=params)
r_data = r.json()
for repo in r_data.get('values'):
yield repo.get('slug')
if not r_data.get('next'):
return
if page is None:
page = 1
page += 1
def get_variables(repo, page=None):
while True:
params = {'page': page, 'pagelen': 100}
r = session.get(f'{URL}/{repo}/pipelines_config/variables/', params=params)
while r.status_code == 429:
print("Hit the API rate limit. Sleeping for 10 sec...")
sleep(10)
print("Resuming...")
r = session.get(URL, params=params)
r_data = r.json()
for var in r_data.get('values'):
yield var.get('key')
if not r_data.get('next'):
return
if page is None:
page = 1
page += 1
def has_variable(var):
if var == variable_name:
return True
def main():
for repo in get_repos():
for var in get_variables(repo):
if has_variable(var):
print(f'{repo}')
if __name__ == '__main__':
main()