Find the Gitlab user ID by username, automagicallylinux gitlab sysadmin automation en
The other day, I looked for a solution to automate kicking users off my Gitlab instance (for example during the process of an employee leaving the company). My idea was to simply do that through Gitlab’s REST API, but I quickly realized that the
/users endpoint can not deal with usernames but expects Gitlab’s unique user IDs, and I did not find an easily automatable way to find that ID based on the username. There might be a way using the Gitlab Search API but that seemed like a rabbit hole I didn’t wanna go down, and other than that the only place the ID shows up is in the Admin Area on the user’s page. So instead, I decided to brute-force it and simply get all users from the API, compare the username and return the ID in the case of a match. Not the most elegant solution, but as we know:
If it looks stupid, but it works, it ain't stupid. ;)
For parsing the JSON that the API returns, I used jq which is “a lightweight and flexible command-line JSON processor” and an amazing tool that you should check out, here: https://stedolan.github.io/jq/. Thanks to jq I was able to build this hack in as a Bash script (y’know, for extra hack-ness) without having to use a proper programming language.
This way, you can simply execute the script, supplying the Gitlab username as the sole argument, and put the returned value into your script to do whatever. OR, if you’re brave: since the script returns only the user ID and nothing else, you can run it directly from within the command you use it with and have Bash expand it, like so:
curl --request POST "https://git.example.net/api/v4/users/$(~/scripts/get-gitlab-user-id-by-name.sh homer.simpson)/block" --header "PRIVATE-TOKEN: $GIT_PRIVATE_TOKEN"
Truly worthy of this dirty script. Don’t tell anyone I told you that!