Managing Secrets via REST API
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 10 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Managing GitHub Actions Secrets and Variables via REST API
Introduction: The Scale of Automation
In the modern software development lifecycle, GitHub Actions has become the standard for CI/CD pipelines. As organizations grow, manual configuration of repositories becomes unsustainable. When you are managing hundreds or thousands of repositories across an enterprise, manually entering secrets like API keys, database credentials, or environment-specific tokens into the GitHub UI is not just tedious—it is a significant operational bottleneck and a security risk.
Managing secrets and variables programmatically via the GitHub REST API is essential for achieving "Configuration as Code" at the enterprise level. By automating the injection, rotation, and synchronization of these sensitive values, you ensure that your security posture remains consistent across your entire organization. This lesson explores how to interact with the GitHub API to manage these assets, the cryptographic requirements involved, and the best practices for maintaining security at scale.
Not read yet
Understanding the Architecture of GitHub Secrets
Before diving into the API, it is vital to understand the hierarchy of secrets within GitHub. GitHub provides three distinct scopes for secrets and variables:
- Repository Secrets: Available only to a specific repository. These are the most common and granular form of configuration.
- Environment Secrets: Tied to specific environments (like "production" or "staging") within a repository. These are useful for restricting access to sensitive production credentials.
- Organization Secrets: Available to all repositories within an organization, or restricted to specific repositories. These are ideal for enterprise-wide credentials, such as internal artifact registry credentials or shared cloud service principals.
The Role of Public Key Encryption
GitHub requires that secrets be encrypted before they are sent over the API. You cannot simply send a plaintext string in a JSON payload. This is a deliberate security measure to ensure that secrets are never exposed in plaintext during transit or in the GitHub server logs.
To encrypt a secret, you must:
- Fetch the organization’s or repository’s public key using the API.
- Use the Libsodium library to encrypt your secret value using that public key.
- Encode the resulting encrypted value in Base64 format.
- Send the Base64-encoded string to the appropriate API endpoint.
Callout: Why Encryption Matters The requirement to encrypt secrets client-side before transmission is a core security feature of the GitHub API. By offloading the encryption process to your own environment, GitHub ensures that your sensitive data is protected by industry-standard cryptographic libraries (libsodium) before it ever hits the network. This prevents "man-in-the-middle" attacks and ensures that even if your API communication were intercepted, the secret data remains unreadable.
Not read yet
Preparing Your Environment
To interact with the GitHub REST API, you need a few prerequisites. First, you need a Personal Access Token (PAT) or a GitHub App installation token with the appropriate permissions. For managing organization-level secrets, your token needs the admin:org scope. For repository-level secrets, you need repo scope permissions.
Essential Tools
- cURL or HTTP Client: A tool to send requests (cURL, Postman, or Python’s
requestslibrary). - Libsodium: You will need a language-specific implementation of Libsodium (e.g.,
pynaclfor Python,tweetnaclfor JavaScript). - GitHub CLI (gh): While the API is the focus here, the
ghCLI tool is often the easiest way to generate the necessary keys and test your logic.
Step-by-Step: Managing Repository Secrets
Let’s walk through the process of creating or updating a repository secret using Python, as it is the most common language for automation scripts.
Step 1: Fetch the Repository Public Key
Before you can encrypt, you need the public key associated with the repository.
import requests
# Set up headers
headers = {
"Authorization": "token YOUR_GITHUB_TOKEN",
"Accept": "application/vnd.github.v3+json"
}
# Fetch the public key
url = "https://api.github.com/repos/OWNER/REPO/actions/secrets/public-key"
response = requests.get(url, headers=headers)
key_data = response.json()
key_id = key_data['key_id']
public_key = key_data['key']
Step 2: Encrypt the Secret
Once you have the public key, you must use the pynacl library to encrypt the plaintext secret.
from base64 import b64encode
from nacl import encoding, public
def encrypt(public_key: str, secret_value: str) -> str:
# Convert the public key to a box
public_key_bytes = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder)
seal_box = public.SealBox(public_key_bytes)
# Encrypt the secret
encrypted = seal_box.encrypt(secret_value.encode("utf-8"))
# Return as base64
return b64encode(encrypted).decode("utf-8")
encrypted_value = encrypt(public_key, "my-super-secret-password")
Step 3: Push the Secret to GitHub
Finally, you perform a PUT request to create or update the secret.
put_url = "https://api.github.com/repos/OWNER/REPO/actions/secrets/MY_SECRET_NAME"
payload = {
"encrypted_value": encrypted_value,
"key_id": key_id
}
requests.put(put_url, json=payload, headers=headers)
Warning: Secret Naming Conventions GitHub secret names are case-insensitive and can only contain alphanumeric characters and underscores. They cannot start with
GITHUB_or a number. Always validate your secret names against these constraints in your script before attempting the API call to avoid 422 Unprocessable Entity errors.
Not read yet
Managing Organization-Level Secrets
Managing organization-level secrets follows a similar pattern but targets different API endpoints. This is highly beneficial when you have a standard set of credentials, such as a cloud provider's service account, that every repository in your company needs to access.
API Endpoints for Organization Secrets
- List Org Secrets:
GET /orgs/{org}/actions/secrets - Get Org Public Key:
GET /orgs/{org}/actions/secrets/public-key - Create/Update Org Secret:
PUT /orgs/{org}/actions/secrets/{secret_name}
The primary difference when moving from repository-level to organization-level management is the scope of visibility. When you create an organization secret, you must specify which repositories can access it using the visibility field in your JSON payload. The options are:
all: All repositories in the organization can access the secret.private: Only private repositories can access the secret.selected: Only repositories specifically listed can access the secret.
If you choose selected, you must also provide the selected_repository_ids array in your request.
Not read yet
Comparing Secrets vs. Variables
It is important to distinguish between Secrets and Variables in the context of GitHub Actions. While they are managed via similar API endpoints, they serve different purposes.
| Feature | Secrets | Variables |
|---|---|---|
| Visibility | Encrypted, masked in logs | Plaintext, visible in logs |
| Usage | Sensitive data (keys, passwords) | Configuration (URLs, flags, versions) |
| Encryption | Required (Libsodium) | None required |
| Security | Highly restricted access | Low security risk |
Variables are designed for non-sensitive configuration data. Because they are not encrypted, you do not need to perform the Libsodium dance when interacting with the /actions/variables API endpoints. You simply pass the value as a standard string in your JSON body.
Best Practices for Enterprise Secret Management
When implementing automated secret management, you are essentially building a security-critical infrastructure. Neglecting the following best practices can lead to credential leakage or broken pipelines.
1. Implement Secret Rotation
Secrets should not be static. Use your automation scripts to periodically rotate secrets. If you are using a tool like HashiCorp Vault or AWS Secrets Manager, your script should:
- Fetch the new secret from the vault.
- Encrypt it using the GitHub public key.
- Update the secret in GitHub.
- Log the success of the rotation without logging the secret value itself.
2. Principle of Least Privilege
Do not use a single "God-mode" token for your automation. Create a dedicated GitHub App or a machine user account with specific permissions. If you are managing organization secrets, the token should only have access to those specific endpoints and not have broad repository write access if it is not required.
3. Idempotency in Scripts
Ensure your scripts are idempotent. If you run your script to update a secret, it should first check if the secret exists. If it does, it should perform an update; if it doesn't, it should perform a creation. This prevents your automation from failing during subsequent runs due to "already exists" errors.
4. Audit Logging
Every time your script interacts with the API, log the action. Record the timestamp, the target repository/organization, the name of the secret being updated, and the status of the request. Never include the content of the secret in your logs.
Callout: Secrets in Logs GitHub automatically attempts to mask secret values in workflow logs if they are defined in the repository or environment. However, this is not foolproof. If a script prints a secret value, or if a base64-encoded version of a secret appears in a log, GitHub may not detect it. Always sanitize your output and double-check your logging logic to ensure no sensitive data is leaked to stdout.
Not read yet
Handling Common Pitfalls
The "401 Unauthorized" Error
This is the most common issue. It almost always relates to token scope. If you are trying to update an organization secret, ensure your PAT has the admin:org scope enabled. If you are using a GitHub App, ensure the "Organization secrets" permission is granted in the App's settings under "Repository permissions" or "Organization permissions."
The "422 Unprocessable Entity" Error
This usually indicates a problem with the payload. Check the following:
- Key ID Mismatch: Are you using the
key_idthat corresponds to the public key you just fetched? If you have multiple keys or if the key rotated, using an oldkey_idwill cause the API to reject the request. - Encryption Failure: If your Libsodium implementation is slightly off, the encrypted string will be invalid. Ensure you are using the correct padding and encoding schemes (Base64).
- Name Constraints: Double-check that your secret name doesn't violate GitHub's naming rules (no special characters, no leading numbers, etc.).
Managing Large Batches of Repositories
If you are updating secrets across 500 repositories, do not send 500 requests synchronously. Use an asynchronous approach (like asyncio in Python or a queue-based system) to handle the requests. GitHub has API rate limits. If you hit those limits, your script will receive a 403 Forbidden with a "rate limit exceeded" message. Implement a back-off strategy in your code to wait if you receive a rate-limit response.
Not read yet
Implementing a Robust Automation Flow
To truly manage secrets at scale, you should move away from running scripts on your local machine. Instead, integrate your secret management logic into a centralized automation server or a "Management Repository."
A Centralized Management Repository Pattern
- Define Configuration: Create a YAML file in a central repository that defines which secrets belong to which repositories.
# secrets_config.yaml secrets: - name: DB_PASSWORD repos: [repo-a, repo-b, repo-c] source: vault-path/prod-db - Triggered Sync: Use a GitHub Action in this management repository that triggers on a push to
mainor on a schedule. - Execution: The action runs your Python script, which reads the YAML, fetches the latest values from your secret store, and updates the targeted GitHub repositories using the API.
- Reporting: Have the script output a summary of updated repositories to a GitHub Issue or a Slack channel for visibility.
This approach provides a clear audit trail. You can see exactly who changed a secret configuration by looking at the Git history of the secrets_config.yaml file.
Not read yet
Advanced: Using GitHub Apps for Authentication
While Personal Access Tokens (PATs) are easy to set up, they are tied to a specific user. If that user leaves the company, your automation breaks. For enterprise-grade automation, use GitHub Apps.
GitHub Apps allow for "fine-grained" permissions. You can create an app, give it exactly the permissions it needs (e.g., Secrets: Read/Write), and install it on your organization. Authentication then happens via a private key that the app uses to generate short-lived installation tokens.
Steps to authenticate with a GitHub App:
- Generate a JWT: Use the app’s private key to sign a JSON Web Token (JWT).
- Request Installation Token: Send the JWT to the GitHub API endpoint
/app/installations/{installation_id}/access_tokens. - Use the Token: Use the resulting token to perform your secret management tasks.
This is the most secure way to automate because it removes the risk of a long-lived user token being compromised.
Not read yet
Comparison: Manual vs. Automated Secret Management
| Aspect | Manual Management | Automated API Management |
|---|---|---|
| Scalability | Low (Linear effort) | High (Constant effort) |
| Consistency | Error-prone | High (Policy-driven) |
| Auditability | Poor (UI logs only) | Excellent (Git history + Custom logs) |
| Security | High risk of human error | Hardened by code/automation |
| Rotation | Slow and manual | Rapid and automated |
Summary of Key Takeaways
- Encryption is Mandatory: You cannot send secrets in plaintext. Always fetch the public key and use Libsodium to encrypt values before calling the API.
- Hierarchy Matters: Understand the difference between repository, environment, and organization-level secrets to ensure you are targeting the correct API endpoints.
- Use Automation for Scale: Manual entry is a security and operational liability. Use scripts or dedicated management repositories to enforce consistency across thousands of repositories.
- Prioritize Security: Use GitHub Apps rather than Personal Access Tokens to avoid reliance on individual user accounts and to enforce the principle of least privilege.
- Build Idempotency: Ensure your automation scripts check for existing configurations before attempting to create new ones to prevent errors and ensure reliability.
- Rate Limiting Awareness: When managing large numbers of repositories, implement asynchronous processing and handle rate-limit responses gracefully to prevent pipeline failure.
- Separation of Concerns: Keep your secret values in a hardened vault (like HashiCorp Vault or AWS Secrets Manager) and use GitHub as the consumer of those secrets, rather than the primary storage location.
By mastering the GitHub REST API for secret management, you transition from being a passive user of CI/CD tools to an active architect of your enterprise’s security infrastructure. This programmatic approach is the foundation for building resilient, secure, and scalable development environments that allow your engineering teams to focus on shipping code rather than managing credentials.
Not read yet
Frequently Asked Questions (FAQ)
Q: Can I retrieve the value of a secret once it is set? A: No. For security reasons, the GitHub API does not allow you to retrieve the plaintext value of a secret once it has been uploaded. You can only verify that a secret exists or update it with a new value.
Q: How do I handle secrets that are too large for the API? A: GitHub secrets have a size limit (typically 64KB). If you have large configuration files, consider storing them in an encrypted object store (like S3) and using a short-lived, scoped access key (a secret) to fetch them during your workflow execution.
Q: What happens if the public key changes? A: GitHub automatically rotates public keys periodically. Your automation script should always fetch the "current" public key from the API before performing an encryption operation, rather than caching the public key for long periods.
Q: Is there a limit to how many secrets I can have per repository? A: Yes, there are limits on the number of secrets per repository (currently 100). If you find yourself hitting this limit, reconsider if you are storing data that should be in a configuration file or a database instead of a secret.
Q: Can I use the API to delete secrets?
A: Yes, the DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name} endpoint allows you to programmatically remove secrets that are no longer needed, which is an important part of the secret lifecycle and security hygiene.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Scheduled Event Triggers
- Scheduled Event Triggers Quiz5q
- Manual Workflow Dispatch
- Manual Workflow Dispatch Quiz5q
- Webhook Event Triggers
- Webhook Event Triggers Quiz5q
- Repository Events Configuration
- Repository Events Configuration Quiz5q
- Workflow Dispatch Inputs
- Workflow Dispatch Inputs Quiz5q
- Reusable Workflows with workflow_call
- Reusable Workflows with workflow_call Quiz5q
- Jobs and Steps Fundamentals
- Jobs and Steps Fundamentals Quiz5q
- Conditional Logic in Workflows
- Conditional Logic in Workflows Quiz5q
- Job Dependencies with needs
- Job Dependencies with needs Quiz5q
- Service Containers Configuration
- Service Containers Configuration Quiz5q
- Matrix Strategy Configuration
- Matrix Strategy Configuration Quiz5q
- YAML Anchors and Aliases
- YAML Anchors and Aliases Quiz5q
- Predefined Contexts Usage
- Predefined Contexts Usage Quiz5q
- Azure Integration Patterns
- Azure Integration Patterns Quiz5q
- AWS Integration Patterns
- AWS Integration Patterns Quiz5q
- Kubernetes Deployments
- Kubernetes Deployments Quiz5q
- Notification Integrations
- Notification Integrations Quiz5q
- Code Quality Integrations
- Code Quality Integrations Quiz5q
- Third-Party Service Integration
- Third-Party Service Integration Quiz5q
- Workflow Orchestration Patterns
- Workflow Orchestration Patterns Quiz5q
- Multi-Environment Workflows
- Multi-Environment Workflows Quiz5q
- Blue-Green and Canary Deployments
- Blue-Green and Canary Deployments Quiz5q
- GitHub-Hosted Runners Configuration
- GitHub-Hosted Runners Configuration Quiz5q
- Self-Hosted Runners Setup
- Self-Hosted Runners Setup Quiz5q
- Runner Groups Management
- Runner Groups Management Quiz5q
- IP Allow Lists and Networking
- IP Allow Lists and Networking Quiz5q
- Runner Troubleshooting
- Runner Troubleshooting Quiz5q
- Environment Protections
- Environment Protections Quiz5q
- Trustworthy Marketplace Actions
- Trustworthy Marketplace Actions Quiz5q
- Script Injection Mitigation
- Script Injection Mitigation Quiz5q
- GITHUB_TOKEN Permissions
- GITHUB_TOKEN Permissions Quiz5q
- OIDC Token for Cloud Federation
- OIDC Token for Cloud Federation Quiz5q
- Action Version Pinning
- Action Version Pinning Quiz5q
- Artifact Attestations and Provenance
- Artifact Attestations and Provenance Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock GH-200 exam-style practice questions.
Practice for GH-200