Skip to content

Instantly share code, notes, and snippets.

@rammanokar
Created July 8, 2024 09:37
Show Gist options
  • Save rammanokar/9a32cfdeca0188f47b811f04af42399d to your computer and use it in GitHub Desktop.
Save rammanokar/9a32cfdeca0188f47b811f04af42399d to your computer and use it in GitHub Desktop.
Automate GitHub Team Permissions with Bash Script
#!/bin/bash
# Define variables
ORG="myOrg"
TEAM="myTeam"
PERMISSION="push"
# Check if the team exists
team_exists=$(gh api \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
/orgs/$ORG/teams/$TEAM)
if [ -z "$(echo $team_exists | jq '.id')" ]; then
echo "Team $TEAM does not exist in organization $ORG."
exit 1
fi
# Fetch all repositories in the organization
repos=$(gh api \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
/orgs/$ORG/repos | jq -r '.[].name')
# Grant write access to the team for each repository
for repo in $repos; do
echo "Granting $PERMISSION access to $TEAM for repository $repo..."
# Attempt to grant access
response=$(gh api --method PUT \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
/orgs/$ORG/teams/$TEAM/repos/$ORG/$repo \
-f permission=$PERMISSION 2>&1)
if echo "$response" | grep -q '"message": "Validation Failed"'; then
echo "Failed to grant $PERMISSION access to $TEAM for repository $repo. Response: $response"
else
echo "Successfully granted $PERMISSION access to $TEAM for repository $repo."
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment