Bulk add users to groups using Python and API

Platform Notice: Cloud and Data Center - This article applies equally to both cloud and data center platforms.

Support for Server* products ended on February 15th 2024. If you are running a Server product, you can visit the Atlassian Server end of support announcement to review your migration options.

*Except Fisheye and Crucible

Summary

This article provides instructions to bulk add users to a group using Python.  The primary differences in the implementation of Jira Cloud and Jira Data Centers are

  • REST API
  • REST API Authentication
    • Jira Cloud uses the API token with the user email address in basic authentication
    • Jira Data Center uses Bearer token in the header

Prerequisites

  • Ensure Python is installed on your local machine. This can be downloaded from the following page Download Python.
  • A CSV file
    • Jira Cloud: CSV file with the Atlassian user and group IDs.
    • Jira Data Center: CSV file with user and group names.
  • API token is needed to authenticate the script.

Creating CSV file for Jira Cloud

To get the group ID you can navigate within Jira to Settings → User management → Groups. From here select the group you want to add the users to, the group ID will be part of the URL in the navigation bar as highlighted in the screenshot below:


To get the user IDs you can navigate to Users on the same screen as the Groups from the earlier step. On this page click the Export users button, which will download a list of users on your instance:

An example of the user export CSV file after being downloaded in the previous step:

You will need to create a CSV file with two columns, the names of the columns will be added to the script that will use the file to obtain the user id and the group id. The file should look like the image below:

Once you have added all the user's IDs and group's IDs save the file users_and_groups.csv.

Creating CSV file for Jira Data Center

The CSV file contains a header and two columns in the following order

    • username - user name to be added to group
    • groupname - group name to add the user

The following example adds users 'chimp2', 'frank', and 'admin' to the group 'Group-A'

username,groupname
admin,Group-A
frank,Group-A
chimp2,Group-A

Creating Python script file for Jira Cloud

In the example below, ensure that the jira_url, email and api_token variables are updates with the relevant information to your environment and user for authentication: 

import requests
from requests.auth import HTTPBasicAuth
import json
import csv

# Jira Cloud URL - update this value to your cloud url
jira_url = "https://Your-Instance.atlassian.net/"

# API endpoint for adding users to a group
api_endpoint = f"{jira_url}/rest/api/3/group/user"

# Authentication credentials - update the email and api_token for your user and token combination
email = "Your-Email@mail.com"
api_token = "Your-Token"

# Read the CSV file with user and group IDs
csv_file_path = "users_and_groups.csv"

auth = HTTPBasicAuth(email, api_token)

headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
}

# Process the CSV file
with open(csv_file_path, mode="r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        user_id = row["userid"]  # Change to match your CSV column names
        group_id = row["groupid"]  # Change to match your CSV column names

        # Construct the JSON payload
        payload = json.dumps({"accountId": user_id})

        # Set the query parameters for the group ID
        query = {"groupId": group_id}

        # Make the API request to add the user to the group
        response = requests.post(
            api_endpoint,
            data=payload,
            headers=headers,
            params=query,
            auth=auth,
        )

        if response.status_code == 201:
            print(f"Added user with ID '{user_id}' to group with ID '{group_id}'.")
        else:
            print(
                f"Failed to add user with ID '{user_id}' to group. Status Code: {response.status_code}"
            )


Save the script with .py extension to your local machine. In this example, the filename will be test4.py.

Creating Python script file for Jira Data Center

Jira Data Center REST API uses username in the payload and group name in the query parameter. 

Here is an example cURL to add user 'admin' to group 'Group-a'

$ curl -s -H "Authorization: Bearer NzY5OTM5NTM4MTI4OpbOYE6v/WgmSSWaCJNUJiz/JZtH" -X POST -H "Content-Type: application/json"  --data '{"name": "admin"}' "http://localhost:49121/j9121/rest/api/latest/group/user?groupname=Group-A"
{"name":"Group-A","self":"http://localhost:49121/j9121/rest/api/2/group?groupname=Group-A","users":{"size":3,"items":[],"max-results":50,"start-index":0,"end-index":0},"expand":"users"

The "size" in the response is the number of users in the group.

Python script

import requests
from requests.auth import HTTPBasicAuth
from urllib.parse import urlencode, quote_plus
import json
import csv

#
# https://confluence.atlassian.com/jirakb/bulk-add-users-to-groups-using-python-and-api-1299910891.html
# 
# THIS SCRIPT WORKS FOR JIRA DATA CENTER ONLY
#

# Jira URL - update this value to your Jira url
jira_url = "<Jira URL>"
# Example: jira_url = "http://localhost:49121/j9121"

# API endpoint for adding users to a group
api_endpoint = f"{jira_url}/rest/api/latest/group/user"

# Authentication credentials - using PAT (bearer token)
bearer_token = "Your-Token"
# Example bearer_token = "NzY5OTM5NTM4MTI4OpbOYE6v/abcdefghijklmnopqrstuvwxyz"

# Read the CSV file with user and group IDs
csv_file_path = "users_and_groups.csv"

# using bearer token in header
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": f"Bearer {bearer_token}"
}
# Process the CSV file
with open(csv_file_path, mode="r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        user_name = row["username"]  # Change to match your CSV column names
        group_name = row["groupname"]  # Change to match your CSV column names

        # Construct the JSON payload for username to be added to the group
        payload = json.dumps({"name": user_name})

        # Set the query parameters for the group name
        query = {"groupname": group_name}

        # Make the API request to add the user to the group
		# Note: use urlencode for query parameter containing special characters
        response = requests.post(
            api_endpoint,
            data=payload,
            headers=headers,
            params=urlencode(query)
        )

        if response.status_code == 201:
            print(f"Added user '{user_name}' to group '{group_name}'.")
        else:
            print(
                f"Failed to add user '{user_name}' to group '{group_name}'. Status Code: {response.status_code}."
            )


Running python script

Open the terminal and navigate to the folder where the Python script has been saved.

To run the script run the command 'python3' with the script file path

python3 <python script file path>

Jira Cloud Example

Jira Data Center Example

% python3 bulk-add-user-to-group.py 

Added user 'admin' to group 'Group-A'.
Added user 'frank' to group 'Group-A'.
Added user 'chimp2' to group 'Group-A'.

Verification

Once the script has stopped, confirm that the users have been added by navigating to User management → Groups, and selecting the target group.

Jira Cloud Example

Jira Data Center Example



Last modified on Dec 9, 2024

Was this helpful?

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