Back to Blog

OpenCode Service Account API Keys: Secure CI/CD Integration

Tutorials and Guides9360
OpenCode Service Account API Keys: Secure CI/CD Integration

A developer can configure OpenCode on a personal workstation in a few minutes. The situation becomes more complicated when the same AI coding workflow needs to run inside a shared development environment, automated pipeline, or company-managed server.

Consider a team that uses OpenCode to review pull requests, generate test cases, inspect application dependencies, and explain failed builds. During development, each engineer may authenticate through an individual account. Once these workflows move into CI/CD, however, personal authentication introduces operational problems.

What happens when an employee leaves the company? Should a build pipeline continue using an engineer's personal API key? How can administrators distinguish automated model consumption from individual development usage? What happens when a credential expires during a scheduled deployment?

These are not simply authentication questions. They are part of API governance.

OpenCode Console provides both personal API keys and service account keys. Understanding the difference is important when moving from individual experimentation to repeatable engineering workflows.

This guide explains how to structure OpenCode authentication for automated workloads, manage permissions, isolate credentials, and connect different model providers through a consistent API configuration.

1. Why Personal API Keys Become a Problem in CI/CD

Personal API keys are convenient for individual developers.

A developer creates a key, stores it in an environment variable, and uses it to authenticate requests. This works well when one person owns the entire workflow.

A shared environment has different requirements.

For example, imagine a development team with five engineers. Each engineer works on a separate branch, but the company also operates a central pipeline that runs automated code reviews.

If the pipeline uses one developer's personal key, several problems can emerge:

This structure creates unnecessary operational dependencies.

A production pipeline should have an identity that belongs to the workload itself.

That is the purpose of a service account.

2. Personal API Keys vs. Service Account API Keys

OpenCode Console supports two types of API keys.

AttributePersonal API KeyService Account API Key
OwnerIndividual workspace memberNon-human service account
CreationAccount settingsWorkspace administration
Usage attributionIndividual memberService account
Budget relationshipMember budgetService account budget
Typical applicationPersonal scriptsCI/CD and shared automation
AdministrationIndividual userWorkspace owner or administrator

A personal key acts with the permissions of the member who created it.

A service account has its own identity, API keys, usage records, and budget. Workspace owners and administrators manage these accounts.

This separation makes service accounts more suitable for shared workloads.

There is another important detail: an API key does not automatically grant unrestricted access. Its permissions remain limited by the identity and permission level associated with that key.

For example, a key configured with read-only model permissions may list available models but cannot submit inference requests.

That distinction matters when diagnosing an apparently valid credential that still cannot call a model.

3. Create a Dedicated Identity for Each Automated Workload

Avoid creating one service account for every application in the company.

A more manageable structure separates workloads by purpose.

For example:

Service accountResponsibility
ci-code-reviewAutomated pull request analysis
test-generationUnit test generation
documentation-agentDocumentation maintenance
release-assistantRelease notes and change summaries

This organization provides several advantages.

First, administrators can identify which application consumes model resources.

Second, a credential can be disabled without unnecessarily interrupting unrelated services.

Third, different applications can receive different permission levels and budget limits.

For a small project, a single service account may be sufficient. As the number of automated workflows increases, separate identities become easier to manage.

4. Create and Configure an OpenCode Service Account

The general configuration process is straightforward.

  1. Open the OpenCode Console workspace.
  2. Navigate to Settings.
  3. Find Service accounts.
  4. Create a new service account.
  5. Give it a descriptive name.
  6. Open the newly created account.
  7. Generate an API key.
  8. Configure the required expiration and permissions.
  9. Copy the key and store it securely.

OpenCode displays the complete key only when it is created. Afterward, the Console shows its prefix rather than the full secret.

This means the original value should be transferred directly into a secure secret store.

Do not put the key into a source-code repository or a shared configuration file.

5. Store Credentials in Environment Variables

A simple local example looks like this:

bash
export OPENCODE_API_KEY="your_service_account_key"

A production pipeline should retrieve the secret from its CI/CD secret manager.

For example, a generic deployment configuration might use:

yaml
name: automated-code-review

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest

    env:
      OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }}

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Verify credential availability
        run: |
          test -n "$OPENCODE_API_KEY"
          echo "Credential is configured"

This example only verifies that the secret is available to the job. It does not establish that the key has model-request permissions or that an inference endpoint is correctly configured.

Those checks should be performed separately.

A useful rule is to distinguish three independent conditions:

A successful check of the first condition does not prove the other two.

6. Verify API Access Before Running a Pipeline

Before connecting an AI coding workflow, test the Console API directly.

For example, OpenCode documents a model-listing endpoint:

bash
curl --fail-with-body \
  "https://opencode.ai/inference/v1/models" \
  -H "Authorization: Bearer $OPENCODE_API_KEY"

A successful response helps establish that the service can authenticate the request and access the model-listing endpoint.

However, model discovery and inference are different operations.

A read-only credential may be able to list models but not call them. A restricted key needs the appropriate model-request permission.

Check the permission configuration before interpreting a failed inference request as a network problem.

Also record the following information:

Never include the full API key in diagnostic logs.

7. Using an API Gateway for Multiple Model Backends

Automated coding workflows rarely remain tied to one model forever.

A team may use one model for routine code explanations, another for complex debugging, and a third for documentation or test generation.

Managing independent endpoints and credentials across multiple pipelines introduces configuration overhead.

An API gateway provides another architectural option.

Instead of placing separate provider configurations throughout the application, developers can centralize the model endpoint and authentication layer.

For example, a compatible OpenAI SDK integration can be structured as follows:

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["GATEWAY_API_KEY"],
    base_url=os.environ["GATEWAY_BASE_URL"]
)

response = client.chat.completions.create(
    model=os.environ["MODEL_ID"],
    messages=[
        {
            "role": "system",
            "content": "Review the code for correctness and security."
        },
        {
            "role": "user",
            "content": "Analyze this pull request."
        }
    ]
)

print(response.choices[0].message.content)

The important point is that the API key, base URL, and model ID are configuration values rather than hardcoded application dependencies.

A gateway such as 4SAPI can provide a centralized API entry point for compatible model integrations. Developers should still verify the supported protocol and model identifier for their selected workflow.

A gateway does not replace OpenCode's own service-account permissions. These are separate authentication and access-control layers.

8. Credential Rotation Without Breaking Automation

Credential rotation should be treated as a planned deployment operation.

A practical rotation sequence is:

  1. Generate a replacement service account key.
  2. Add it to the CI/CD secret manager.
  3. Test the replacement in a controlled pipeline.
  4. Switch production jobs to the new secret.
  5. Verify successful model requests.
  6. Revoke the previous key.

Do not revoke the existing credential before testing its replacement.

This sequence avoids unnecessary interruptions.

For systems with several deployment environments, use a staged rollout. Development and staging should validate the replacement before production adopts it.

9. Common Problems and How to Diagnose Them

SymptomPossible causeRecommended check
401 UnauthorizedInvalid or expired keyCheck the issuing workspace and key
403 ForbiddenInsufficient permissionsReview key access settings
Model listing succeeds but inference failsRead-only permissionCheck model-request access
CI job cannot find the keySecret not injectedInspect pipeline environment configuration
Requests use unexpected budgetPersonal identity usedCheck the credential owner
One project works but another failsDifferent workspace or permissionsCompare endpoint and workspace configuration

One mistake worth avoiding is treating every authentication failure as an expired key.

The service may be rejecting the request because of permissions, workspace association, or an incorrect endpoint.

The distinction is important because generating another key will not fix a configuration problem.

10. Production Checklist

Before deploying an automated OpenCode workflow, verify:

Conclusion

Moving OpenCode from a personal development environment into CI/CD changes the authentication requirements.

Personal API keys remain useful for individual experimentation, but shared automation needs clearer ownership, usage attribution, and credential lifecycle management.

Service accounts provide a dedicated identity for these workloads. When combined with restricted permissions, centralized secret storage, and controlled credential rotation, they make automated model access easier to operate.

For teams building multi-model applications, the next architectural step is to separate the application identity from the model-provider connection. This allows authentication, usage governance, and model routing to evolve without rewriting every application.

References and further reading

  1. OpenCode Console API Documentation
  2. OpenCode Console Models
  3. OpenCode Harness Configuration
  4. OpenCode API Documentation
  5. OpenAI API Authentication Documentation
  6. OWASP Secrets Management Cheat Sheet

Related articles

Tags:OpenCode service account API keyOpenCode CI/CD integrationOpenCode API key permissionsOpenCode workspace APIOpenCode automation authentication

Recommended reading

Explore more frontier insights and industry know-how.