Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Atlassian Python Scripting Tools

Steven Kling March 27, 2019

PROBLEM

There's so little python examples of Jira or other Atlassian Cloud REST API calls out there. Even fewer that aren't out-of-date and actually work. The key is really finding examples of successful auth constructs. Even seemingly simple "Basic" authorization examples, like those in python examples in the official REST API documents simply do not work. 

So I'll start the share-fest with an example of a desperately needed script for this use case:  Clone production cloud instance for a test cloud "sandbox".

Atlassian Cloud only supports full export/import of one environment to another. So if your team needs a sandbox this is your only option. *However* you'll soon find that the Access group membership (i.e. Jira Software) confers for every user imported, thus pushing your license count up to be the same as the prod environment you cloned.

You'll then discover there's no bulk deactivate or remove. "Invited" users who will never login are counted against the license because they belong to the Access Group.

SOLUTION

Script a bulk remove of unwanted users from the Access Group(s).

Step 1: Export all users to CSV.

Step 2: Remove users from the CSV where access is to be retained.

Step 2: Create an API Token
https://id.atlassian.com/manage/api-tokens

Step 3: Run this script:

import csv
import requests

user = 'yourusersemail@yourcompany.com'
apiToken = "putYourAPITokeHere"

base_url = "https://myinstance.atlassian.net"
rest_path = "/rest/api/3"
group_path = "/group/user"
groupname = "jira-software-users"


with open('cloud-export-users.csv', mode='r') as infile:
reader = csv.reader(infile)
mydict = {rows[0]:rows[2] for rows in reader}

for username, email in mydict.items():
print("Processing removal of " + username + " from group: " + groupname)

# Based on https://developer.atlassian.com/cloud/jira/platform/rest/v3/#api-rest-api-3-group-user-delete
# Warning: The example placing auth in headers absolutely will *NOT* work!
full_url = base_url + rest_path + group_path + "?groupname=" + groupname + "&username=" + username

# This is the line of python code that will drive you mad because there are no good examples of
# recent, working basic auth using API Tokens pretty much anywhere on all the internets
response = requests.delete(full_url, auth=(user, apiToken))
# Check the response in the loop.
print("Response: " + response.text + " Code: " + str(response.status_code)) 

 

1 comment

Comment

Log in or Sign up to comment
Ricardo Cerceau March 27, 2019

Nice Solution. Congrats.

TAGS
AUG Leaders

Atlassian Community Events