How to Add and Remove Users from Project Roles in Jira Cloud using JMWE Post Function and REST API
This guide explains how to automatically add a user (selected in a Single User Picker custom field) to a specific Project Role during a workflow transition using JMWE post functions.
Adding a User to a Project Role:
To add a user to a project role, you can utilize the callJira feature provided by JMWE. Here's a step-by-step approach:
Identify Project Role and User: Determine the ID of the project role to which you want to add the user. Also, ensure you have the correct user account or identifier. Please refer this page for more information: https://confluence.atlassian.com/jirakb/how-to-get-project-id-from-the-jira-user-interface-827341414.html
Note : The custom field ID represents the single-user picker. For this guide, we use customfield_10187 as an example.
Use the callJira Function:
{{ "/rest/api/2/project/:projectKey/role/:id" | callJira( params={"id":"10002","projectKey":issue.fields.project.key}, verb="POST", body={"user": [issue.fields.customfield_10187._accountId]} ) }}Replace the
<id>of the project role in your instance.Replace
customfield_10187with the ID of your custom field representing the single user picker.
Execute the Function: The script can be added in Build-your-own (Nunjucks scripted) Post function post-function or other JMWE post-functions that support Nunjucks editor .
Removing a User from a Project Role:
To remove a user from a project role, similar steps are followed with a slight modification. Here's how:
Identify Project Role and User: As before, ensure you have the project role ID and the user to be removed.
Use callJira Function with the DELETE method:
{{ "/rest/api/2/project/:projectKey/role/:id" | callJira( query={"user":issue.fields.customfield_10187._accountId}, params={"id":"10002","projectKey":issue.fields.project.key}, verb="DELETE" ) }}Replace
<id>with the ID of the project role in your instance.Replace
customfield_10187with the ID of your custom field representing the single user picker.This script removes the user from the project role of the current issue’s project.
Execute the Function: Similar to adding a user, trigger this function within your post function in your Jira workflow. Ensure all parameters are correctly replaced.
Handling Empty Fields
To avoid errors when the single-user picker field (customfield_10187) is empty, you can add a condition to check if the field is populated before calling the API. Here’s how you can modify the script:
{% if issue.fields.customfield_10187 %}
{{
"/rest/api/2/project/:projectKey/role/:id" |
callJira(
params={"id":"10002","projectKey":issue.fields.project.key},
verb="POST",
body={"user": [issue.fields.customfield_10187._accountId]}
)
}}
{% else %}
User field is empty. Skipping API call.
{% endif %}By following these steps, you can efficiently manage user roles in your Jira projects through automation, ensuring seamless updates and modifications to project permissions.