Build and test Go applications

This page explains how to use Cloud Build to build and test your Go applications, upload your artifacts to Artifact Registry, generate provenance information, and save your test logs in Cloud Storage.

Before you begin

The instructions on this page assume that you are familiar with Go. In addition:

Configure the service account

The examples in this document use a user-specified service account. To create the service account used by Cloud Build, run the following command in Google Cloud CLI:

gcloud iam service-accounts create cloud-build-go \
--description="Build and test Go applications" \
--display-name="Cloud Build Go" \
--project="PROJECT_ID"

The default compute service account (used by Cloud Run) needs permission to act as the new service account. First, determine the name of the compute service account in your project:

gcloud iam service-accounts list --filter="email:-compute@developer.gserviceaccount.com"

Next, grant the Service Account User (roles/iam.serviceAccountUser) role:

gcloud iam service-accounts add-iam-policy-binding \
COMPUTE_SERVICE_ACCOUNT_EMAIL  \
--member="serviceAccount:cloud-build-go@PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/iam.serviceAccountUser"

Replace COMPUTE_SERVICE_ACCOUNT_EMAIL with the default compute service account email address printed by the previous command.

Configure IAM permissions

Ensure that you have the permissions that you need:

To get the permissions that you need to perform builds in Cloud Build, ask your administrator to grant you the Cloud Build Service Account (roles/cloudbuild.builds.builder) IAM role on your build service account. For more information about granting roles, see Manage access to projects, folders, and organizations.

You might also be able to get the required permissions through custom roles or other predefined roles.

To get the permissions that you need to store built images in Artifact Registry, ask your administrator to grant you the Artifact Registry Writer (roles/artifactregistry.writer) IAM role on your build service account.

To get the permissions that you need to store test logs in Logging, ask your administrator to grant you the Storage Object Creator (roles/storage.objectCreator) IAM role on your build service account.

To get the permissions that you need to deploy the application to Cloud Run, ask your administrator to grant you the Cloud Run Developer (roles/run.developer) IAM role on your build service account.

Configure Go builds

The public golang image from Docker Hub supports building using Go modules. Using this image as a build step in your Cloud Build config file lets you invoke go commands within the image. Arguments passed to this build step are passed to the golang tool directly, allowing you to run any go command in this image.

This section walks through an example build config file for a Go app. It has build steps to build the app, add unit tests, and after the tests pass, to deploy the app.

This section shows an example build config file for a Go app from the cloud-build-samples Git repository. It has build steps to build the app, add unit tests, and after the tests pass, to containerize and deploy the app.

To build the example Go application:

  1. Configure unit tests: If you've defined unit tests in your application, you can configure Cloud Build to run the tests by adding the following fields in a build step:

    • name: Set the value of this field to golang to use the golang image from Docker Hub for your task.
    • entrypoint: Set the value of this field to /bin/bash. This lets you run multi-line bash commands directly from the build step.
    • args: The args field of a build step takes a list of arguments and passes them to the image referenced by the name field. In the following example, the args field takes the arguments for:

      • Running the test log formatter to download the test log output.
      • Printing the log output.
      • Saving test results in sponge.log.
      • Outputting the results in sponge.log to a JUNIT XML file. The name of the JUNIT XML file is constructed using the short version of the commit ID associated with your build. A subsequent build step will save the logs in this file to Cloud Storage.

        steps:
          # Run tests and save to file
          - name: golang:1.23
            entrypoint: /bin/bash
            args:
              - -c
              - |
                go install github.com/jstemmer/go-junit-report/v2@latest
                2>&1 go test -timeout 1m -v ./... | /go/bin/go-junit-report -set-exit-code -iocopy -out ${SHORT_SHA}_test_log.xml
        
  2. Upload to Artifact Registry: In your config file, use the goModules field to specify your application path and your Go repository in Artifact Registry:

    # Upload Go module to artifact registry
    artifacts:
      goModules:
        repositoryName: 'repositoryName'
        repositoryLocation: 'location'
        repositoryProjectId: 'projectId'
        sourcePath: 'sourcePath'
        modulePath: 'appPath'
        moduleVersion: 'version'
    

    Replace the following values:

    • repositoryName: the name of your Go repository in Artifact Registry.
    • location: the location for your repository in Artifact Registry.
    • projectId: the ID of the Google Cloud project that contains your Artifact Registry repository.
    • sourcePath: the path to the go.mod file in the build's workspace.
    • appPath: the path to your packaged application.
    • version: the version number for your application, formatted in numbers and dots like v1.0.1.
  3. Optional: Enable provenance generation

    Cloud Build can generate verifiable Supply chain Levels for Software Artifacts (SLSA) build provenance metadata to help secure your continuous integration pipeline.

    To enable provenance generation, add requestedVerifyOption: VERIFIED to the options section in your config file.

    Once your build completes, you can view repository details in Artifact Registry.

    You can also view build provenance metadata and validate provenance.

  4. Save test logs to Cloud Storage: You can configure Cloud Build to store any test logs in Cloud Storage by specifying an existing bucket location and path to the test logs.

    The following build step stores the test logs that you saved in the JUNIT XML file to a Cloud Storage bucket:

    # Save test logs to Google Cloud Storage
    artifacts:
      objects:
        location: gs://$_BUCKET_NAME/
        paths:
          - ${SHORT_SHA}_test_log.xml
    

    The following snippet shows the complete build config file for the preceding steps:

      steps:
        # Run tests and save to file
        - name: golang:1.23
          entrypoint: /bin/bash
          args:
            - -c
            - |
              go install github.com/jstemmer/go-junit-report/v2@latest
              2>&1 go test -timeout 1m -v ./... | /go/bin/go-junit-report -set-exit-code -iocopy -out ${SHORT_SHA}_test_log.xml
    
      # Store golang modules in Google Artifact Registry
      artifacts:
        goModules:
          repositoryName: 'repositoryName'
          repositoryLocation: 'location'
          repositoryProject_id: 'projectId'
          sourcePath: 'sourcePath'
          modulePath: 'appPath'
          moduleVersion: 'version'
    
     The following snippet shows the complete build config file for the all the steps
     described above:
    
      # Store images in Google Artifact Registry
      images:
        - us-central1-docker.pkg.dev/$PROJECT_ID/$_AR_REPO_NAME/myimage:$SHORT_SHA
    
  5. Start the build using the gcloud CLI or create a build trigger:

Google Cloud CLI

 gcloud builds submit --region=us-west2 --config=cloudbuild.yaml \
     --substitutions=_AR_REPO_NAME="AR_REPO_NAME"

Build Triggers

Follow the steps in Create a build trigger. In the Substitution variables field, you must also provide the name of your Artifact Registry repository and the name of your Cloud Storage bucket for test logs.

What's next