Running Gemini CLI in CI/CD pipelines requires headless mode, which disables interactive prompts and uses non-interactive authentication. This guide covers everything you need to configure Gemini CLI for automated workflows in GitHub Actions, GitLab CI/CD, Docker containers, and other server environments.
Understanding Headless Mode
Headless mode allows Gemini CLI to operate without user interaction. This is essential for:
- CI/CD pipelines: Automated code review, documentation generation, or test analysis
- Scheduled jobs: Nightly codebase analysis or report generation
- Docker containers: Serverless functions or containerized workflows
- Server environments: Backend services that need AI assistance
In headless mode, Gemini CLI skips the browser-based OAuth flow and instead uses API keys or service account credentials that you provide through environment variables.
Authentication Methods
Method 1: Google API Key (Recommended)
The simplest approach for most CI/CD scenarios is using a Gemini API key.
-
Generate an API key at Google AI Studio
-
Store the key securely in your CI/CD platform's secrets manager
-
Set the environment variable before running Gemini commands:
export GOOGLE_API_KEY="your-api-key-here"
gemini --non-interactive "analyze this code"
Method 2: Service Account (Enterprise)
For Google Cloud organizations, service accounts provide better audit trails and access control.
-
Create a service account in Google Cloud Console with appropriate permissions
-
Download the JSON key file and store it securely
-
Configure the credentials:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
export GOOGLE_CLOUD_PROJECT="your-project-id"
export GOOGLE_GENAI_USE_VERTEXAI=true
gemini --non-interactive "analyze this code"
Required Environment Variables
For headless operation, configure these environment variables:
| Variable | Purpose | Required |
|---|---|---|
GOOGLE_API_KEY | API key for Gemini authentication | Yes (unless using service account) |
GOOGLE_APPLICATION_CREDENTIALS | Path to service account JSON | For enterprise/Vertex AI |
GOOGLE_CLOUD_PROJECT | Google Cloud project ID | For Vertex AI |
GOOGLE_GENAI_USE_VERTEXAI | Enable Vertex AI backend | For enterprise |
NO_COLOR | Disable colored output | Recommended for CI logs |
Command-Line Flags for Non-Interactive Operation
Gemini CLI provides several flags optimized for headless environments:
# Prevent any interactive prompts
gemini --non-interactive "your prompt"
# Auto-approve tool executions (use only in trusted environments)
gemini --yolo "run tests and fix failures"
# Output in JSON format for parsing
gemini --output-format json "analyze security vulnerabilities"
# Combine flags for full automation
gemini --non-interactive --yolo --output-format json "review this PR"
Security warning: The --yolo flag auto-approves all tool executions including shell commands. Only use this in isolated, trusted environments where the Gemini agent cannot cause harm.
GitHub Actions Integration
Here is a complete GitHub Actions workflow that uses Gemini CLI to review pull requests:
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
gemini-review:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Gemini CLI
run: npm install -g @google/gemini-cli
- name: Run code review
env:
GOOGLE_API_KEY: ${{ secrets.GOOGLE_API_KEY }}
NO_COLOR: true
run: |
git diff origin/main...HEAD > changes.diff
gemini --non-interactive -p "Review this diff for bugs, security issues, and improvements:" < changes.diff > review.md
- name: Post review comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.md', 'utf8');
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `## AI Code Review\n\n${review}`
});
GitLab CI/CD Integration
For GitLab pipelines, configure Gemini CLI in your .gitlab-ci.yml:
stages:
- review
variables:
NODE_VERSION: "20"
ai-code-review:
stage: review
image: node:${NODE_VERSION}
before_script:
- npm install -g @google/gemini-cli
script:
- git diff $CI_MERGE_REQUEST_DIFF_BASE_SHA...$CI_COMMIT_SHA > changes.diff
- gemini --non-interactive -p "Review this diff:" < changes.diff > review.md
- cat review.md
artifacts:
paths:
- review.md
expire_in: 1 week
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
variables:
GOOGLE_API_KEY: $GOOGLE_API_KEY
NO_COLOR: "true"
Store your GOOGLE_API_KEY as a CI/CD variable in GitLab Settings > CI/CD > Variables, and mark it as protected and masked.
Docker Container Usage
Create a Dockerfile for containerized Gemini CLI workflows:
FROM node:20-slim
# Install Gemini CLI globally
RUN npm install -g @google/gemini-cli
# Set working directory
WORKDIR /workspace
# Configure for headless operation
ENV NO_COLOR=true
# Default command
ENTRYPOINT ["gemini", "--non-interactive"]
Build and run the container:
# Build the image
docker build -t gemini-cli .
# Run with API key
docker run -e GOOGLE_API_KEY="your-key" \
-v $(pwd):/workspace \
gemini-cli "analyze the codebase structure"
Security Best Practices
When running Gemini CLI in automated environments, follow these security guidelines:
-
Never commit API keys to version control. Always use secrets managers.
-
Use least-privilege access. Create dedicated API keys for CI/CD with minimal permissions.
-
Rotate keys regularly. Set up key rotation schedules, especially for production pipelines.
-
Audit tool executions. Review logs to ensure Gemini is not executing unexpected commands.
-
Isolate execution environments. Run Gemini in containers or VMs with limited network access.
-
Avoid --yolo in untrusted contexts. The auto-approve flag should only be used when the input is fully controlled.
-
Validate outputs. Do not blindly apply AI-generated code changes to production.
Troubleshooting Common CI/CD Issues
Authentication Failures
If Gemini fails to authenticate:
# Verify the API key is set
echo $GOOGLE_API_KEY | head -c 10
# Test with a simple prompt
gemini --non-interactive "say hello"
Rate Limiting
For high-volume pipelines, you may hit rate limits:
- Implement retry logic with exponential backoff
- Consider Vertex AI for higher quotas
- Spread analysis across multiple pipeline stages
Timeout Issues
Long-running analysis may timeout:
# Increase timeout for complex operations
timeout 300 gemini --non-interactive "analyze entire codebase"
Output Parsing
When parsing JSON output programmatically:
# Ensure clean JSON output
gemini --non-interactive --output-format json "list all functions" | jq '.result'
Next Steps
- Configure MCP integrations for extended capabilities
- Learn about batch code analysis for large-scale operations
- Explore Vertex AI enterprise setup for production workloads