Skip to main content

Chapter 9: GitHub CLI (gh) for Enterprise

Part IV: Developer Tooling & Workflows Prerequisites: Chapter 1: Enterprise Subscription & Environment Setup GH-100 Exam Mapping: Domain 1 (Support GitHub Enterprise for users and stakeholders — 9%) Verified: 2026-02-01 against official documentation

1. Introduction​

Learning Objectives​

After completing this chapter, you will be able to:

  • Install and authenticate the GitHub CLI (Command-Line Interface) across Windows, macOS, and Linux environments
  • Configure multi-account authentication for GitHub Enterprise Cloud and GitHub Enterprise Server hostnames
  • Execute repository management, pull request, and issue operations using gh commands
  • Automate enterprise workflows by scripting gh commands in CI/CD (Continuous Integration/Continuous Delivery) pipelines
  • Evaluate and install gh extensions to extend CLI capabilities for enterprise teams
  • Integrate the GitHub CLI into standardized developer workflows for organizations with 50+ developers

Exam Domain Coverage​

DomainTopics in This Chapter
D1: Support GitHub Enterprise for users and stakeholders (9%)CLI-based enterprise administration, repository management, authentication methods, API access via CLI

Chapter Overview​

The GitHub CLI (gh) is the official command-line tool for interacting with GitHub from a terminal. While the GitHub web interface serves well for occasional tasks, enterprise teams that manage hundreds of repositories, thousands of pull requests, and complex CI/CD pipelines need the speed and scriptability that only a CLI can provide. The gh tool bridges the gap between the GitHub REST/GraphQL APIs and everyday developer operations, providing a human-friendly interface that is equally powerful when embedded in automation scripts.

For enterprise organizations, the GitHub CLI is more than a convenience tool. It is a critical component of developer infrastructure. Teams use it to enforce consistent workflows, automate repository creation with standardized templates, manage pull request reviews at scale, and integrate GitHub operations into existing shell-based toolchains. When combined with GitHub Actions (see Chapter 12: GitHub Actions & Copilot-Powered CI/CD), the CLI becomes the backbone of enterprise automation.

This chapter covers the GitHub CLI from installation through advanced enterprise usage. You will learn how to authenticate against multiple GitHub Enterprise hostnames, manage repositories and pull requests efficiently, build automation scripts suitable for CI/CD pipelines, and leverage the extensions ecosystem to customize the CLI for your organization's specific needs. By the end of this chapter, you will be equipped to roll out the GitHub CLI as a standard tool across your enterprise development teams.


2. Theory & Deep Dive​

2.1 Installing the GitHub CLI​

The GitHub CLI is distributed as a standalone binary for all major operating systems. Enterprise teams should standardize on a single installation method per platform to simplify onboarding and version management.

Windows Installation​

On Windows, the recommended approach for enterprise environments is to use winget, the Windows Package Manager, which supports centralized software management:

# Install gh using winget (recommended for enterprise Windows environments)
winget install --id GitHub.cli

Alternatively, for organizations that manage software through Chocolatey:

# Install gh using Chocolatey
choco install gh

After installation, verify the installation:

# Verify gh is installed and check the version
gh --version

Expected output (version number will vary):

gh version 2.65.0 (2025-12-10)
https://github.com/cli/cli/releases/tag/v2.65.0

macOS Installation​

On macOS, Homebrew is the standard package manager for enterprise developer workstations:

# Install gh using Homebrew
brew install gh

Linux Installation​

For Debian/Ubuntu-based distributions:

# Add the GitHub CLI repository and install
(type -p wget >/dev/null || (sudo apt update && sudo apt-get install wget -y)) \
&& sudo mkdir -p -m 755 /etc/apt/keyrings \
&& out=$(mktemp) && wget -nv -O$out https://cli.github.com/packages/githubcli-archive-keyring.gpg \
&& cat $out | sudo tee /etc/apt/keyrings/githubcli-archive-keyring.gpg > /dev/null \
&& sudo chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
&& sudo apt update \
&& sudo apt install gh -y

For Red Hat/Fedora-based distributions:

# Install gh on Fedora/RHEL
sudo dnf install gh

Enterprise Version Pinning​

For organizations that need to pin a specific version for consistency across teams, the GitHub CLI releases are available as direct downloads from https://github.com/cli/cli/releases. Enterprise IT teams can host the binary on internal artifact servers and distribute it through configuration management tools such as Ansible, Puppet, or SCCM (System Center Configuration Manager).

Enterprise Scenario: A financial services company with 300 developers standardizes on a quarterly upgrade cycle for developer tools. Their platform engineering team downloads the approved gh version, runs it through security scanning, publishes it to an internal Artifactory repository, and distributes it via Ansible playbooks. Developers receive the update automatically on their next workstation provisioning cycle.

2.2 Authentication and Enterprise Hostname Configuration​

Authentication is the most critical step for enterprise usage. The GitHub CLI supports multiple authentication methods and can manage credentials for multiple GitHub hostnames simultaneously.

Interactive Authentication​

The simplest method for individual developers is the interactive login flow:

# Authenticate with github.com using the interactive browser flow
gh auth login

This command prompts you to select:

  1. The GitHub hostname (github.com or a GitHub Enterprise Server URL)
  2. The preferred protocol (HTTPS or SSH)
  3. The authentication method (browser-based OAuth or a Personal Access Token)

For GitHub Enterprise Server instances:

# Authenticate with a GitHub Enterprise Server instance
gh auth login --hostname github.example.com

Token-Based Authentication​

In automated environments such as CI/CD pipelines, token-based authentication is required. The GitHub CLI reads the GH_TOKEN or GITHUB_TOKEN environment variable:

# Set the token as an environment variable (CI/CD pipeline)
export GH_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

# Verify authentication status
gh auth status

In PowerShell on Windows:

# Set the token as an environment variable (PowerShell)
$env:GH_TOKEN = "ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Verify authentication status
gh auth status

Expected output:

github.com
✓ Logged in to github.com account your-username (GH_TOKEN)
- Active account: true
- Git operations protocol: https
- Token: ghp_************************************
- Token scopes: 'admin:org', 'repo', 'workflow'

Multi-Account Configuration​

Enterprise developers frequently need to work with multiple GitHub accounts -- for example, a personal account on github.com and a corporate account on a GitHub Enterprise Server (GHES) instance. The gh CLI supports this natively:

# Log in to github.com (personal or corporate cloud account)
gh auth login --hostname github.com

# Log in to GitHub Enterprise Server
gh auth login --hostname ghes.corpname.com

# Switch the active account for github.com
gh auth switch --hostname github.com --user corporate-username

# View all authenticated accounts
gh auth status

The CLI stores credentials in a platform-appropriate secure store:

  • Windows: Windows Credential Manager
  • macOS: macOS Keychain
  • Linux: Uses a helper (e.g., pass, secretservice) or falls back to a plain-text file at ~/.config/gh/hosts.yml

Enterprise Scenario: A consulting firm with 150 developers works across three GitHub Enterprise Cloud organizations and one on-premise GHES instance. Each developer authenticates to all four hostnames during onboarding. The platform team distributes a shell script that runs gh auth login with the appropriate --hostname flags, ensuring every developer has consistent access from day one.

Fine-Grained Personal Access Tokens (PATs)​

For enterprise use, fine-grained PATs are preferred over classic tokens because they allow scoping to specific repositories and permissions (see Chapter 8: Access Control & Permissions Model):

# Authenticate using a fine-grained PAT
gh auth login --with-token < my-token.txt

Enterprise administrators can enforce fine-grained PAT policies at the organization level, requiring approval for tokens that request access to organization resources.

2.3 Core CLI Operations for Enterprise Workflows​

The GitHub CLI organizes commands into logical groups. The most commonly used in enterprise environments are: repo, pr, issue, run, release, and api.

Repository Management​

Creating repositories from standardized templates is a common enterprise pattern:

# Create a new repository from an enterprise template
gh repo create my-org/new-microservice \
--template my-org/microservice-template \
--private \
--clone
# List all repositories in an organization
gh repo list my-org --limit 100

# View repository details
gh repo view my-org/my-repo

# Clone a repository
gh repo clone my-org/my-repo

# Fork a repository into your organization
gh repo fork upstream-org/library --org my-org --clone=false

Pull Request Workflows​

Pull requests are the core collaboration unit in GitHub. The CLI streamlines the entire lifecycle:

# Create a pull request with title and body
gh pr create --title "Add payment retry logic" \
--body "Implements exponential backoff for payment API failures" \
--base main \
--reviewer alice,bob \
--assignee @me \
--label "backend,payment"

# List open pull requests assigned to you
gh pr list --assignee @me --state open

# View pull request details including checks and reviews
gh pr view 42

# Check out a pull request locally for review
gh pr checkout 42

# Approve a pull request
gh pr review 42 --approve --body "LGTM - tested locally"

# Merge a pull request using squash strategy
gh pr merge 42 --squash --delete-branch

Issue Management​

# Create an issue from a template
gh issue create --title "Database connection pool exhaustion" \
--body "Under load, the service runs out of DB connections..." \
--label "bug,priority-high" \
--assignee @me \
--project "Sprint 24"

# List issues with specific labels
gh issue list --label "bug" --state open --limit 50

# Close an issue with a comment
gh issue close 123 --comment "Fixed in PR #456"

# Transfer an issue to another repository
gh issue transfer 123 my-org/other-repo

Workflow Run Management​

The CLI provides direct access to GitHub Actions workflow runs:

# List recent workflow runs
gh run list --limit 10

# View details of a specific run
gh run view 12345678

# Watch a run in real time
gh run watch 12345678

# Re-run failed jobs in a workflow run
gh run rerun 12345678 --failed

# Download workflow artifacts
gh run download 12345678 --name "test-results"

2.4 The gh api Command: Direct API Access​

The gh api command is one of the most powerful features for enterprise administrators. It provides authenticated access to any GitHub REST or GraphQL API endpoint without needing to manage tokens manually:

# REST API: List organization members
gh api orgs/my-org/members --paginate --jq '.[].login'

# REST API: Get repository topics
gh api repos/my-org/my-repo/topics

# GraphQL API: Query repository count for an organization
gh api graphql -f query='
query {
organization(login: "my-org") {
repositories(first: 0) {
totalCount
}
}
}
'

The --jq flag integrates jq-style filtering directly into the command, eliminating the need to pipe output through external tools:

# List all repositories with their visibility and language
gh api orgs/my-org/repos --paginate \
--jq '.[] | {name: .name, visibility: .visibility, language: .language}'

Enterprise Scenario: A platform engineering team at a 500-developer company uses gh api in a nightly cron job to audit all repositories across their three organizations. The script checks for repositories without branch protection rules, missing CODEOWNERS files, and disabled secret scanning. Results are posted to a Slack channel and tracked in an internal compliance dashboard.

2.5 Scripting and Automation in CI/CD Pipelines​

The GitHub CLI is designed to be scripting-friendly. Several features make it suitable for unattended automation.

Environment Variables for Configuration​

VariablePurposeExample
GH_TOKENAuthentication tokenghp_xxxx...
GH_ENTERPRISE_TOKENToken for GHES hostnameghp_xxxx...
GH_HOSTDefault hostnameghes.corpname.com
GH_REPODefault repositorymy-org/my-repo
NO_COLORDisable colored output1
GH_PAGERPager program for outputless

Structured Output with --json​

For scripting, always use the --json flag to produce machine-readable output:

# Get pull request data as JSON
gh pr list --json number,title,author,state --limit 20

# Combine with --jq for filtered output
gh pr list --json number,title,reviewDecision \
--jq '.[] | select(.reviewDecision == "APPROVED") | .number'

Using gh in GitHub Actions Workflows​

The gh CLI is pre-installed on all GitHub-hosted runners, and the GITHUB_TOKEN is automatically available:

# .github/workflows/auto-label.yml
name: Auto-label PRs by file path
on:
pull_request:
types: [opened, synchronize]

jobs:
label:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Label PR based on changed files
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Get the list of changed files
FILES=$(gh pr diff ${{ github.event.pull_request.number }} --name-only)

# Apply labels based on file paths
if echo "$FILES" | grep -q "^src/api/"; then
gh pr edit ${{ github.event.pull_request.number }} --add-label "api"
fi

if echo "$FILES" | grep -q "^docs/"; then
gh pr edit ${{ github.event.pull_request.number }} --add-label "documentation"
fi

if echo "$FILES" | grep -q "^\.github/workflows/"; then
gh pr edit ${{ github.event.pull_request.number }} --add-label "ci/cd"
fi

Bulk Operations Script​

Enterprise teams often need to perform operations across many repositories. Here is a pattern for bulk operations:

#!/usr/bin/env bash
# bulk-enable-secret-scanning.sh
# Enable secret scanning on all private repos in an organization

ORG="my-org"

# Get all private repository names
REPOS=$(gh repo list "$ORG" --visibility private --json name --jq '.[].name')

for REPO in $REPOS; do
echo "Enabling secret scanning for $ORG/$REPO..."
gh api --method PATCH "repos/$ORG/$REPO" \
-f security_and_analysis[secret_scanning][status]=enabled \
2>/dev/null && echo " Done." || echo " Failed."
done

The equivalent in PowerShell for Windows environments:

# bulk-enable-secret-scanning.ps1
# Enable secret scanning on all private repos in an organization

$Org = "my-org"

# Get all private repository names
$repos = gh repo list $Org --visibility private --json name --jq '.[].name' | ForEach-Object { $_.Trim() }

foreach ($repo in $repos) {
Write-Host "Enabling secret scanning for $Org/$repo..."
gh api --method PATCH "repos/$Org/$repo" `
-f 'security_and_analysis[secret_scanning][status]=enabled' 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host " Done."
} else {
Write-Host " Failed."
}
}

2.6 The Extensions Ecosystem​

GitHub CLI extensions are community or custom-built additions that add new subcommands to gh. Extensions are Git repositories that follow a naming convention (gh-<name>) and contain an executable.

Discovering and Installing Extensions​

# Search for extensions
gh extension search "dashboard"

# Install an extension
gh extension install dlvhdr/gh-dash

# List installed extensions
gh extension list

# Upgrade all extensions
gh extension upgrade --all

# Remove an extension
gh extension remove gh-dash
ExtensionCommandPurpose
gh-dashgh dashTerminal-based dashboard for PRs and issues across repos
gh-copilotgh copilotGitHub Copilot in the CLI (see Chapter 10: GitHub Copilot in the CLI)
gh-poigh poiSafely delete local branches that have been merged
gh-markdown-previewgh markdown-previewPreview markdown files locally
gh-changeloggh changelogGenerate changelogs from merged pull requests

Creating Custom Enterprise Extensions​

Organizations can build custom extensions tailored to their workflows. Extensions can be written in any language as long as they produce an executable:

# Create a new extension scaffold
gh extension create my-org-tool

# This creates the following structure:
# gh-my-org-tool/
# gh-my-org-tool (bash script or compiled binary)

Here is an example of a simple custom extension that lists all repositories missing a CODEOWNERS file:

#!/usr/bin/env bash
# gh-my-org-tool/gh-my-org-tool
# Extension: gh my-org-tool
# Lists repos in the specified org that lack a CODEOWNERS file

set -e

ORG="${1:?Usage: gh my-org-tool <org-name>}"

echo "Checking repositories in $ORG for missing CODEOWNERS..."
echo "======================================================="

REPOS=$(gh repo list "$ORG" --json name,nameWithOwner --jq '.[].nameWithOwner')

for REPO in $REPOS; do
# Check for CODEOWNERS in common locations
FOUND=false
for PATH_CHECK in "CODEOWNERS" ".github/CODEOWNERS" "docs/CODEOWNERS"; do
if gh api "repos/$REPO/contents/$PATH_CHECK" --silent 2>/dev/null; then
FOUND=true
break
fi
done

if [ "$FOUND" = false ]; then
echo "MISSING: $REPO"
fi
done

To distribute the extension internally, push it to a repository named gh-my-org-tool in your organization. Developers install it with:

# Install a custom enterprise extension from an internal repository
gh extension install my-org/gh-my-org-tool

Enterprise Scenario: A healthcare technology company with 200 developers builds a custom extension called gh-compliance that verifies all new repositories meet HIPAA (Health Insurance Portability and Accountability Act) compliance requirements: branch protection, signed commits, secret scanning enabled, and a SECURITY.md file present. The platform team requires this check to pass before any repository is approved for production workloads.

2.7 Enterprise Configuration and Aliases​

The GitHub CLI supports aliases that let teams standardize frequently used command patterns:

# Create an alias for a common PR creation workflow
gh alias set pr-ready 'pr create --base main --assignee @me --label "ready-for-review"'

# Create an alias for team standup: list your open PRs and assigned issues
gh alias set standup '!gh pr list --author @me --state open && echo "---" && gh issue list --assignee @me --state open'

# Create an alias for organization-wide search
gh alias set org-search 'search repos --owner my-org'

# Use the alias
gh pr-ready --title "Feature: Add user notifications"
gh standup

Aliases are stored in the CLI configuration file (~/.config/gh/config.yml on Linux/macOS, %APPDATA%\GitHub CLI\config.yml on Windows). Enterprise teams can distribute a base configuration file as part of their developer onboarding automation.

2.8 Security Considerations for Enterprise Usage​

When deploying the GitHub CLI across an enterprise, several security practices are essential:

  1. Token scope minimization: Use fine-grained PATs with the minimum required permissions. Avoid classic tokens with broad scopes in automation.

  2. Credential storage: On Linux systems, configure a secure credential helper rather than relying on plain-text token storage. Use gh auth setup-git to configure Git credential integration.

  3. CI/CD token handling: In GitHub Actions, use the built-in GITHUB_TOKEN which is automatically scoped to the repository. For cross-repository operations, use GitHub App installation tokens rather than PATs.

  4. Audit trail: All API calls made through gh are logged in the organization and enterprise audit log, providing traceability for compliance requirements.

  5. Network considerations: For organizations using a proxy, configure the HTTPS_PROXY or HTTP_PROXY environment variables. The GitHub CLI respects standard proxy environment variables.

# Configure proxy for corporate networks
export HTTPS_PROXY=http://proxy.corpname.com:8080

# Configure gh to work with Git over HTTPS behind a proxy
gh auth setup-git

3. Diagrams​

GitHub CLI Authentication and Command Flow​

flowchart TD
A[Developer Workstation] --> B{gh auth login}
B -->|Browser OAuth| C[GitHub OAuth Flow]
B -->|PAT / Token| D[Token Validation]
B -->|GH_TOKEN env var| D

C --> E[Credential Store]
D --> E

E -->|Windows| F[Windows Credential Manager]
E -->|macOS| G[macOS Keychain]
E -->|Linux| H[secretservice / pass / file]

A --> I{gh command}
I --> J[gh repo / pr / issue]
I --> K[gh api]
I --> L[gh run]
I --> M[gh extension]

J --> N[GitHub REST API]
K --> N
K --> O[GitHub GraphQL API]
L --> N

N --> P{Target Hostname}
O --> P
P -->|github.com| Q[GitHub Enterprise Cloud]
P -->|ghes.corp.com| R[GitHub Enterprise Server]

style A fill:#e1f5fe
style Q fill:#c8e6c9
style R fill:#c8e6c9
style E fill:#fff3e0

Figure 9.1: GitHub CLI authentication flow showing how credentials are stored per platform and how commands route to the appropriate GitHub hostname (Enterprise Cloud or Enterprise Server).

Enterprise CLI Automation Architecture​

flowchart LR
subgraph CI["CI/CD Pipeline"]
A1[GitHub Actions Runner] --> A2[gh CLI pre-installed]
A2 --> A3[GITHUB_TOKEN auto-injected]
end

subgraph Scripts["Automation Scripts"]
B1[Bulk Repo Management]
B2[Compliance Audits]
B3[Release Automation]
B4[PR Workflow Automation]
end

subgraph API["GitHub APIs"]
C1[REST API v3]
C2[GraphQL API v4]
end

subgraph Targets["Enterprise Targets"]
D1[200+ Repositories]
D2[50+ Teams]
D3[Org Settings]
end

A3 --> B1
A3 --> B2
A3 --> B3
A3 --> B4

B1 --> C1
B2 --> C2
B3 --> C1
B4 --> C1

C1 --> D1
C1 --> D2
C2 --> D1
C2 --> D3

style CI fill:#e3f2fd
style Scripts fill:#fce4ec
style API fill:#f3e5f5
style Targets fill:#e8f5e9

Figure 9.2: Enterprise automation architecture showing how the GitHub CLI integrates with CI/CD pipelines to manage repositories, teams, and organizational settings at scale.


4. Summary​

Key Takeaways:

  • The GitHub CLI (gh) provides authenticated, scriptable access to all GitHub features from the terminal, supporting both github.com and GitHub Enterprise Server hostnames simultaneously.
  • Enterprise teams should standardize CLI installation through package managers or internal artifact servers, pinning versions for consistency across 50+ developer workstations.
  • Multi-account authentication with gh auth login --hostname enables developers to work across multiple GitHub Enterprise Cloud organizations and on-premise GHES instances seamlessly.
  • The gh api command combined with --jq filtering and --paginate is the most powerful tool for enterprise administration tasks such as compliance audits, bulk configuration, and reporting.
  • Structured JSON output (--json and --jq flags) makes the CLI suitable for unattended automation in CI/CD pipelines, where GH_TOKEN or GITHUB_TOKEN environment variables provide authentication.
  • The extensions ecosystem allows organizations to build and distribute custom gh subcommands that encode enterprise-specific workflows, compliance checks, and operational standards.
  • All gh CLI operations are recorded in the GitHub audit log, providing the traceability that enterprise compliance teams require.

What's Next: See Chapter 10: GitHub Copilot in the CLI for how the gh copilot extension brings AI-powered command suggestions and explanations directly into your terminal workflow.


5. Hands-On Assignment​

Prerequisites Check: Before starting this lab, ensure you have completed:

  • A working GitHub Enterprise Cloud environment (Chapter 1: Enterprise Subscription & Environment Setup)
  • A personal access token or SSH key configured for authentication

Lab: Enterprise GitHub CLI Automation Setup​

Objective: Install the GitHub CLI, authenticate against a GitHub Enterprise Cloud organization, create and manage a repository using CLI commands, and build a shell script that audits repository settings across the organization.

Prerequisites:

  • A GitHub Enterprise Cloud trial or paid organization (see Chapter 1: Enterprise Subscription & Environment Setup)
  • Owner or admin access to the organization
  • A workstation with a supported shell (bash on macOS/Linux, PowerShell on Windows)
  • At least three repositories in the organization (create test repos if needed)

Assignment:

  1. Install the GitHub CLI on your workstation and verify the installation produces a valid version number.
  2. Authenticate to your GitHub Enterprise Cloud organization using the interactive browser flow. Verify your scopes include repo, admin:org, and workflow.
  3. Create a new private repository from the CLI using a template repository (create a simple template first if one does not exist). Add a description and clone it locally.
  4. Create a feature branch, make a change, push it, and create a pull request entirely from the CLI. Add a reviewer and a label.
  5. Write a shell script (bash or PowerShell) that uses gh api to list all repositories in your organization and report which ones do NOT have branch protection rules configured on their default branch. The script should output results in a table format.
  6. Install the gh-dash extension and use it to view your open pull requests across all organization repositories.

Expected Outcome: You should have a working GitHub CLI installation authenticated to your enterprise organization, a new repository created from a template with a pull request, and a compliance audit script that identifies unprotected repositories.

Validation:

  • gh auth status shows your enterprise organization with the correct scopes
  • The new repository appears in the organization's repository list
  • The pull request is visible and has the assigned reviewer and label
  • The audit script correctly identifies repositories without branch protection
  • gh extension list shows gh-dash installed

6. Step-by-Step Walkthrough​

This section provides a guided solution for the hands-on assignment above. If you completed the assignment independently, you can skip this section or use it to verify your approach.

Step 1: Install the GitHub CLI​

On Windows (PowerShell):

# Install using winget
winget install --id GitHub.cli

# Close and reopen your terminal, then verify
gh --version

On macOS (bash):

# Install using Homebrew
brew install gh

# Verify
gh --version

On Linux/Ubuntu (bash):

# Install using apt
sudo apt update && sudo apt install gh -y

# Verify
gh --version

Expected output:

gh version 2.65.0 (2025-12-10)
https://github.com/cli/cli/releases/tag/v2.65.0

Step 2: Authenticate to Your Enterprise Organization​

# Start the interactive login flow
gh auth login

When prompted, select:

  1. GitHub.com (for Enterprise Cloud)
  2. HTTPS as the protocol
  3. Login with a web browser

The CLI displays a one-time code. Press Enter to open the browser, paste the code, and authorize the application.

# Verify authentication and check scopes
gh auth status

Expected output:

github.com
✓ Logged in to github.com account your-username (keyring)
- Active account: true
- Git operations protocol: https
- Token: ghp_************************************
- Token scopes: 'admin:org', 'read:org', 'repo', 'workflow'

If scopes are insufficient, refresh with:

# Request additional scopes
gh auth refresh --scopes admin:org,repo,workflow

Step 3: Create a Repository from a Template​

First, if you do not have a template repository, create one:

# Create a template repository
gh repo create my-org/microservice-template --public --description "Starter template for microservices"

# Clone it, add a basic file, push, then mark as template via the web UI or API
gh repo clone my-org/microservice-template
cd microservice-template

Create a basic README:

# Add a starter README (bash)
echo "# Microservice Template" > README.md
echo "Starter template for enterprise microservices." >> README.md
git add README.md && git commit -m "Add starter README" && git push

Mark the repository as a template (requires the API):

# Mark the repo as a template
gh api --method PATCH repos/my-org/microservice-template \
-F is_template=true

Now create a new repository from the template:

# Create a new repo from the template
gh repo create my-org/payment-service \
--template my-org/microservice-template \
--private \
--description "Payment processing microservice" \
--clone

Expected output:

✓ Created repository my-org/payment-service on GitHub
https://github.com/my-org/payment-service
Cloning into 'payment-service'...

Step 4: Create a Branch, Make a Change, and Open a Pull Request​

# Navigate into the cloned repository
cd payment-service

# Create and switch to a feature branch
git checkout -b feature/add-healthcheck

# Create a health check endpoint file
echo '{"status": "ok"}' > healthcheck.json

git add healthcheck.json
git commit -m "Add health check endpoint configuration"

# Push the branch to GitHub
git push --set-upstream origin feature/add-healthcheck

Now create the pull request using the CLI:

# Create a pull request with reviewer and label
gh pr create \
--title "Add health check endpoint" \
--body "Adds a health check configuration file for load balancer integration.

## Changes
- Added healthcheck.json with status response

## Testing
- Verified JSON is valid" \
--base main \
--reviewer teammate-username \
--label "enhancement"

Expected output:

Creating pull request for feature/add-healthcheck into main in my-org/payment-service

https://github.com/my-org/payment-service/pull/1

If the label does not exist, create it first:

# Create a label if it does not exist
gh label create enhancement --description "New feature or request" --color 0E8A16

Step 5: Write a Repository Compliance Audit Script​

Create the following script:

bash version (audit-branch-protection.sh):

#!/usr/bin/env bash
# audit-branch-protection.sh
# Reports repositories in an organization that lack branch protection on their default branch

set -euo pipefail

ORG="${1:?Usage: $0 <org-name>}"

echo "Branch Protection Audit for organization: $ORG"
echo "================================================"
printf "%-40s %-15s %-10s\n" "REPOSITORY" "DEFAULT BRANCH" "PROTECTED"
printf "%-40s %-15s %-10s\n" "----------------------------------------" "---------------" "----------"

# Get all repos with their default branch
gh api "orgs/$ORG/repos" --paginate \
--jq '.[] | [.name, .default_branch] | @tsv' |
while IFS=$'\t' read -r REPO DEFAULT_BRANCH; do
# Check if branch protection exists
PROTECTED="No"
if gh api "repos/$ORG/$REPO/branches/$DEFAULT_BRANCH/protection" --silent 2>/dev/null; then
PROTECTED="Yes"
fi
printf "%-40s %-15s %-10s\n" "$REPO" "$DEFAULT_BRANCH" "$PROTECTED"
done

PowerShell version (audit-branch-protection.ps1):

# audit-branch-protection.ps1
# Reports repositories in an organization that lack branch protection on their default branch

param(
[Parameter(Mandatory=$true)]
[string]$Org
)

Write-Host "Branch Protection Audit for organization: $Org"
Write-Host "================================================"
Write-Host ("{0,-40} {1,-15} {2,-10}" -f "REPOSITORY", "DEFAULT BRANCH", "PROTECTED")
Write-Host ("{0,-40} {1,-15} {2,-10}" -f ("-" * 40), ("-" * 15), ("-" * 10))

# Get all repos with their default branch
$repos = gh api "orgs/$Org/repos" --paginate --jq '.[] | [.name, .default_branch] | @csv' |
ConvertFrom-Csv -Header "Name","DefaultBranch"

foreach ($repo in $repos) {
$protected = "No"
$null = gh api "repos/$Org/$($repo.Name)/branches/$($repo.DefaultBranch)/protection" 2>$null
if ($LASTEXITCODE -eq 0) {
$protected = "Yes"
}
Write-Host ("{0,-40} {1,-15} {2,-10}" -f $repo.Name, $repo.DefaultBranch, $protected)
}

Run the script:

# Make executable and run (bash)
chmod +x audit-branch-protection.sh
./audit-branch-protection.sh my-org

Expected output:

Branch Protection Audit for organization: my-org
================================================
REPOSITORY DEFAULT BRANCH PROTECTED
---------------------------------------- --------------- ----------
payment-service main No
microservice-template main No
frontend-app main Yes

Step 6: Install and Use the gh-dash Extension​

# Install the gh-dash extension
gh extension install dlvhdr/gh-dash

# Verify installation
gh extension list

Expected output:

NAME            REPO                  VERSION
gh-dash dlvhdr/gh-dash v4.7.0
# Launch the dashboard
gh dash

This opens an interactive terminal dashboard showing your pull requests and issues. Press ? for keyboard shortcuts. Press q to exit.

Verification​

Run the following commands to confirm all lab objectives are met:

# 1. Verify authentication
gh auth status

# 2. Verify the new repository exists
gh repo view my-org/payment-service

# 3. Verify the pull request exists with correct attributes
gh pr view 1 --repo my-org/payment-service --json title,labels,reviewRequests

# 4. Verify extensions are installed
gh extension list

# 5. Run the audit script one more time to confirm it works
./audit-branch-protection.sh my-org

7. Q&A -- Chapter Review​

Instructions: Select the best answer for each question. Answers and explanations follow after all questions.

Question 1​

Which environment variable does the GitHub CLI use for authentication when running in a CI/CD pipeline?

  • A) GITHUB_CLI_TOKEN
  • B) GH_TOKEN
  • C) GH_AUTH_KEY
  • D) GITHUB_API_KEY

Question 2​

A developer needs to work with both github.com and an on-premise GitHub Enterprise Server instance at ghes.acme.com. Which command authenticates them to the Enterprise Server?

  • A) gh auth login --server ghes.acme.com
  • B) gh auth login --hostname ghes.acme.com
  • C) gh auth login --enterprise ghes.acme.com
  • D) gh login --host ghes.acme.com

Question 3​

An enterprise platform team wants to list all repositories in their organization and output only the repository names as plain text. Which command achieves this?

  • A) gh repo list my-org --json name --jq '.[].name'
  • B) gh repo list my-org --format text --field name
  • C) gh api orgs/my-org/repos --output names
  • D) gh repo list my-org | cut -d ' ' -f 1

Question 4​

Which gh subcommand provides direct authenticated access to any GitHub REST or GraphQL API endpoint?

  • A) gh rest
  • B) gh curl
  • C) gh api
  • D) gh request

Question 5​

A team lead wants to create a pull request from the CLI that automatically assigns two reviewers and applies the "urgent" label. Which command accomplishes this?

  • A) gh pr create --title "Fix" --reviewer alice,bob --label urgent
  • B) gh pr new --title "Fix" --assign-reviewer alice bob --tag urgent
  • C) gh pr create --title "Fix" --request-review alice bob --add-label urgent
  • D) gh pr open --title "Fix" --reviewers alice,bob --labels urgent

Question 6​

What is the naming convention required for GitHub CLI extension repositories?

  • A) cli-extension-<name>
  • B) gh-ext-<name>
  • C) gh-<name>
  • D) github-cli-<name>

Question 7​

An automation script needs to process the output of gh pr list programmatically. Which flags should be used to get structured, machine-readable output filtered to specific fields?

  • A) --format json --fields number,title
  • B) --json number,title --jq '.[]'
  • C) --output json --select number,title
  • D) --machine-readable --columns number,title

Question 8​

In a GitHub Actions workflow, what is the recommended way to authenticate gh commands?

  • A) Run gh auth login interactively in the workflow
  • B) Store a PAT in a repository secret and set GH_TOKEN
  • C) Use the automatically available GITHUB_TOKEN via the GH_TOKEN environment variable
  • D) Use SSH key authentication configured on the runner

Question 9​

An enterprise administrator wants to ensure that all gh api calls paginate through the complete result set when querying organizations with hundreds of repositories. Which flag should they add?

  • A) --all-pages
  • B) --paginate
  • C) --follow-next
  • D) --page-limit 0

Question 10​

A platform team distributes a standardized set of gh aliases to all 150 developers. Where are these aliases stored on a Linux workstation?

  • A) /etc/gh/aliases.conf
  • B) ~/.gh/aliases.yml
  • C) ~/.config/gh/config.yml
  • D) ~/.local/share/gh/config.json

Answer Key​

QAnswerExplanation
1BThe GitHub CLI reads the GH_TOKEN environment variable (or GITHUB_TOKEN as a fallback) for authentication in non-interactive environments such as CI/CD pipelines.
2BThe --hostname flag specifies the GitHub Enterprise Server URL when authenticating with gh auth login. This allows the CLI to store separate credentials per hostname.
3AThe gh repo list command supports --json for structured output and --jq for filtering. The expression '.[].name' extracts only the repository names from the JSON array.
4CThe gh api command provides direct, authenticated access to any GitHub REST or GraphQL API endpoint, automatically handling authentication headers and pagination.
5AThe gh pr create command uses --reviewer for assigning reviewers (comma-separated) and --label for applying labels. This is the correct syntax for the current CLI version.
6CGitHub CLI extensions must follow the naming convention gh-<name> for their repository. The CLI discovers and invokes extensions based on this prefix convention.
7BThe --json flag specifies which fields to include in structured JSON output, and --jq applies a jq filter expression for further processing. Together they produce machine-readable, filtered output.
8CIn GitHub Actions, the GITHUB_TOKEN is automatically generated for each workflow run with permissions scoped to the repository. Setting GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} is the recommended, most secure approach.
9BThe --paginate flag instructs gh api to follow pagination links automatically, retrieving all pages of results. This is essential for organizations with large numbers of repositories or members.
10COn Linux (and macOS), the GitHub CLI stores its configuration, including aliases, in ~/.config/gh/config.yml. On Windows, the path is %APPDATA%\GitHub CLI\config.yml.