Skip to main content

integration

GitLab Duo Agent Platform - CI/CD Integration

Overview

The GitLab Duo Agent Platform integrates seamlessly with GitLab CI/CD pipelines, enabling agent-driven workflows, automated deployments, and intelligent pipeline operations. This document covers integration patterns, authentication, and best practices for using agents in CI/CD contexts.

Integration Architecture


                    GitLab CI/CD Pipeline                      

                                                               
                  
     Build           Test          Deploy           
     Stage           Stage           Stage            
                  
                                                           
                                                           
          
            Agent Platform Integration                     
                                                            
     Trigger flows on pipeline events                     
     Agent-driven testing and validation                  
     Automated security scanning                          
     Intelligent deployment decisions                      
     Post-deployment monitoring                            
          
                                                             

                            
                            
                 
                   Duo Agent         
                   Platform          
                 

Authentication Methods

OIDC provides temporary, short-lived credentials without storing secrets.

Configuration:

agent_workflow: image: gitlab/agent-runner:latest # Define OIDC tokens id_tokens: AGENT_PLATFORM_TOKEN: aud: https://agent-platform.gitlab.com AWS_TOKEN: aud: https://aws.amazon.com GCP_TOKEN: aud: https://gcp.example.com script: # Authenticate with Agent Platform using OIDC - duo-agent auth --token $AGENT_PLATFORM_TOKEN # Agent can now use cloud credentials - duo-agent deploy \ --flow production-deployment \ --aws-token $AWS_TOKEN

Benefits:

  • No long-lived credentials stored in GitLab
  • Tokens expire automatically (1 hour TTL)
  • Granular permissions per job
  • Full audit trail

Trust Configuration (One-time setup):

# Configure AWS to trust GitLab OIDC aws iam create-open-id-connect-provider \ --url https://gitlab.com \ --client-id-list "https://gitlab.com" \ --thumbprint-list "..." # Create IAM role for GitLab CI/CD aws iam create-role \ --role-name GitLabAgentPlatformRole \ --assume-role-policy-document file://trust-policy.json

Trust Policy:

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Federated": "arn:aws:iam::AWS_ACCOUNT:oidc-provider/gitlab.com" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "gitlab.com:sub": "project_path:mygroup/myproject:ref_type:branch:ref:main" } } } ] }

2. CI Job Token (GitLab-internal)

Use CI_JOB_TOKEN for GitLab API access:

agent_job: script: # Token automatically available - echo $CI_JOB_TOKEN # Use for GitLab API calls - curl --header "JOB-TOKEN: $CI_JOB_TOKEN" \ "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID" # Agent Platform automatically uses job token - duo-agent trigger \ --flow security-scan \ --project $CI_PROJECT_ID \ --merge-request $CI_MERGE_REQUEST_IID

Token Scope:

  • Inherits job's permissions
  • Limited to pipeline duration
  • Automatically rotates
  • Scoped to specific project/group

3. Service Account Token

For long-running agents or scheduled flows:

agent_scheduled_job: script: # Use stored service account token - export GITLAB_TOKEN=$SERVICE_ACCOUNT_TOKEN # Run agent workflow - duo-agent run \ --flow nightly-dependency-check \ --token $GITLAB_TOKEN

Setup:

# Create service account glab api -X POST "/groups/:group_id/service_accounts" \ --field username="ci-agent-platform" \ --field name="CI Agent Platform Service Account" # Generate token glab api -X POST "/users/:user_id/personal_access_tokens" \ --field name="CI Token" \ --field scopes[]="api" \ --field scopes[]="read_repository" # Store in CI/CD variables glab variable set SERVICE_ACCOUNT_TOKEN \ --value="$TOKEN" \ --masked \ --protected

Integration Patterns

1. Agent-Driven Testing

Agents analyze test failures and suggest fixes:

test: stage: test script: - npm test || TEST_FAILED=true # If tests fail, trigger diagnostic agent - | if [ "$TEST_FAILED" = "true" ]; then duo-agent run \ --flow test-failure-diagnostic \ --pipeline-id $CI_PIPELINE_ID \ --output diagnostic-report.json # Create issue with diagnostics glab issue create \ --title "Test failure in pipeline $CI_PIPELINE_ID" \ --description "$(cat diagnostic-report.json)" exit 1 fi

Diagnostic Flow:

name: test-failure-diagnostic description: Analyze test failures and suggest fixes flow: agents: - code_review_agent steps: - name: analyze_failure agent: code_review_agent action: analyze_test_failure inputs: pipeline_id: context.pipeline_id test_results: context.test_results - name: identify_root_cause agent: code_review_agent action: root_cause_analysis inputs: failure_data: steps.analyze_failure.outputs - name: suggest_fixes agent: code_review_agent action: generate_fix_suggestions inputs: root_cause: steps.identify_root_cause.outputs - name: create_report agent: code_review_agent action: format_report

2. Automated Security Scanning

Trigger security agents on every pipeline:

security_scan: stage: security script: # Run standard security scans - glas sast . - glas dependency_scanning . - glas secret_detection . after_script: # Trigger security analyst agent for triage - duo-agent run \ --flow security-triage \ --mr-iid $CI_MERGE_REQUEST_IID \ --scan-results security-report.json

Security Triage Flow:

name: security-triage description: Automated vulnerability triage and prioritization trigger: event: ci_pipeline_success conditions: - stage: security flow: steps: - name: collect_findings agent: security_analyst_agent action: collect_scan_results - name: assess_vulnerabilities agent: security_analyst_agent action: risk_assessment - name: prioritize agent: security_analyst_agent action: prioritize_remediation - name: create_issues agent: security_analyst_agent action: create_vulnerability_issues condition: - high_risk_count > 0 - name: block_if_critical agent: security_analyst_agent action: block_merge_request condition: - critical_risk_count > 0

3. Intelligent Deployment

Agents make deployment decisions based on quality gates:

deploy_production: stage: deploy environment: name: production action: start rules: # Only deploy if agent approves - if: $AGENT_APPROVAL == "approved" before_script: # Request deployment validation from agent - duo-agent run \ --flow deployment-validation \ --mr-iid $CI_MERGE_REQUEST_IID \ --environment production \ --output validation-result.json # Check agent decision - export AGENT_APPROVAL=$(jq -r '.decision' validation-result.json) - | if [ "$AGENT_APPROVAL" != "approved" ]; then echo " Deployment blocked by agent" echo "Reason: $(jq -r '.reason' validation-result.json)" exit 1 fi script: # Proceed with deployment - kubectl apply -f k8s/production/

Deployment Validation Flow:

name: deployment-validation description: Validate deployment readiness flow: steps: - name: check_tests agent: code_review_agent action: verify_tests_passed - name: check_security agent: security_analyst_agent action: verify_no_critical_vulnerabilities - name: check_performance agent: code_review_agent action: verify_performance_benchmarks - name: check_documentation agent: code_review_agent action: verify_docs_updated - name: make_decision agent: code_review_agent action: deployment_decision inputs: tests: steps.check_tests.outputs.passed security: steps.check_security.outputs.passed performance: steps.check_performance.outputs.passed docs: steps.check_documentation.outputs.updated

4. Post-Deployment Monitoring

Agents monitor deployments and respond to issues:

monitor_deployment: stage: monitor environment: name: production action: monitor script: # Trigger monitoring flow - duo-agent run \ --flow post-deployment-monitoring \ --deployment-id $CI_DEPLOY_ID \ --duration 30m \ --async # Job continues in background allow_failure: true

Monitoring Flow:

name: post-deployment-monitoring description: Monitor deployment and respond to issues flow: steps: - name: monitor_metrics agent: code_review_agent action: watch_metrics duration: 30m inputs: metrics: - error_rate - latency_p95 - cpu_usage - memory_usage - name: detect_anomalies agent: code_review_agent action: anomaly_detection inputs: metrics: steps.monitor_metrics.outputs.timeseries - name: trigger_rollback agent: code_review_agent action: initiate_rollback condition: - steps.detect_anomalies.outputs.anomaly_detected == true - steps.detect_anomalies.outputs.severity >= "high" - name: notify_team agent: code_review_agent action: send_alert params: channel: "#production-alerts"

5. Automated Dependency Updates

Agent creates MRs for dependency updates:

# Scheduled pipeline dependency_update: stage: maintenance rules: - if: $CI_PIPELINE_SOURCE == "schedule" script: # Trigger dependency update flow - duo-agent run \ --flow automated-dependency-update \ --branch $CI_DEFAULT_BRANCH # Flow runs independently and creates MR

Complete Pipeline Example:

# .gitlab-ci.yml with Agent Platform integration stages: - build - test - security - deploy - monitor variables: AGENT_PLATFORM_ENABLED: "true" # Global OIDC token for all jobs id_tokens: GITLAB_OIDC_TOKEN: aud: https://gitlab.com build: stage: build script: - npm ci - npm run build artifacts: paths: - dist/ test: stage: test script: - npm test coverage: '/Coverage: \d+\.\d+%/' after_script: # Analyze test results with agent - | if [ $CI_JOB_STATUS = "failed" ]; then duo-agent run \ --flow test-failure-analysis \ --pipeline-id $CI_PIPELINE_ID \ --async fi security: stage: security script: # Run security scans - glas sast - glas dependency_scanning - glas secret_detection after_script: # Trigger security triage agent - duo-agent run \ --flow security-triage \ --mr-iid $CI_MERGE_REQUEST_IID deploy_staging: stage: deploy environment: name: staging rules: - if: $CI_COMMIT_BRANCH == "main" script: # Agent validates deployment - duo-agent run \ --flow deployment-validation \ --environment staging \ --output validation.json # Deploy if approved - | if [ "$(jq -r '.approved' validation.json)" = "true" ]; then kubectl apply -f k8s/staging/ else echo "Deployment blocked: $(jq -r '.reason' validation.json)" exit 1 fi deploy_production: stage: deploy environment: name: production rules: - if: $CI_COMMIT_TAG when: manual # Require human approval for production before_script: # Agent provides deployment recommendation - duo-agent run \ --flow production-readiness-check \ --tag $CI_COMMIT_TAG \ --output readiness.json - cat readiness.json # Show recommendation to human approver script: - kubectl apply -f k8s/production/ after_script: # Start monitoring - duo-agent run \ --flow post-deployment-monitoring \ --deployment-id $CI_DEPLOY_ID \ --async monitor: stage: monitor rules: - if: $CI_COMMIT_BRANCH == "main" when: always script: # Continuous monitoring with agent - duo-agent run \ --flow continuous-monitoring \ --environment production \ --duration 24h \ --async

Advanced Patterns

1. Multi-Agent Pipeline Orchestration

Multiple agents work together across pipeline stages:

.agent_job_template: image: gitlab/agent-runner:latest id_tokens: AGENT_TOKEN: aud: https://agent-platform.gitlab.com code_review: extends: .agent_job_template stage: review script: - duo-agent run --flow code-review --mr-iid $CI_MERGE_REQUEST_IID security_review: extends: .agent_job_template stage: review script: - duo-agent run --flow security-review --mr-iid $CI_MERGE_REQUEST_IID performance_review: extends: .agent_job_template stage: review script: - duo-agent run --flow performance-review --mr-iid $CI_MERGE_REQUEST_IID aggregate_reviews: extends: .agent_job_template stage: decide needs: - code_review - security_review - performance_review script: # Agent aggregates all review results and makes final decision - duo-agent run \ --flow aggregate-reviews \ --mr-iid $CI_MERGE_REQUEST_IID \ --reviews code_review,security_review,performance_review

2. Dynamic Pipeline Generation

Agent generates pipeline configuration:

generate_pipeline: stage: .pre script: # Agent analyzes changes and generates optimized pipeline - duo-agent run \ --flow pipeline-generator \ --mr-iid $CI_MERGE_REQUEST_IID \ --output pipeline-config.yml # Use generated pipeline - cat pipeline-config.yml artifacts: reports: dotenv: pipeline-config.yml

3. Parallel Agent Execution

Run multiple agents in parallel:

parallel_agents: stage: analysis parallel: matrix: - AGENT: [security, performance, accessibility, compliance] script: - duo-agent run --flow ${AGENT}-analysis --mr-iid $CI_MERGE_REQUEST_IID

4. Agent-Driven Feature Flags

Agent decides feature flag states:

feature_flag_management: stage: deploy script: # Agent analyzes deployment and adjusts feature flags - duo-agent run \ --flow feature-flag-optimizer \ --environment production \ --output flags.json # Apply flag changes - | for flag in $(jq -r '.flags[] | @base64' flags.json); do _jq() { echo ${flag} | base64 --decode | jq -r ${1} } FLAG_NAME=$(_jq '.name') FLAG_STATE=$(_jq '.state') unleash-cli toggle $FLAG_NAME --state $FLAG_STATE done

Error Handling in Pipelines

Retry on Agent Failure

agent_job: script: - duo-agent run --flow code-review retry: max: 2 when: - agent_timeout - agent_error

Fallback to Manual Process

agent_review: script: - duo-agent run --flow code-review || AGENT_FAILED=true - | if [ "$AGENT_FAILED" = "true" ]; then echo " Agent review failed, requiring human review" glab mr update $CI_MERGE_REQUEST_IID \ --label "needs-human-review" \ --reviewer @senior-developer fi

Graceful Degradation

security_scan: script: # Try agent-powered scan - duo-agent run --flow advanced-security-scan || USE_BASIC=true # Fall back to basic scan - | if [ "$USE_BASIC" = "true" ]; then echo "Using basic security scan" glas sast fi

Monitoring and Debugging

Pipeline Agent Logs

# View agent execution in pipeline glab ci trace --job security_scan # View agent session details glab duo agent session show $SESSION_ID # Download agent artifacts glab ci artifact download --job agent_analysis

Performance Optimization

# Cache agent context for faster execution agent_job: cache: key: agent-context-$CI_COMMIT_REF_SLUG paths: - .agent-cache/ policy: pull-push script: - duo-agent run \ --flow code-review \ --cache-dir .agent-cache/

Best Practices

1. Use OIDC for Authentication

Recommended:

id_tokens: AGENT_TOKEN: aud: https://agent-platform.gitlab.com

Avoid:

script: - export GITLAB_TOKEN=$LONG_LIVED_TOKEN # Security risk

2. Handle Agent Failures Gracefully

script: - duo-agent run --flow review || true # Don't fail pipeline - # Continue with other checks

3. Use Async for Long-Running Agents

# Don't block pipeline - duo-agent run --flow long-analysis --async # Pipeline continues immediately

4. Limit Agent Scope

# Specific, focused flows - duo-agent run --flow security-scan # # vs # Overly broad - duo-agent run --flow do-everything #

5. Monitor Agent Costs

after_script: - duo-agent session show $SESSION_ID --format json > agent-cost.json - echo "Agent cost: $(jq -r '.total_cost_usd' agent-cost.json)"

Next Steps


Last Updated: January 2026 GitLab Version: 18.7 (Beta), 18.8 GA (Upcoming)