> 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).

# Local Scanner を使用した 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 で、 **新規アイテム → Multibranch Pipeline**を選択し、名前を付けて、 **OK**.
2. の下で **ブランチソース**、次を選択します **ソースを追加 → SCM を選択**.
3. 次に、 **リポジトリ**.
4. の下で **動作**、次を選択します **追加 → プルリクエストの検出** を追加し、 **ブランチの検出。**
5. の下で **Multibranch Pipeline トリガーのスキャン**で、 **webhook トリガー → Pull request opened or source branch updated** オプションを有効にします。
6. そのままにします **ビルド設定** として **Jenkinsfile による**、 **Script Path** = `Jenkinsfile`.
7. 選択 **保存**として設定します。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 "ベースコミット: ${baseCommit}"
                    echo "ヘッドコミット: ${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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
