Skip to content

Instantly share code, notes, and snippets.

@narze
Created July 22, 2022 08:33
Show Gist options
  • Save narze/2c2e141f03daea2c23fc5795107d41d4 to your computer and use it in GitHub Desktop.
Save narze/2c2e141f03daea2c23fc5795107d41d4 to your computer and use it in GitHub Desktop.
Add repos to team with gh
#!/bin/bash
PERMISSION="push" # Can be one of: pull, push, admin, maintain, triage
ORG="orgname"
TEAM_SLUG="your-team-slug"
# Get names with `gh repo list orgname`
REPOS=(
"orgname/reponame"
)
for REPO in "${REPOS[@]}"; do
echo "Adding repo ${REPO} to Org:$ORG Team:$TEAM_SLUG"
# https://docs.github.com/en/rest/teams/teams#add-or-update-team-repository-permissions
# (needs admin:org scope)
# --silent added to make it less noisy
gh api \
--method PUT \
-H "Accept: application/vnd.github+json" \
--silent \
"/orgs/$ORG/teams/$TEAM_SLUG/repos/$REPO" \
-f permission="$PERMISSION" && echo 'Added' || echo 'Failed'
echo "\n============================================================\n"
done
@richmahn
Copy link

richmahn commented Oct 12, 2022

For those who need it, you can get change the REPOS=(...) lines to:

REPOS=($(gh repo list $ORG --limit 200 --json name --json owner -q '.[] | "\(.owner.login)/\(.name)"'

@narze
Copy link
Author

narze commented Oct 18, 2022

That's nice!

@damien-qc
Copy link

working like a charm, thank you both for the script and list of all repos. had me skip adding 80ish repos 1 by 1. much appreciated

@complacent
Copy link

ditto here - super helpful, thanks!

@jay-flood
Copy link

Thank you for sharing this. You saved my day!

@dmotylev
Copy link

For a long list of repositories, one can replace L7-L12 with

# Get names with `gh repo list orgname`
gh repo list $ORG --limit 1000 --json name --json owner -q '.[] | "\(.owner.login)/\(.name)"' | while read -r REPO; do
  echo "Adding repo ${REPO} to Org:$ORG Team:$TEAM_SLUG"

Note the --limit 1000 as well.

@swiknaba
Copy link

gh repo list also provides a nameWithOwner field, which allows for the following simplification:

REPOS=$(gh repo list "$ORG" --limit 1000 --json nameWithOwner -q '.[] | "\(.nameWithOwner)"')

A slightly updated gh command for adding repos to the team:

for REPO in "${REPOS[@]}"; do
 gh api \
  --method PUT \
  -H "Accept: application/vnd.github+json" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  /orgs/$ORG/teams/$TEAM_SLUG/repos/$REPO \
   -f "permission=$PERMISSION"
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment