> For the complete documentation index, see [llms.txt](https://help.aikido.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.aikido.dev/docs/docs-ja/kdosukyan/local-code-scanning/pr-gating/jenkins-pr-gating-using-local-scanner.md).

# ローカルスキャナーを使ったJenkinsのPRゲーティング

Aikido Local Scanner は、CI パイプライン内でセキュリティゲートを強制するために使用できます。

{% hint style="info" %}
クラウド接続されたワークスペース（GitHub、BitBucket など）でも PR ゲーティングを使用できます。CI の [統合セクションをご覧ください](https://help.aikido.dev/section/ci-integrations/sg3q6UrIf4qE).
{% endhint %}

PR ゲーティングにより、新しいコードがデフォルトブランチにマージされる前にセキュリティ基準を満たしていることを確認できます。これは、プルリクエストで導入された変更のみをスキャンします。スキャンで、設定した重大度しきい値以上に該当する新しい問題が検出された場合、CI パイプラインは失敗します。

これにより、新しい脆弱性の混入を防ぎつつ、既存の検出結果は別途対応できます。

{% hint style="info" %}
また、 [リリースゲート](/docs/docs-ja/kontenaimjisukyan/local-image-scanning/release-gating-for-container-images-using-local-image-scanner.md) リリース時にチェックを強制したいチーム向けのサポートもあります。
{% endhint %}

PR ゲーティングを有効にするには、 `--fail-on <severity>` オプションを追加して、お好みの重大度レベルを選択します。次に、 `--gating-mode pr` オプションを追加して、PR ゲーティングを実行したいことを示します。また、ベース（`--base-commit-id <commit-id>`）とヘッドコミット（`--head-commit-id <commit-id>`）を指定する必要があります。ベースの commit id に対して以前にスキャンが実行されていた場合、スキャン結果はそれと比較されます。そうでない場合は、デフォルトブランチ上の最新のスキャン結果と比較されます。

Jenkins 環境で Local Scanner をセットアップする一般的な情報については、 [この記事](/docs/docs-ja/kdosukyan/local-code-scanning/github-action-setup-for-local-code-scanning.md).

#### 仕組み

3 つの要素があります:

1. **SCM と Jenkins の統合。**
2. **Multibranch Pipeline ジョブ** で *プルリクエストの検出* 動作です。これにより、Jenkins は開いている各プルリクエストをビルドします。PR ビルドでは、Jenkins はソースブランチをチェックアウトし、標準の change-request 環境変数（`CHANGE_ID`, `CHANGE_TARGET`, `CHANGE_BRANCH`).
3. **Aikido Local Scanner**を、 `Jenkinsfile` で `--gating-mode pr`.

```
で実行 ──►  PR が開かれる/更新される ──►  SCM が webhook を送信 ──►  Jenkins Multibranch PR ビルド
                                                      │
                                                      ▼
                                        aikido-local-scanner --gating-mode pr
                                                      │
                                  新しい問題 ≥ --fail-on?  ── はい ──► ビルドが失敗
                                                      │                    │
                                                      いいえ                   ▼
                                                      ▼            ビルド状態 = FAILED
                                                ビルドが成功               │
                                                      │                    ▼
                                                      ▼          SCM がマージをブロック
                                              SCM チェックがパス
```

#### Multibranch Pipeline のセットアップ

プルリクエストのビルドには **Multibranch Pipeline** ジョブが必要です。

1. Jenkins で **New Item → Multibranch Pipeline**を選び、名前を付けて、 **OK**.
2. 次の項目の下で **Branch Sources**、次を選択します **Add source → Select your SCM**.
3. 自分の **リポジトリ**.
4. 次の項目の下で **Behaviors**、次を選択します **Add → Discover pull requests** を追加し、 **Discover branches.**
5. 次の項目の下で **Scan Multibranch Pipeline Triggers**を有効にし、 **webhook trigger → Pull request opened or source branch updated** オプション。
6. そのままにしておく **Build Configuration** として **by Jenkinsfile**で始まり、 **Script Path** = `Jenkinsfile`.
7. 選択します **Save**を指定します。Jenkins はリポジトリをスキャンし、開いている各プルリクエストのビルドを開始します。

#### Jenkinsfile に Aikido の PR ゲーティングステージを追加する

リポジトリのルートに `Jenkinsfile` を追加（または拡張）します。以下のステージは **プルリクエストのビルドでのみ**実行され、Git からベースとヘッドのコミットを取得し、PR ゲーティングモードでスキャナーを実行します。ゲートに失敗したときにスキャナーがゼロ以外の終了コードを返すことで、ビルドが失敗します。

```groovy
pipeline {
    agent any

    environment {
        // ここでは、https://help.aikido.dev/code-scanning/local-code-scanning/jenkins-setup-for-local-code-scanning#id-1-get-your-authentication-token で設定した資格情報を取得します
        AIKIDO_API_KEY = credentials('aikido-local-scanner-api-key')
        AIKIDO_REPO_NAME = 'my-repo'
    }

    stages {
        stage('Aikido PR Gating') {
            // CHANGE_ID はプルリクエストのビルドでのみ設定されます
            when { expression { env.CHANGE_ID != null } }
            steps {
                script {
                    // 対象（宛先）ブランチがローカルで利用可能であることを確認します
                    sh "git fetch origin ${env.CHANGE_TARGET}"

                    // Head = PR ソースブランチの先端（マージされる内容）
                    def headCommit = sh(
                        script: 'git rev-parse HEAD',
                        returnStdout: true
                    ).trim()

                    // Base = 宛先ブランチの先端（マージ先）
                    def baseCommit = sh(
                        script: "git rev-parse origin/${env.CHANGE_TARGET}",
                        returnStdout: true
                    ).trim()

                    echo "PR #${env.CHANGE_ID}: ${env.CHANGE_BRANCH} -> ${env.CHANGE_TARGET}"
                    echo "Base commit: ${baseCommit}"
                    echo "Head commit: ${headCommit}"

                    // Docker 版。スキャナーは、新しい問題が
                    // --fail-on 以上で見つかるとゼロ以外で終了し、その結果ビルドは失敗します。
                    sh """
                        docker run --rm \\
                          -v "\$(pwd):/scan-target" \
                          aikidosecurity/local-scanner \\
                          scan /scan-target \\
                          --apikey "\$AIKIDO_API_KEY" \
                          --repositoryname "\$AIKIDO_REPO_NAME" \
                          --branchname "${env.CHANGE_BRANCH}" \
                          --gating-mode pr \
                          --fail-on critical \
                          --base-commit-id ${baseCommit} \
                          --head-commit-id ${headCommit}
                    """
                }
            }
        }
    }
}
```

**スキャナーのバイナリがエージェントにインストールされている場合は** 、Docker の代わりに `docker run …` のブロックを次のように置き換えます:

```groovy
sh """
    aikido-local-scanner scan ./ \
      --apikey "\$AIKIDO_API_KEY" \
      --repositoryname "\$AIKIDO_REPO_NAME" \
      --branchname "${env.CHANGE_BRANCH}" \
      --gating-mode pr \
      --fail-on critical \
      --base-commit-id ${baseCommit} \
      --head-commit-id ${headCommit}
"""
```

* **`--fail-on critical`** は重大度のしきい値を設定します。より厳しくゲートしたい場合は `high`, `medium`、または `low` に変更してください。

必要に応じて、SCM 側でゲート強制の設定を行ってください。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://help.aikido.dev/docs/docs-ja/kdosukyan/local-code-scanning/pr-gating/jenkins-pr-gating-using-local-scanner.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
