Build Secure VM Images in Google Cloud with cnspec and HashiCorp Packer
Learn how to build secure machine images in Google Cloud with cnspec and HashiCorp Packer.
You can run security scans during HashiCorp Packer builds using Packer plugin cnspec by Mondoo. This tutorial includes instructions for using the plugin both with and without an account on Mondoo Platform.
This tutorial provisions resources in your Google Cloud project. Mondoo is not responsible for charges that you incur.
Prerequisites
Before you begin, be sure you have:
- A Google Cloud account
- The Google Cloud SDK installed and authenticated using Application Default Credentials
- The latest HashiCorp Packer version installed
The user or service account must have these roles:
roles/iam.serviceAccountUser(Service Account User)roles/compute.instanceAdmin.v1(Compute Instance Admin v1)
You can find more authentication methods for the googlecompute builder in the Packer
documentation.
Configure the Google Cloud project
You must create machine images within a Google Cloud project. Run gcloud projects list to get a list of the projects you have access to, or run gcloud projects create to create a new project to build your images in.
Enable the required APIs in the project:
gcloud services enable sourcerepo.googleapis.com
gcloud services enable compute.googleapis.com
gcloud services enable servicemanagement.googleapis.com
gcloud services enable storage-api.googleapis.comPacker plugin cnspec by Mondoo
Packer plugin cnspec by Mondoo scans Linux and Windows HashiCorp Packer builds for vulnerabilities and security misconfigurations. The plugin is designed to work with any of the supported Packer builders, including containers.
Plugin modes
Packer plugin cnspec is designed to work in one of two modes:
- Unregistered - In unregistered mode, the plugin works without being registered to Mondoo Platform, and is designed to provide baseline security scanning with minimal configuration. The plugin runs either the Linux Security by Mondoo policy on Linux builds, or the Windows Security by Mondoo policy on Windows builds. Each of these policies provides security hardening checks based on industry standards for Linux and Windows. Scan results are shown in STDOUT during the Packer run.
- Registered - In registered mode, the plugin is registered to your account in Mondoo Platform using a service account. Registered mode allows you to configure and customize any of the policies in Mondoo Platform including CIS benchmarks and more. Scan results are shown in STDOUT and sent back to Mondoo Platform for your records.
To scan for vulnerabilities, you must register cnspec with Mondoo Platform. Sign up for a free account today.
Plugin configuration
Packer plugin cnspec provides this configuration:
score_threshold- This configuration sets anintscore threshold for security scans. If the scan produces a score that falls below the threshold, the build will fail.on_failure = "continue"- This configuration ensures that the Packer build will not fail even if the scan produces a score that falls below thescore_threshold.sudo- Some of the security configuration checks require elevated permissions to scan a given resource such as thesshd_config. Setting thesudooption toactive = trueconfigures the plugin to run insudomode.asset_name- Override the asset name on Mondoo Platform. This configuration is only used in registered mode.annotations- Custom annotations can be applied to Packer build assets to provide additional metadata for asset tracking. This configuration is only used in registered mode.
Register with Mondoo Platform
To configure the plugin to work in registered mode, you must first create a Base64-encoded service account. If you do not wish to use custom policies and store results on Mondoo Platform you can skip this step.
To create a Base64-encoded service account:
- Navigate to the space in which you want to create a service account.
- In the left navigation, select Settings. Then select the Service Accounts tab.
- Select the purple plus sign to add a new service account.
- Provide a Name and optionally a Description for the service account.
- Under permissions select Agent and select Generate Service Account.
- Copy the Base64-encoded credentials to the clipboard.
- Open a terminal and run:
export MONDOO_CONFIG_BASE64=<paste Base64-encoded token>Run Packer
A Packer template is a configuration file that defines the image you want to build and how to build it. Packer templates use the HashiCorp Configuration Language (HCL).
Ubuntu 20.04 template
Create a new directory named mondoo_packer, and change to that directory.
mkdir mondoo_packer
cd mondoo_packerCreate a file gcp-ubuntu2004.pkr.hcl, add this HCL block to it, and save the file.
packer {
required_plugins {
googlecompute = {
version = ">= 1.0.0"
source = "github.com/hashicorp/googlecompute"
}
cnspec = {
version = ">= 12.0.0"
source = "github.com/mondoohq/cnspec"
}
}
}
variable "zone" {
default = "us-east5-a"
description = "Google Cloud zone to build the image in"
}
variable "project_id" {
type = string
description = "Google Cloud Project ID to build the image in"
}
variable "image_prefix" {
type = string
description = "Prefix to be applied to image name"
default = "cnspec-tested-ubuntu-2004"
}
locals { timestamp = regex_replace(timestamp(), "[- TZ:]", "") }
source "googlecompute" "ubuntu2004" {
image_name = "${var.image_prefix}-${local.timestamp}"
machine_type = "e2-small"
source_image = "ubuntu-pro-2004-focal-v20220627a"
ssh_username = "packer"
temporary_key_pair_type = "rsa"
temporary_key_pair_bits = 2048
zone = var.zone
project_id = var.project_id
}
build {
sources = ["source.googlecompute.ubuntu2004"]
provisioner "shell" {
inline = [
"echo Hello From ${source.type} ${source.name}"
]
}
provisioner "cnspec" {
score_threshold = 80
on_failure = "continue"
sudo {
active = true
}
}
}This is a complete Packer template that you will use to build an Ubuntu 20.04 image in the us-east5-a zone.
The template defines three variables you can customize: zone (default: us-east5-a), project_id (required), and image_prefix (default: cnspec-tested-ubuntu-2004). Override them using any of the standard Packer variable methods.
Initialize the Packer configuration
Initialize your Packer configuration.
packer init gcp-ubuntu2004.pkr.hclBuild the image
Build the image with the packer build gcp-ubuntu2004.pkr.hcl command. Packer prints output similar to what is shown below.
packer build gcp-ubuntu2004.pkr.hcl
<image-name>: output will be in this color.
==> <image-name>: Checking image does not exist...
==> <image-name>: Creating temporary RSA SSH key for instance...
==> <image-name>: Using image: ubuntu-pro-2004-focal-v20220627a
==> <image-name>: Creating instance...
<image-name>: Loading zone: us-east5-a
<image-name>: Loading machine type: e2-small
<image-name>: Requesting instance creation...
<image-name>: Waiting for creation operation to complete...
<image-name>: Instance has been created!
==> <image-name>: Waiting for the instance to become running...
<image-name>: IP: 34.162.0.117
==> <image-name>: Using SSH communicator to connect: 34.162.0.117
==> <image-name>: Waiting for SSH to become available...
...
<image-name>:
<image-name>:
<image-name>: Summary
<image-name>: ========================
<image-name>:
<image-name>: Target: cnspec-tested-ubuntu-2004-20220630154951
<image-name>: Score: A 86/100 (100% completed)
<image-name>: ✓ Passed: ███████ 49% (80)
<image-name>: ✕ Failed: ██████ 37% (61)
<image-name>: ! Errors: ██ 14% (23)
<image-name>: » Skipped: 0% (0)
<image-name>:
<image-name>: Policies:
<image-name>: A 100 Platform End-of-Life Policy by Mondoo
<image-name>: A 100 Platform Vulnerability Policy by Mondoo
<image-name>:
<image-name>: Report URL: https://console.mondoo.com/space/inventory/<space>
==> <image-name>: Deleting instance...
<image-name>: Instance has been deleted!
==> <image-name>: Creating image...
==> <image-name>: Deleting disk...
<image-name>: Disk has been deleted!
Build '<image-name>' finished after 5 minutes 46 seconds.View the scan report in Mondoo Platform (registered mode only)
Packer plugin cnspec sends the scan results to your account in Mondoo Platform. To view the scan report in the Mondoo Console, navigate to INVENTORY, then ASSETS and select your asset. You may need to refresh your browser.

View the findings details
Select the Findings tab.

Select any of the findings from your build to show additional documentation, audit, and remediation steps:

View the image in Google Cloud Console

After running the above example, you can navigate to the Storage Images of Google Cloud Console.
Next steps
In this tutorial, you built a Google Cloud machine image and scanned it for vulnerabilities and misconfigurations with cnspec.
The GitHub repository for Packer plugin cnspec contains additional templates for other platforms and cloud environments.
Cross-Project Snapshot Scanning
Configure cnspec to scan GCP Compute Engine snapshots that reside in a different project than your scanner VM.
Workload Identity Federation
Use Workload Identity Federation to let a service account in one GCP project scan resources in other GCP projects without exporting keys.