[PYTHON] Use gitlabApi to add members to multiple groups in gitlab at once

Task

It's hard to manually add a gitlab group every time a new person comes in

solution

I created a program using the GitLab API. Based on the following, it is set in Lambda and made into API.

Process flow

--Valid input values (user: username and level: permissions) --Get user information using usersAPI --Add the ID included in the user information to the target group list

We are doing validation in some places, so please refer to it.

program

# coding: utf-8
import json, requests, re
import inspect

private_token = '[Please issue from the management screen of gitlab]'
url_prefix = 'https://[your_gitlab_domain]/api/v4/'

def main(params):
  success_group_list = {}
  try:
    check_empty(params)
    user_info = get_user_info(params['user'])
    success_group_list = add_group(user_info[0]['id'], params['level'])
  except AddGitLabException as e:
    info = e.get_info()
    return {'body': info['body'], 'code': info['code'], 'function': info['function']}
  return {
    'code': 200,
    'body': 'Success:' + str(success_group_list)
  }

#need to check
def check_empty(params):
  if 'user' not in params or len(params['user']) == 0 or 'level' not in params or len(params['level']) == 0:
    raise AddGitLabException('Input require parameter.', 400, inspect.currentframe().f_code.co_name)

#Get user information
def get_user_info(username):
  url = url_prefix + 'users?active=true&username=' + username
  headers = {'Private-Token': private_token}
  response = requests.get(url, headers=headers)

  if response.status_code != 200 and response.status_code != 201:
    raise AddGitLabException(response.content, response.status_code, inspect.currentframe().f_code.co_name)
  user_info = json.loads(response.content)
  if user_info[0:1] == False:
    #Error if the target user does not exist
    raise AddGitLabException('Nothing user.', 404, inspect.currentframe().f_code.co_name)
  return user_info

#Add target members to the group
def add_group(user_id, level):
  success_group = []
  for group_info in target_group_list():
    for group_name, group_id in group_info.items():
      url = url_prefix + 'groups/' + str(group_id) + '/members'
      headers = {'Private-Token': private_token}
      response = requests.post(url, headers=headers, data={'user_id': user_id, 'access_level': level})
  
      # 200/201:Successful registration, 409:Not thrown as an exception because it is already registered
      if response.status_code != 200 and response.status_code != 201 and response.status_code != 409:
        raise AddGitLabException(response.content, response.status_code, inspect.currentframe().f_code.co_name + ' group_id:' + str(group_id))
      success_group.append(group_name + ':' + str(response.status_code))
  return success_group

#Get the target group
def target_group_list():
  return [
    {'[group_name1]' : [group_id1]},
    {'[group_name2]' : [group_id2]}
  ]

#Dedicated exception class
class AddGitLabException(Exception):
  def __init__(self, body, code, function):
    self.body = body
    self.code = code
    self.function = function

  def get_info(self):
    return {'body':self.body,'code':self.code, 'function': self.function}

print(main({'user':'test_user', 'level':'30'}))

The group ID is obtained manually by API (see below).

gitlabAPI v4 groups

For group_id, I used the groups API to get the group_id and did my best to list it (since I made a list once, I don't have to change much after that). I would like to know if there is a good way to narrow down to a specific group without trying hard to list it.

When gitlabApi is v3

If you're still working with older gitlab, you may only have v3 enabled.

There is a document below, so please try to rearrange it for reference.

https://gitlab.com/gitlab-org/gitlab-foss/blob/8-16-stable/doc/api/README.md

Recommended Posts

Use gitlabApi to add members to multiple groups in gitlab at once
Combine multiple dictionaries and add multiple elements at once, safely and non-destructively in Python
Register multiple self-made styles in Word at once
Convert images in multiple folders to different pdfs for each folder at once
[Linux] Grep multiple gzip files in a directory at once
Rsync multiple files at once
[Laravel] Aliase to create migration file of multiple tables at once
How to use classes in Theano
Mock in python-how to use mox
How to use SQLite in Python
How to use Mysql in python
How to use ChemSpider in Python
How to use PubChem in Python
Create multiple users with serial numbers at once in Ansible Playbook: Part 2
Add words to MeCab's user dictionary on Ubuntu for use in Python