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
@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