Get all SSH public keys from gitlab
Published: 26-08-2020 | Author: Remy van Elst | Text only version of this article
❗ This post is over two years old. It may no longer be up to date. Opinions may have changed.
Table of Contents
This small snippet gets all the SSH keys from a gitlab instance. You need to be an administrator, then you can query all keys at once using the API. On the web frontend you can only see the keys per user, not all at once in an overview.
[If you like this snippet, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get $100 credit for 60 days). (referral link)]
jq to filter out specific fields of the JSON API output, but you can
omit that and just use shell (
sed) if you want to.
SSH keys via the API
In [the API] you can query keys by ID. As far as I could find, there is no way to find out how many keys there are, so you have to gamble that a bit, in my case 500 was enough since the gitlab instace I used only has 400-ish users.
You also need a personal access token for your administrative account, which
you can create via your gitlab profile, under
Settings and then
This is the full command:
for i in $(seq 1 500); do curl --silent --header "PRIVATE-TOKEN: $your_token_here" "https://your_gitlab_URL.com/api/v4/keys/$i" | \ jq -M -c -r '[.key, .user.name]' | \ grep -v null ; done
Replace the token and domain name by your domain name.
["ssh-rsa AAAAB3NzaC1y[...]zmSDQ== key1","User Name"] ["ssh-rsa AAAAB3NzaC1y[...]GaE6cC1 key2","User Name"] ["ssh-ed25519 AAAAC3N[...]9W key5", "Other User Name"]
You can use the
|@tsv output modifier to get rid of the quotes and
for i in $(seq 1 500); do curl --silent --header "PRIVATE-TOKEN: $your_token_here" "https://your_gitlab_URL.com/api/v4/keys/$i" | \ jq -M -c -r '[.key, .user.name]|@tsv' | \ grep -v null ; done
Tags: bash , curl , git , gitlab , jq , json , shell , snippets , ssh
ssh-ed25519 AAAAC3N[...]9W key5 Other User Name