將 Docker Scout 與 GitLab CI/CD 進行整合
目錄
以下範例在 GitLab CI 中執行,針對包含 Docker 映像檔定義與內容的儲存庫。當提交(commit)觸發時,Pipeline 會建置該映像檔。如果提交的是預設分支,它會使用 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 Registry。
將以下內容新增至 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 會將新版本與目前已發布的版本進行比較。它僅會顯示嚴重(critical)或高風險(high-severity)等級的漏洞,並忽略自上次分析以來未曾變更的漏洞。
將以下內容新增至 YAML 檔案中
rules:
- if: $CI_COMMIT_BRANCH
exists:
- Dockerfile最後這幾行確保只有在提交內容包含 Dockerfile 且提交的是 CI 分支時,Pipeline 才會執行。
影片教學
以下是使用 GitLab 設定此工作流程過程的影片教學。