> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codeant.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Jenkins

> Set up CodeAnt Quality Gates in your Jenkins CI Pipeline.

## Jenkins Pipeline

Add the following to your `Jenkinsfile`. It will trigger on every push to your repository and run quality gate checks to detect secrets and other security issues:

```groovy theme={null}
pipeline {
    agent any
    
    environment {
        ACCESS_TOKEN = credentials('ACCESS_TOKEN')
        API_BASE = 'https://api.codeant.ai'
    }
    
    stages {
        stage('Quality Gate Scan') {
            steps {
                script {
                    echo "�  Setting up environment variables"
                    
                    // Extract repository information
                    def repoUrl = env.GIT_URL
                    def repoName = ""
                    
                    if (repoUrl.contains('github.com')) {
                        repoName = repoUrl.replaceAll(/.*github\.com[\/:]([^\/]+\/[^\/]+)\.git.*/, '$1')
                    } else if (repoUrl.contains('gitlab.com')) {
                        repoName = repoUrl.replaceAll(/.*gitlab\.com[\/:]([^\/]+\/[^\/]+)\.git.*/, '$1')
                    } else {
                        // For other Git providers, extract org/repo from URL
                        repoName = repoUrl.replaceAll(/.*[\/:]([^\/]+\/[^\/]+)\.git.*/, '$1')
                    }
                    
                    echo "=
 Debug Info:"
                    echo "  Repository URL: ${env.GIT_URL}"
                    echo "  Repository: ${repoName}"
                    echo "  Commit: ${env.GIT_COMMIT}"
                    echo "  Branch: ${env.GIT_BRANCH}"
                    echo "  Build Number: ${env.BUILD_NUMBER}"
                    
                    if (!env.ACCESS_TOKEN) {
                        error "L ERROR: ACCESS_TOKEN is not set!"
                    }
                    
                    echo "=� Downloading CodeAnt quality gates script..."
                    sh """
                        curl -sS -X GET "${API_BASE}/analysis/ci/quality-gates/script/get" \\
                            --output quality_gates.sh.b64
                    """
                    
                    echo "�  Decoding and making script executable"
                    sh """
                        base64 -d quality_gates.sh.b64 > quality_gates.sh
                        chmod +x quality_gates.sh
                    """
                    
                    echo "=� Starting quality gate scan..."
                    sh """
                        ./quality_gates.sh \\
                            -a "${ACCESS_TOKEN}" \\
                            -r "${repoName}" \\
                            -c "${env.GIT_COMMIT}" \\
                            -s github \\
                            -o start
                    """
                    echo "Quality gate scan initiated successfully"
                    
                    echo "=
 Polling for quality gate results..."
                    sh """
                        ./quality_gates.sh \\
                            -a "${ACCESS_TOKEN}" \\
                            -r "${repoName}" \\
                            -c "${env.GIT_COMMIT}" \\
                            -s github \\
                            -o results \\
                            -t 300 \\
                            -p 15
                    """
                    
                    echo " Quality Gate PASSED "
                }
            }
            post {
                failure {
                    echo "L Quality Gate FAILED "
                }
                always {
                    // Clean up script files
                    sh """
                        rm -f quality_gates.sh quality_gates.sh.b64
                    """
                }
            }
        }
    }
    
    triggers {
        // Trigger on SCM changes
        scm('H/5 * * * *')
    }
}
```

> **Important:**
>
> * In **Manage Jenkins � Credentials**, add a **Secret text** credential with ID `ACCESS_TOKEN` containing your personal access token.
> * Jenkins automatically provides `${env.GIT_URL}` (repository URL), `${env.GIT_COMMIT}` (commit SHA), and other build variables.

## How it works

1. **Setup environment**\
   Extract repository information from Jenkins built-in environment variables.

2. **Download script**\
   We fetch the quality gates script (`quality_gates.sh`) from the CodeAnt API endpoint.

3. **Start scan**\
   The script initiates a quality gate scan for your commit using the `-o start` operation.

4. **Poll for results**\
   The script polls for scan results using the `-o results` operation with:
   * **Timeout**: 300 seconds (5 minutes)
   * **Poll interval**: 15 seconds

5. **Pipeline feedback**
   * **Success**: Quality gate passes if no secrets are detected
   * **Failure**: Quality gate fails if secrets are found, blocking the build

## Script Parameters

The `quality_gates.sh` script accepts the following parameters:

| Parameter             | Description                                   | Required | Example              |
| --------------------- | --------------------------------------------- | -------- | -------------------- |
| `-a, --access-token`  | Personal Access Token or repo token           | Yes      | `${ACCESS_TOKEN}`    |
| `-r, --repo`          | Repository in format `owner/repository`       | Yes      | `${repoName}`        |
| `-c, --commit-id`     | Commit SHA to scan                            | Yes      | `${env.GIT_COMMIT}`  |
| `-s, --service`       | VCS provider                                  | Yes      | `github`             |
| `-o, --operation`     | Operation to perform (`start` or `results`)   | Yes      | `start` or `results` |
| `-t, --timeout`       | Timeout in seconds for polling (default: 300) | No       | `300`                |
| `-p, --poll-interval` | Poll interval in seconds (default: 15)        | No       | `15`                 |
| `-u, --base-url`      | Base URL for VCS service (optional)           | No       | `https://github.com` |

## Quality Gate Checks

Currently, the quality gate performs the following checks:

### Secret Detection

* Scans for hardcoded secrets, API keys, passwords, and tokens
* Analyzes only the changed lines since your merge base commit
* Uses high-confidence detection to minimize false positives
* Blocks the build if any secrets are found

## Best Practices

1. **Run on all branches**: Quality gates should run on every push to catch issues early
2. **Block builds**: Configure Jenkins to fail the build when quality gates fail
3. **Review failures**: When quality gates fail, review the detected issues immediately
4. **Keep tokens secure**: Never commit access tokens directly - always use Jenkins Credentials
5. **Use shared libraries**: Create shared pipeline libraries for reusable quality gate steps

## Jenkins Built-in Variables

The following Jenkins built-in variables are automatically available and used:

| Variable              | Description         | Example                            |
| --------------------- | ------------------- | ---------------------------------- |
| `${env.GIT_URL}`      | Repository URL      | `https://github.com/user/repo.git` |
| `${env.GIT_COMMIT}`   | Current commit SHA  | `abc123def456`                     |
| `${env.GIT_BRANCH}`   | Current branch name | `origin/main`                      |
| `${env.BUILD_NUMBER}` | Build number        | `42`                               |
| `${env.JOB_NAME}`     | Job name            | `my-project/main`                  |
| `${env.WORKSPACE}`    | Workspace directory | `/var/jenkins_home/workspace/job`  |

## Troubleshooting

### Quality gate times out

If the scan takes longer than expected:

* Increase the timeout using `-t 600` (10 minutes)
* Check if the CodeAnt service is operational
* Consider optimizing your repository size

### Authentication failures

If you see "Access token invalid":

* Verify your `ACCESS_TOKEN` credential is correctly configured in Jenkins Credentials
* Ensure the token has appropriate repository permissions
* Check that the credential ID matches exactly

### No results returned

If the scan completes but returns no results:

* Check that quality gates are enabled for your repository in CodeAnt
* Verify the commit SHA is correct
* Ensure your Jenkins instance has proper integration with CodeAnt

### Repository format issues

If you see "Invalid repository format":

* Verify the repository format is extracted correctly from `GIT_URL`
* Check that the repository name follows `owner/repository` format
* Debug the repository extraction by adding echo statements

### Permission issues

If you see permission denied errors:

* Ensure Jenkins has permission to execute shell scripts
* Check that the workspace is writable
* Verify curl is installed on Jenkins agents

With quality gates in place, every push will automatically be scanned for security issues, helping you maintain code security and compliance standards in your Jenkins pipelines.
