CodeBuddy Code GitLab CI/CD Integration â
Overview â
CodeBuddy Code supports deep integration with GitLab CI/CD, enabling you to leverage AI assistance for code review, automated implementation, and intelligent optimization tasks within your CI/CD pipelines. This integration is built on top of the CodeBuddy Code CLI, allowing you to programmatically use AI capabilities in GitLab CI jobs.
Why Use CodeBuddy Code in GitLab CI/CD? â
- Instant MR Creation: Describe your requirements, and CodeBuddy automatically generates complete merge requests with change descriptions
- Automated Implementation: Transform Issues into working code through simple commands or comments
- Project-Aware: CodeBuddy follows your CODEBUDDY.md guidelines and existing code conventions
- Simple Configuration: Just add a single job to .gitlab-ci.yml and necessary CI/CD variables
- Secure by Default: Runs in your GitLab Runner, adhering to branch protection and approval workflows
How It Works â
CodeBuddy Code leverages GitLab CI/CD to run AI tasks in isolated jobs and submit results via MRs:
Event-Driven Orchestration: GitLab listens for your chosen triggers (e.g., Issues, MRs, or @codebuddy mentions in comments). Jobs collect context and codebase information, build prompts, and run CodeBuddy Code.
Sandboxed Execution: Each interaction runs in a container with strict network and filesystem rules. CodeBuddy Code enforces workspace-scoped permission constraints on writes. Every change flows through MRs, reviewers can see diffs, and approval workflows still apply.
What Can CodeBuddy Do? â
CodeBuddy Code supports powerful CI/CD workflows that transform how you collaborate with code:
- Create and update MRs from Issue descriptions or comments
- Analyze performance regressions and suggest optimizations
- Implement features directly in branches, then create MRs
- Fix bugs and regressions found in tests or comments
- Respond to follow-up comments to iteratively refine requested changes
Configuration Guide â
Quick Setup â
The fastest way to get started is to add a minimal job to .gitlab-ci.yml and set your API key as a protected variable.
Step 1: Add Protected CI/CD Variables
Go to your GitLab project's Settings â CI/CD â Variables and add the following environment variables:
Authentication Configuration:
Add the following environment variables in your GitLab project's Settings â CI/CD â Variables:
- CODEBUDDY_API_KEY (Required)
- API key for model interface calls
- When configuring, check: â Protect variable, â Mask variable
Optional Configuration:
CODEBUDDY_INTERNET_ENVIRONMENT
- Network environment configuration (China version users need to set to
internal, iOA users set toiOA)
- Network environment configuration (China version users need to set to
CODEBUDDY_BASE_URL
- Custom base URL for model service (must be compatible with OpenAI API protocol)
GITLAB_ACCESS_TOKEN
- GitLab project access token (requires api scope)
- Used for CodeBuddy to create/update MRs and comments
- If not configured, defaults to using
CI_JOB_TOKEN - When configuring, check: â Protect variable, â Mask variable
đ Complete Configuration Guide: Based on your account type, refer to the corresponding configuration methods and API KEY retrieval locations:
- iOA Account Users (internal company): See Using API KEY with iOA Account
- China Version Users: See Using API KEY with China Version
- International Version Users: See Using API KEY with International Version
Each section includes complete environment variable configuration methods and API KEY retrieval locations.
Step 2: Add CodeBuddy Job to .gitlab-ci.yml
yaml
stages:
- ai
codebuddy:
stage: ai
image: node:24-alpine3.21
# Adjust trigger rules as needed:
# - Manual run
# - Merge request events
# - Triggered via Web/API when comments contain '@codebuddy'
rules:
- if: '$CI_PIPELINE_SOURCE == "web"'
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
variables:
GIT_STRATEGY: fetch
# CODEBUDDY_API_KEY is automatically injected from CI/CD variables
# Optional variables: CODEBUDDY_BASE_URL, GITLAB_ACCESS_TOKEN
before_script:
- apk update
- apk add --no-cache git curl bash
- npm install -g @tencent-ai/codebuddy-code
# Verify CODEBUDDY_API_KEY is set
- |
if [ -z "$CODEBUDDY_API_KEY" ]; then
echo "Error: CODEBUDDY_API_KEY is not set. Please configure it in GitLab CI/CD variables"
exit 1
fi
script:
# Optional: Start GitLab MCP server (if provided by your environment)
- /bin/gitlab-mcp-server || true
# Pass context through web/API trigger when using AI_FLOW_* variables
- echo "$AI_FLOW_INPUT for $AI_FLOW_CONTEXT on $AI_FLOW_EVENT"
- >
codebuddy
-p "${AI_FLOW_INPUT:-'Review this MR and implement requested changes'}"
--permission-mode acceptEdits
--allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"
--debugAfter adding the job and API key variable, test by manually running the job through CI/CD â Pipelines, or trigger it from an MR to have CodeBuddy propose updates in the branch and create an MR when needed.
Manual Configuration (Recommended for Production) â
If you need finer control:
Add Project Credentials for GitLab API Operations:
- By default, uses CI_JOB_TOKEN, or create a project access token with api scope
- If using PAT, store it as GITLAB_ACCESS_TOKEN (masked)
Add CodeBuddy Job to .gitlab-ci.yml (see example above)
(Optional) Enable Mention-Driven Triggers:
- Add a project Webhook for "notes" to your event listener (if using)
- Have the listener call the pipeline trigger API when comments contain @codebuddy, passing variables like AI_FLOW_INPUT and AI_FLOW_CONTEXT
Usage Examples â
Transform Issue into MR â
In an Issue comment:
@codebuddy Implement this feature based on the Issue descriptionCodeBuddy analyzes the Issue and codebase, writes changes in a branch, and creates an MR for review.
Get Implementation Help â
In an MR discussion:
@codebuddy Suggest a specific approach to cache the results of this API callCodeBuddy proposes changes, adds appropriate caching code, and updates the MR.
Quick Bug Fix â
In an Issue or MR comment:
@codebuddy Fix the TypeError in the user dashboard componentCodeBuddy locates the bug, implements a fix, and updates the branch or creates a new MR.
Best Practices â
CODEBUDDY.md Configuration â
Create a CODEBUDDY.md file in your repository root to define coding standards, review criteria, and project-specific rules. CodeBuddy reads this file during execution and follows your conventions when proposing changes.
Example CODEBUDDY.md:
markdown
# Project Coding Standards
## Code Style
- Use ESLint and Prettier for code formatting
- Follow Airbnb JavaScript Style Guide
- Use TypeScript strict mode
## Commit Conventions
- Follow Conventional Commits specification
- Use Chinese for commit messages
- Each commit should contain only one logical change
## Testing Requirements
- All new features must include unit tests
- Test coverage must be at least 80%
- Use Jest as the testing framework
## MR Review Checklist
- Code passes all CI checks
- At least one team member has approved
- Update relevant documentationSecurity Considerations â
Never commit sensitive information to the repository! Always use GitLab CI/CD variables:
- Add sensitive configuration as masked variables (mark as protected if needed)
- Limit job permissions and network egress
- Review CodeBuddy's MRs as you would any other contributor's
Performance Optimization â
- Keep CODEBUDDY.md concise and clear
- Provide clear Issue/MR descriptions to reduce iterations
- Configure reasonable job timeouts to avoid runaway executions
- Cache npm and package installations in Runners (if possible)
CI Cost Control â
When using CodeBuddy Code with GitLab CI/CD, be aware of associated costs:
GitLab Runner Time:
- CodeBuddy runs on your GitLab Runner and consumes compute minutes
- Check your GitLab plan's Runner billing details
Cost Optimization Recommendations:
- Use specific @codebuddy commands to reduce unnecessary rounds
- Set appropriate --max-turns and job timeout values
- Limit concurrency to control parallel runs
Security and Governance â
- Each job runs in an isolated container with restricted network access
- CodeBuddy's changes flow through MRs, reviewers can see every diff
- Branch protection and approval rules apply to AI-generated code
- CodeBuddy Code uses workspace-scoped permissions to constrain writes
Troubleshooting â
CodeBuddy Doesn't Respond to @codebuddy Commands â
- Verify your pipeline is being triggered (manually, MR events, or via note event listener/Webhook)
- Ensure CI/CD variables exist and are configured correctly
- Check that comments contain @codebuddy (not /codebuddy) and your mention trigger is configured
Job Cannot Write Comments or Create MRs â
- Ensure CI_JOB_TOKEN has sufficient permissions for the project, or use a project access token with api scope
- Check that the mcp__gitlab tool is enabled in --allowedTools
- Confirm the job is running in an MR context or has sufficient context via AI_FLOW_* variables
Authentication Errors â
Authentication Variables Not Set:
- Confirm
CODEBUDDY_API_KEYis added in your GitLab project's Settings â CI/CD â Variables - Check the variable name spelling is correct (case-sensitive)
- If "Protect variable" is set, ensure the job runs on a protected branch
API Authentication Failed (401 Unauthorized):
- Verify the API key is valid and not expired
- Confirm no extra spaces or newlines were included when copying the API key
- Check the API key has sufficient permission scopes
- See Settings Configuration Documentation for detailed configuration methods
API Connection Failed:
- Check
CODEBUDDY_BASE_URLis configured correctly (if using a custom endpoint) - Verify the GitLab Runner can access the CodeBuddy API server
- Confirm the URL format is correct, including protocol (e.g.,
https://api.example.com)
Key Visible in Logs:
- Ensure â Mask variable is checked when configuring CI/CD variables
- Avoid directly echoing or printing the API key in scripts
GitLab Access Token Related Issues:
- Check that the configured CI/CD variables are set correctly
- Verify the related access permission configuration
- Ensure CI_JOB_TOKEN or GITLAB_ACCESS_TOKEN has sufficient permissions (api scope)
Job Timeout â
- Increase the job's timeout configuration
- Simplify prompts to reduce processing time
- Consider breaking large tasks into multiple smaller tasks
Advanced Configuration â
Common Parameters and Variables â
Environment Variables:
CodeBuddy Code uses the following environment variables in CI/CD environments:
Authentication Configuration:
CODEBUDDY_API_KEY: Used for model interface calls, suitable for CI/CD non-interactive environments
Optional Configuration:
CODEBUDDY_BASE_URL: Custom base URL for model serviceGITLAB_ACCESS_TOKEN: GitLab API access token (for MR operations)CI_JOB_TOKEN: Job token automatically provided by GitLab CI
Flow Control Variables:
AI_FLOW_INPUT: User input passed through Web/API triggersAI_FLOW_CONTEXT: Context information (e.g., Issue ID, MR ID, etc.)AI_FLOW_EVENT: Trigger event type (e.g., note, issue, merge_request)
đ For detailed descriptions and configuration examples of each environment variable, please refer to Settings Configuration Documentation
Command Line Parameters:
CodeBuddy Code supports these common inputs:
- prompt (-p): Provide instructions inline
- max-turns: Limit the number of back-and-forth iterations
- permission-mode: Permission mode (e.g., acceptEdits)
- allowedTools: List of allowed tools
- debug: Enable debug output
Note: Exact flags and parameters may vary depending on @tencent-ai/codebuddy-code version. Run codebuddy --help in the job to see supported options.
Customizing CodeBuddy Behavior â
You can guide CodeBuddy through two main approaches:
CODEBUDDY.md: Define coding standards, security requirements, and project conventions. CodeBuddy reads this file during execution and follows your rules.
Custom Prompts: Pass task-specific instructions via prompt/prompt_file in the job. Use different prompts for different jobs (e.g., review, implementation, refactoring).
Multi-Environment Configuration â
You can configure different CodeBuddy jobs for different environments (development, testing, production):
yaml
# Development environment - Auto-trigger
codebuddy-dev:
stage: ai
rules:
- if: '$CI_COMMIT_BRANCH == "develop"'
script:
- codebuddy -p "Quick review and auto-merge"
# Production environment - Manual trigger
codebuddy-prod:
stage: ai
rules:
- if: '$CI_COMMIT_BRANCH == "main"'
when: manual
script:
- codebuddy -p "Detailed review, generate complete change report"Reference Resources â
- CodeBuddy Code Official Documentation
- CLI Reference
- Settings Configuration
- Common Workflows
- Troubleshooting
Empower your CI/CD pipeline with AI and boost development efficiency!