Integrating Trivy for Docker Image Scanning in GitLab CI/CD
In this article, we will set up Trivy to scan Docker images in a GitLab CI/CD pipeline. Trivy is a powerful vulnerability scanner for containers and other artifacts.
GitLab CI/CD Configuration
To integrate Trivy into your GitLab CI/CD pipeline, you need to define a job in your .gitlab-ci.yml file. Below is an example configuration:
Trivy_container_scanning:
stage: test
image: docker:stable-git
variables:
GIT_STRATEGY: none # Prevents GitLab from fetching the repository
IMAGE: "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" # Define the image to scan
allow_failure: true # Allow the job to fail without failing the pipeline
before_script:
- export TRIVY_VERSION=${TRIVY_VERSION:-v0.20.0} # Set Trivy version
- apk add --no-cache curl docker-cli # Install necessary packages
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY # Authenticate to the registry
- curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin ${TRIVY_VERSION} # Install Trivy
- curl -sSL -o /tmp/trivy-gitlab.tpl https://github.com/aquasecurity/trivy/raw/${TRIVY_VERSION}/contrib/gitlab.tpl # Download Trivy template
script:
- trivy --exit-code 0 --cache-dir .trivycache/ --no-progress --format template --template "@/tmp/trivy-gitlab.tpl" -o gl-container-scanning-report.json $IMAGE # Run Trivy scan
cache:
paths:
- .trivycache/ # Cache Trivy results
artifacts:
reports:
container_scanning: gl-container-scanning-report.json # Store the scan report
only:
refs:
- branches # Run this job only for branches
Dockerfile Example
Here’s a simple Dockerfile that you can use for testing:
FROM composer:1.7.2
RUN git clone https://github.com/aquasecurity/trivy-ci-test.git && cd trivy-ci-test && rm Cargo.lock && rm Pipfile.lock
CMD apk add --no-cache mysql-client
ENTRYPOINT ["mysql"]
Troubleshooting Common Errors
If you encounter issues such as image pull failures, ensure that:
- The image name and tag are correct.
- Your GitLab runner has access to the Docker daemon.
- The Kubernetes executor is properly configured if you are using one.
For further assistance, refer to the GitLab CI/CD documentation and the Trivy documentation.