Skip to content

Instantly share code, notes, and snippets.

@lorello
Created April 5, 2019 13:13
Show Gist options
  • Select an option

  • Save lorello/86ea96e82ed4a96d3e36288740baf071 to your computer and use it in GitHub Desktop.

Select an option

Save lorello/86ea96e82ed4a96d3e36288740baf071 to your computer and use it in GitHub Desktop.
Add the ssh public keys of a github team to a local user
#!/bin/bash
#
# Enable an ops team defined in github to connect to a server using ssh keys
#
# Requirements:
#
# - jq
# - httpie
#
# On debian based:
#
# sudo apt install httpie jq
#
# Install
#
# - set GITHUB_TOKEN environment variable (for example in ~/.bashrc of the user
# - schedule in user's cron, where you want the keys to be added:
#
# @hourly /usr/local/bin/get_github_team_keys <organization> <team>
#
[ $TRACE ] && set -x
org='OpencontentCoop'
base_url='https://api.github.com'
auth_file=~/.ssh/authorized_keys
ask()
{
local path=$1
local headers
[ -n $GITHUB_TOKEN ] && header_auth="Authorization: token $GITHUB_TOKEN"
headers="Accept: application/vnd.github.hellcat-preview+json"
if [[ $path =~ http(s)?:.* ]]; then
url="$path"
else
url="${base_url}/${path}"
fi
http get "$url" "$headers" "$header_auth"
}
orgs.getTeamMembers()
{
local name=$1
local team_id
team_id=$(ask orgs/${org}/teams | jq -c '.[] | select( .name| contains("ops")) | .id')
ask teams/${team_id}/members | jq --raw-output -c '.[].login'
}
orgs.getTeamKeys()
{
local team_name=$1
for user in $(orgs.getTeamMembers $team_name); do
public_keys="https://github.com/${user}.keys"
keys=$(http get $public_keys)
if [[ $? -eq 0 ]]; then
if [[ -n "$keys" ]]; then
echo "${keys} ${user}@github"
fi
fi
done
}
[[ ! -d $(dirname $auth_file) ]] && mkdir -p $(dirname $auth_file)
orgs.getTeamKeys $team_name | while read key
do
# remove the comment, could be different, altered, coming from another source
key_parts=($key)
key_to_match="${key_parts[0]} ${key_parts[1]}"
# check if the key is already authorized
if grep -q "$key_to_match" $auth_file; then
echo -e "Key is already authorized: $key"
else
echo -e "Missing key, adding to $auth_file"
echo "$key" >> $auth_file
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment