將 Docker Scout 與 GitLab CI/CD 整合

以下示例在 GitLab CI 中執行,在一個包含 Docker 映象定義和內容的儲存庫中。透過提交觸發,管道構建映象。如果提交到預設分支,它使用 Docker Scout 獲取 CVE 報告。如果提交到不同的分支,它使用 Docker Scout 將新版本與當前釋出的版本進行比較。

步驟

首先,設定工作流的其餘部分。有很多內容與 Docker Scout 無關,但需要建立要比較的映象。

將以下內容新增到儲存庫根目錄下的 .gitlab-ci.yml 檔案中。

docker-build:
  image: docker:latest
  stage: build
  services:
    - docker:dind
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY

    # Install curl and the Docker Scout CLI
    - |
      apk add --update curl
      curl -sSfL https://raw.githubusercontent.com/docker/scout-cli/main/install.sh | sh -s -- 
      apk del curl 
      rm -rf /var/cache/apk/*
    # Login to Docker Hub required for Docker Scout CLI
    - echo "$DOCKER_HUB_PAT" | docker login -u "$DOCKER_HUB_USER" --password-stdin

這設定了工作流,以 Docker-in-Docker 模式構建 Docker 映象,在容器內部執行 Docker。

然後它下載 curl 和 Docker Scout CLI 外掛,使用儲存庫設定中定義的環境變數登入到 Docker 登錄檔。

將以下內容新增到 YAML 檔案中

script:
  - |
    if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
      tag=""
      echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'"
    else
      tag=":$CI_COMMIT_REF_SLUG"
      echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag"
    fi
  - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" .
  - |
    if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
      # Get a CVE report for the built image and fail the pipeline when critical or high CVEs are detected
      docker scout cves "$CI_REGISTRY_IMAGE${tag}" --exit-code --only-severity critical,high    
    else
      # Compare image from branch with latest image from the default branch and fail if new critical or high CVEs are detected
      docker scout compare "$CI_REGISTRY_IMAGE${tag}" --to "$CI_REGISTRY_IMAGE:latest" --exit-code --only-severity critical,high --ignore-unchanged
    fi

  - docker push "$CI_REGISTRY_IMAGE${tag}"

這建立了前面提到的流程。如果提交到預設分支,Docker Scout 將生成 CVE 報告。如果提交到不同的分支,Docker Scout 將新版本與當前釋出的版本進行比較。它只顯示嚴重或高危漏洞,並忽略自上次分析以來未更改的漏洞。

將以下內容新增到 YAML 檔案中

rules:
  - if: $CI_COMMIT_BRANCH
    exists:
      - Dockerfile

最後幾行確保管道僅在提交包含 Dockerfile 且提交到 CI 分支時執行。

影片演練

以下是使用 GitLab 設定工作流過程的影片演練。