3

Can I change role of particular user in multiple projects at a time? If yes, How?

I have a user whose role is "Reporter" in more than 75 projects. I want to change the role to "Developer" in all projects. Can I achieve with minimal efforts?

TPS
  • 493
  • 1
  • 5
  • 28

1 Answers1

3

You can edit access of an existing member of a project with the following Gitlab API :

PUT /projects/:id/members/:user_id?access_level=XX.

I didn't find any API to request the projects for a specific user in the User API. But you can request the list of all projects, extract the ids and call the edit member API

What you can do is :

  • request the user API to get the user id for your target username :

    https://gitlab.com/api/v4/users?private_token=YOUR_TOKEN&username=someuser
    
  • request the list of projects and extracts the ids in a list :

    https://gitlab.com/api/v4/projects?private_token=YOUR_TOKEN&page=1&per_page=1000
    
  • call edit member API for each project with the access level of your choice :

    https://gitlab.com/api/v4/projects/<project_id>/members/<user_id>?private_token=YOUR_TOKEN&access_level=10
    

The access_level field can be any of these :

10 => Guest access
20 => Reporter access
30 => Developer access
40 => Master access
50 => Owner access # Only valid for groups

Here is a Bash script that will update user with username johndoe with the access level 30 (Developer access) for all projects where (s)he is member, this script also uses jq json parser :

#!/bin/bash

GITLAB_DOMAIN=gitlab.com
GITLAB_PORT=443
GITLAB_BASE_URL=https://$GITLAB_DOMAIN:$GITLAB_PORT
PER_PAGE=1000

PRIVATE_TOKEN=YOUR_TOKEN
ACCESS_LEVEL=30
USERNAME=johndoe

user_id=$(curl -s  "$GITLAB_BASE_URL/api/v4/users?private_token=$PRIVATE_TOKEN&username=$USERNAME" | jq '.[].id')

echo "user_id : $user_id"

projects=$(curl -s  "$GITLAB_BASE_URL/api/v4/projects?private_token=$PRIVATE_TOKEN&page=1&per_page=$PER_PAGE" | jq '.[].id')

while read -r project; do

    status=$(curl --write-out '%{http_code}' -s -o /dev/null -X PUT "$GITLAB_BASE_URL/api/v4/projects/$project/members/$user_id?private_token=$PRIVATE_TOKEN&access_level=$ACCESS_LEVEL")

    if [ "$status" == "200" ]; then
        echo "right change to $ACCESS_LEVEL for project : $project"
    fi  
done <<< "$projects"

Note that each request including a project where the specified user is not a member result in a 404.

Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159