Retrieve Project Roles List using Python

Still need help?

The Atlassian Community is here for you.

Ask the community


Platform Notice: Cloud - This article applies to Atlassian products on the cloud platform.

Disclaimer

Atlassian does not support this code below, which is provided "AS IS". The goal of this article is to provide a piece of code that illustrates one way to achieve the desired goal.

Feedback provided at the bottom of the page is appreciated, but won't be handled as support.

Summary

The Python script on this page retrieves the roles of the users assigned to the project:

  • Project Key
  • Name (User)
  • Role

Environment

Usage

The Python script requires an API_TOKEN: Manage API tokens for your Atlassian account
User with Administrative Access to the instance: Permissions

A CSV file must be provided with the pkey (Project Key) for each project for which you want to retrieve the roles. This file must be named: projects.csv
The file must contain a single column called project_key

Solution

Here is the script - Adjust your User Name and API TOKEN accordingly
import requests
from requests.auth import HTTPBasicAuth
import csv

# Replace with your actual values
JIRA_DOMAIN = 'https://<your_instance>.atlassian.net'
EMAIL = '<your_email>@atlassian.com'
API_TOKEN = '<API_TOKEN>'

# Function to get users and their roles for a specific project
def get_users_and_roles_for_project(project_key):
    url = f"{JIRA_DOMAIN}/rest/api/3/project/{project_key}/role"
    auth = HTTPBasicAuth(EMAIL, API_TOKEN)

    response = requests.get(url, auth=auth)
    if response.status_code == 200:
        roles_data = response.json()
        users_and_roles = []

        # Loop through each role and get the users associated with the role
        for role_name, role_url in roles_data.items():
            role_response = requests.get(role_url, auth=auth)

            if role_response.status_code == 200:
                role_info = role_response.json()

                # Retrieve the users and their roles from the role info
                for user in role_info.get('actors', []):
                    user_name = user['displayName']
                    users_and_roles.append((project_key, user_name, role_name))  # Store project, user, and role

        return users_and_roles
    else:
        print(f"Failed to retrieve roles for project {project_key}. Status code: {response.status_code}")
        return []

# Function to read project keys from a CSV file
def read_project_keys_from_csv(csv_file_path):
    project_keys = []
    with open(csv_file_path, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            project_keys.append(row['project_key'])
    return project_keys

# Function to write users and roles to a CSV file
def write_users_and_roles_to_csv(output_file, users_and_roles_data):
    # Define CSV header
    header = ['Project Key', 'User', 'Role']
    
    # Write to CSV file
    with open(output_file, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(header)  # Write header
        writer.writerows(users_and_roles_data)  # Write data rows

# Main script logic
csv_file_path = 'projects.csv'  # Path to your input CSV file
output_csv_file = 'users_and_roles_output.csv'  # Path to output CSV file

# Read project keys from CSV
project_keys = read_project_keys_from_csv(csv_file_path)

# Collect all users and roles for all projects
all_users_and_roles = []

# Total number of projects to process
total_projects = len(project_keys)

# Process each project with a progress counter
for index, project_key in enumerate(project_keys, start=1):
    print(f"\nProcessing project {index}/{total_projects}: {project_key}")
    users_and_roles = get_users_and_roles_for_project(project_key)
    
    if users_and_roles:
        all_users_and_roles.extend(users_and_roles)  # Append users and roles to the master list
    else:
        print(f"No users or roles found for project {project_key}.")

    # Inform how many projects are left to process
    remaining = total_projects - index
    print(f"Processed {index}/{total_projects}. {remaining} project(s) remaining.")

# Write the collected data to the output CSV file
write_users_and_roles_to_csv(output_csv_file, all_users_and_roles)

print(f"\nUsers and roles have been successfully exported to {output_csv_file}")




Last modified on Oct 24, 2024

Was this helpful?

Yes
No
Provide feedback about this article
Powered by Confluence and Scroll Viewport.