Introduction: Why Scanning and Cleanup Matter

Welcome to the fifth and final lesson in our course on working with container registries. You've built a solid foundation in Google Artifact Registry fundamentals, created secure repositories, mastered the push-pull workflow, and successfully deployed container images. Now it's time to learn how to manage those images responsibly over time through vulnerability scanning and cleanup policies.

Vulnerability scanning automatically analyzes your images against databases of known vulnerabilities through the Container Analysis API, providing detailed security reports as new threats are discovered in container components. Cleanup policies provide automated rules that remove old, unused, or untagged images, preventing repositories from accumulating hundreds of versions that lead to unnecessary storage costs and operational complexity.

You'll achieve two key outcomes: viewing vulnerability scan findings using the gcloud artifacts docker images describe command for security analysis and creating automated cleanup rules using the gcloud artifacts repositories set-cleanup-policies command with configuration files.

Prerequisites and Context

Before diving into vulnerability scanning and cleanup policies, you need to ensure you have the proper foundation from previous lessons and understand the permissions required for these advanced Artifact Registry operations.

You should have an existing Artifact Registry repository with at least one container image — specifically, the my-web-app repository with a Docker image tagged as latest from lessons two and three. Additionally, you should have enabled the Container Analysis API at the project level in an earlier lesson, which automatically enables vulnerability scanning for all images pushed to any repository in your project. You can verify your repository exists by running the familiar command from previous lessons.

gcloud artifacts repositories describe my-web-app \
  --location=us-central1

This command should return details about your repository, including the repository format, creation time, and configuration settings. You can also check which images exist in your repository using the list command.

gcloud artifacts docker images list \
  us-central1-docker.pkg.dev/PROJECT_ID/my-web-app

For the advanced operations covered in this lesson, your Google Cloud credentials need appropriate IAM permissions beyond the basic push and pull permissions you used previously. The essential roles are:

  • Vulnerability Scanning:

    • roles/artifactregistry.reader: Allows you to view repository contents and image metadata.
    • roles/containeranalysis.occurrences.viewer: Lets you retrieve and view vulnerability scan results from the Container Analysis API.
  • Cleanup Policy Management:

    • roles/artifactregistry.repoAdmin: Required for setting or updating cleanup policies on repositories. The writer role is insufficient for policy management.
    • roles/artifactregistry.reader: Allows viewing existing cleanup policies and repository configurations (read-only access).

Permission Summary for Common Operations:

  • Create repositories: Requires roles/artifactregistry.repoAdmin
  • Push images: Requires roles/artifactregistry.writer or higher
  • Pull images: Requires roles/artifactregistry.reader or higher
  • View vulnerability scans: Requires roles/containeranalysis.occurrences.viewer
  • Set cleanup policies: Requires roles/artifactregistry.repoAdmin

These permissions are required in addition to the standard push and pull permissions for Artifact Registry.

Most Google Cloud environments that provide Artifact Registry access include these permissions in standard roles, but if you encounter permission denied errors during this lesson, verify these specific roles in your IAM policies. The permissions can be granted at the project level or for specific repositories, allowing you to control access granularly based on your security requirements.

As with all Artifact Registry operations, consistency in location and repository naming remains critical. Your gcloud commands must use the same location where your repository exists, and repository names must exactly match those used during creation. Double-check these details if you encounter "repository not found" errors during vulnerability scanning or cleanup policy operations.

Viewing Vulnerability Scan Findings

Google Artifact Registry provides automatic vulnerability scanning through the Container Analysis API, which you enabled at the project level in an earlier lesson. Vulnerability scanning is a project-wide setting — once enabled, the Container Analysis API automatically scans all images pushed to any repository in your project, analyzing each layer for known vulnerabilities and continuously updating results as new vulnerability databases become available. You do not configure scanning per-repository; it applies to all repositories in your project.

When you pushed your Docker image in lesson three, the Container Analysis API automatically began scanning it in the background. You can retrieve vulnerability count summaries for any image using the gcloud artifacts docker images describe command with the --show-package-vulnerability flag, which provides high-level vulnerability statistics.

gcloud artifacts docker images describe \
  us-central1-docker.pkg.dev/PROJECT_ID/my-web-app/my-web-app:latest \
  --show-package-vulnerability

The scan findings output provides vulnerability counts by severity level.

Listing items under project PROJECT_ID.

IMAGE: us-central1-docker.pkg.dev/PROJECT_ID/my-web-app/my-web-app:latest
CREATE_TIME: 2024-01-15T10:30:45
UPDATE_TIME: 2024-01-15T10:35:22
DIGEST: sha256:8f2a1b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a
VULNERABILITIES:
  CRITICAL: 2
  HIGH: 5
  MEDIUM: 12
  LOW: 8
  TOTAL: 27

This summary view is ideal for quickly assessing the overall security posture of an image. Critical and High severity vulnerabilities represent the most serious security risks that should be addressed immediately. Medium findings represent moderate risks for regular maintenance cycles, while Low findings often indicate minor improvements that can be addressed as time permits.

For detailed information about each vulnerability — including CVE identifiers, affected packages, and specific remediation steps — use the separate gcloud artifacts docker images list-vulnerabilities command.

gcloud artifacts docker images list-vulnerabilities \
  us-central1-docker.pkg.dev/PROJECT_ID/my-web-app/my-web-app:latest

This command provides comprehensive details for each vulnerability found in the image. Each detailed finding includes the CVE identifier, affected package name and version, vulnerability description, severity rating, and which container layer contains the vulnerable component. When working with images that have many findings, add the optional --limit=N flag to control pagination (e.g., --limit=10 shows only the first 10 vulnerabilities).

When triaging scan findings, focus first on Critical and High severity vulnerabilities affecting packages exposed to network traffic or user input. Research each CVE to understand specific attack vectors and determine whether your deployment context exposes you to the vulnerability.

The most effective approach to addressing scan findings involves updating base images, upgrading vulnerable packages, and rebuilding container images with the latest security patches integrated into your regular development workflows.

Cleanup Policy Model

Cleanup policies in Google Artifact Registry are defined using structured JSON configuration that specifies rules for automatically deleting images. Each policy consists of one or more rules with an action and a condition that defines which images to target.

Here's a basic cleanup policy that deletes untagged images older than 7 days.

{
  "rules": [
    {
      "action": "DELETE",
      "condition": {
        "tagState": "UNTAGGED",
        "olderThan": "604800s"
      }
    }
  ]
}

Policy components:

  • action: What to do with matching images (DELETE or KEEP).
  • condition: Defines criteria for rule application.
    • tagState: Can be TAGGED, UNTAGGED, or ANY.
    • olderThan: Age threshold in seconds (604800s = 7 days, 86400s = 1 day, 2592000s = 30 days).

You can create policies with multiple rules that work together. This example keeps the 10 most recent tagged images while deleting old untagged images.

{
  "rules": [
    {
      "action": "KEEP",
      "mostRecentVersions": {
        "keepCount": 10
      }
    },
    {
      "action": "DELETE",
      "condition": {
        "tagState": "UNTAGGED",
        "olderThan": "604800s"
      }
    }
  ]
}

Save policy content to a file (e.g., cleanup-policy.json) for version control and consistent application across repositories. Warning: Deleted images cannot be recovered — test policies carefully before production use.

Applying and Verifying Cleanup Policies

Apply your cleanup policy to a repository using the gcloud artifacts repositories set-cleanup-policies command.

gcloud artifacts repositories set-cleanup-policies my-web-app \
  --location=us-central1 \
  --policy=cleanup-policy.json

The --policy flag reads policy content from your local file. On success, gcloud returns a confirmation message.

Updated cleanup policies for repository [my-web-app].

Verify the policy configuration by retrieving the repository details.

gcloud artifacts repositories describe my-web-app \
  --location=us-central1

This command returns the complete repository configuration, including active cleanup policies.

Encryption: Google-managed key
Repository Size: 245.3MB
Create Time: 2024-01-10T08:15:30
Update Time: 2024-01-15T11:20:45
Cleanup Policies:
  rules:
  - action: DELETE
    condition:
      tagState: UNTAGGED
      olderThan: 604800s

Artifact Registry evaluates cleanup policies on a regular schedule (typically daily). Policy effects are not immediate — new policies take effect during the next scheduled evaluation cycle, providing a safety buffer against accidental deletion due to configuration errors.

Monitor policy effects by checking your repository's image list periodically.

gcloud artifacts docker images list \
  us-central1-docker.pkg.dev/PROJECT_ID/my-web-app

Over time, you should see that images matching your policy criteria are automatically removed while protected images remain available.

Pitfalls & Best Practices

Several common pitfalls can cause unexpected behavior when working with Artifact Registry. Following these best practices helps you implement scanning and cleanup policies safely and effectively in production environments.

  • Avoid Accidental Deletion with Immutable Tags.
    Pushing a new latest tag untags the previous image, making it a target for cleanup. Use immutable tags (e.g., version numbers, Git SHAs) to protect important releases from accidental deletion.

  • Test Policies in Non-Production Environments.
    Never apply a new policy directly to production, as an incorrect rule can cause irreversible data loss. Always test policies in a non-production environment first to verify their behavior.

  • Understand Rule Evaluation Order.
    Rules are evaluated in order. KEEP actions are evaluated before DELETE actions, so place KEEP rules first in your policy file to protect important images from matching a later deletion rule.

  • Verify IAM Permissions.
    Ensure you have the correct IAM roles: roles/artifactregistry.repoAdmin to manage cleanup policies and roles/containeranalysis.occurrences.viewer to view vulnerability scans.

  • Act on Vulnerability Scan Findings.
    Scanning without action provides little security benefit. Regularly review findings, prioritize remediation based on severity, and integrate patching and rebuilding images into your development workflow.

  • Monitor and Adjust Policies.
    Policies are not "set and forget." Regularly monitor storage costs and image counts to confirm policies are working as expected. Adjust rules and retention periods as needed.

By internalizing these practices, you shift from simply using Artifact Registry as a storage bucket to managing it as a critical component of your software supply chain. A thoughtful approach to tagging, testing, and remediation ensures your container registry remains secure, cost-effective, and operationally sound, preventing common issues before they can impact your production environment.

Lesson Wrap-Up

In this lesson, you mastered advanced Artifact Registry management for production environments. You learned to identify security risks by viewing automatic vulnerability scans with gcloud artifacts docker images describe and the Container Analysis API, and to control costs by creating automated cleanup rules with gcloud artifacts repositories set-cleanup-policies. These skills transform Artifact Registry from a simple image store into a secure, automated component of your software delivery pipeline.

In the upcoming practice, you'll apply these skills by analyzing scan results and creating custom cleanup policies. The commands and principles are directly transferable to your own projects, provided your local gcloud CLI is configured with the necessary IAM roles for repository administration and vulnerability analysis.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal