arrow_back

Continuous Delivery Pipelines with Spinnaker and Kubernetes Engine

Join Sign in

Continuous Delivery Pipelines with Spinnaker and Kubernetes Engine

1 hour 30 minutes 7 Credits

GSP114

Google Cloud self-paced labs logo

Overview

This hands-on lab shows you how to create a continuous delivery pipeline using Google Kubernetes Engine, Google Cloud Source Repositories, Google Cloud Container Builder, and Spinnaker. After you create a sample application, you configure these services to automatically build, test, and deploy it. When you modify the application code, the changes trigger the continuous delivery pipeline to automatically rebuild, retest, and redeploy the new version.

Objectives

  • Set up your environment by launching Google Cloud Shell, creating a Kubernetes Engine cluster, and configuring your identity and user management scheme.

  • Download a sample application, create a Git repository then upload it to a Google Cloud Source Repository.

  • Deploy Spinnaker to Kubernetes Engine using Helm.

  • Build your Docker image.

  • Create triggers to create Docker images when your application changes.

  • Configure a Spinnaker pipeline to reliably and continuously deploy your application to Kubernetes Engine.

  • Deploy a code change, triggering the pipeline, and watch it roll out to production.

Pipeline architecture

To continuously deliver application updates to your users, you need an automated process that reliably builds, tests, and updates your software. Code changes should automatically flow through a pipeline that includes artifact creation, unit testing, functional testing, and production rollout. In some cases, you want a code update to apply to only a subset of your users, so that it is exercised realistically before you push it to your entire user base. If one of these canary releases proves unsatisfactory, your automated procedure must be able to quickly roll back the software changes.

Process diagram

With Kubernetes Engine and Spinnaker you can create a robust continuous delivery flow that helps to ensure your software is shipped as quickly as it is developed and validated. Although rapid iteration is your end goal, you must first ensure that each application revision passes through a gamut of automated validations before becoming a candidate for production rollout. When a given change has been vetted through automation, you can also validate the application manually and conduct further pre-release testing.

After your team decides the application is ready for production, one of your team members can approve it for production deployment.

Application delivery pipeline

In this lab you build the continuous delivery pipeline shown in the following diagram.

Continuous delivery pipeline flow diagram

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.

  4. Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  5. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Navigation menu icon

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:

Your Cloud Platform project in this session is set to YOUR_PROJECT_ID

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:

gcloud auth list
  1. Click Authorize.

  2. Your output should now look like this:

Output:

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:

gcloud config list project

Output:

[core] project = <project_ID>

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Task 1. Set up your environment

Configure the infrastructure and identities required for this lab. First you'll create a Kubernetes Engine cluster to deploy Spinnaker and the sample application.

  1. Set the default compute zone:

gcloud config set compute/zone us-east1-d
  1. Create a Kubernetes Engine cluster using the Spinnaker tutorial sample application:

gcloud container clusters create spinnaker-tutorial \ --machine-type=n1-standard-2

Cluster creation takes between five and ten minutes to complete. Wait for your cluster to finish provisioning before proceeding.

When completed you see a report detailing the name, location, version, ip-address, machine-type, node version, number of nodes and status of the cluster that indicates the cluster is running.

Configure identity and access management

Create a Cloud Identity Access Management (Cloud IAM) service account to delegate permissions to Spinnaker, allowing it to store data in Cloud Storage. Spinnaker stores its pipeline data in Cloud Storage to ensure reliability and resiliency. If your Spinnaker deployment unexpectedly fails, you can create an identical deployment in minutes with access to the same pipeline data as the original.

Upload your startup script to a Cloud Storage bucket by following these steps:

  1. Create the service account:

gcloud iam service-accounts create spinnaker-account \ --display-name spinnaker-account
  1. Store the service account email address and your current project ID in environment variables for use in later commands:

export SA_EMAIL=$(gcloud iam service-accounts list \ --filter="displayName:spinnaker-account" \ --format='value(email)') export PROJECT=$(gcloud info --format='value(config.project)')
  1. Bind the storage.admin role to your service account:

gcloud projects add-iam-policy-binding $PROJECT \ --role roles/storage.admin \ --member serviceAccount:$SA_EMAIL
  1. Download the service account key. In a later step, you will install Spinnaker and upload this key to Kubernetes Engine:

gcloud iam service-accounts keys create spinnaker-sa.json \ --iam-account $SA_EMAIL

Output:

created key [12f224e036437704b91a571792462ca6fc4cd438] of type [json] as [spinnaker-sa.json] for [spinnaker-account@qwiklabs-gcp-gcpd-f5e16da10e5d.iam.gserviceaccount.com]

Task 2. Set up Cloud Pub/Sub to trigger Spinnaker pipelines

  1. Create the Cloud Pub/Sub topic for notifications from Container Registry:

gcloud pubsub topics create projects/$PROJECT/topics/gcr
  1. Create a subscription that Spinnaker can read from to receive notifications of images being pushed:

gcloud pubsub subscriptions create gcr-triggers \ --topic projects/${PROJECT}/topics/gcr
  1. Give Spinnaker's service account permissions to read from the gcr-triggers subscription:

export SA_EMAIL=$(gcloud iam service-accounts list \ --filter="displayName:spinnaker-account" \ --format='value(email)') gcloud beta pubsub subscriptions add-iam-policy-binding gcr-triggers \ --role roles/pubsub.subscriber --member serviceAccount:$SA_EMAIL

Test completed task

Click Check my progress to verify your performed task. If you have successfully set up the environment, you will see an assessment score.

Set up your environment

Task 3. Deploying Spinnaker using Helm

In this section you use Helm to deploy Spinnaker from the Charts repository. Helm is a package manager you can use to configure and deploy Kubernetes applications.

Helm is already installed in your Cloud Shell.

Configure Helm

  1. Grant Helm the cluster-admin role in your cluster:

kubectl create clusterrolebinding user-admin-binding \ --clusterrole=cluster-admin --user=$(gcloud config get-value account)
  1. Grant Spinnaker the cluster-admin role so it can deploy resources across all namespaces:

kubectl create clusterrolebinding --clusterrole=cluster-admin \ --serviceaccount=default:default spinnaker-admin
  1. Add the stable charts deployments to Helm's usable repositories (includes Spinnaker):

helm repo add stable https://charts.helm.sh/stable helm repo update

Configure Spinnaker

  1. Still in Cloud Shell, create a bucket for Spinnaker to store its pipeline configuration:

export PROJECT=$(gcloud info \ --format='value(config.project)') export BUCKET=$PROJECT-spinnaker-config gsutil mb -c regional -l us-east1 gs://$BUCKET
  1. Run the following command to create a spinnaker-config.yaml file, which describes how Helm should install Spinnaker:

export SA_JSON=$(cat spinnaker-sa.json) export PROJECT=$(gcloud info --format='value(config.project)') export BUCKET=$PROJECT-spinnaker-config cat > spinnaker-config.yaml <<EOF gcs: enabled: true bucket: $BUCKET project: $PROJECT jsonKey: '$SA_JSON' dockerRegistries: - name: gcr address: https://gcr.io username: _json_key password: '$SA_JSON' email: 1234@5678.com # Disable minio as the default storage backend minio: enabled: false # Configure Spinnaker to enable GCP services halyard: spinnakerVersion: 1.19.4 image: repository: us-docker.pkg.dev/spinnaker-community/docker/halyard tag: 1.32.0 pullSecrets: [] additionalScripts: create: true data: enable_gcs_artifacts.sh: |- \$HAL_COMMAND config artifact gcs account add gcs-$PROJECT --json-path /opt/gcs/key.json \$HAL_COMMAND config artifact gcs enable enable_pubsub_triggers.sh: |- \$HAL_COMMAND config pubsub google enable \$HAL_COMMAND config pubsub google subscription add gcr-triggers \ --subscription-name gcr-triggers \ --json-path /opt/gcs/key.json \ --project $PROJECT \ --message-format GCR EOF

Deploy the Spinnaker chart

  1. Use the Helm command-line interface to deploy the chart with your configuration set:

helm install -n default cd stable/spinnaker -f spinnaker-config.yaml \ --version 2.0.0-rc9 --timeout 10m0s --wait Note: The installation typically takes 5-8 minutes to complete.
  1. After the command completes, run the following command to set up port forwarding to Spinnaker from Cloud Shell:

export DECK_POD=$(kubectl get pods --namespace default -l "cluster=spin-deck" \ -o jsonpath="{.items[0].metadata.name}") kubectl port-forward --namespace default $DECK_POD 8080:9000 >> /dev/null &
  1. To open the Spinnaker user interface, click the Web Preview icon at the top of the Cloud Shell window and select Preview on port 8080.

Web Preview icon at the top of the Cloud Shell window

The welcome screen opens, followed by the Spinnaker user interface.

Leave this tab open, this is where you'll access the Spinnaker UI.

Test completed task

Click Check my progress to verify your performed task. If you have successfully deployed the Spinnaker chart using Kubernetes Helm, you will see an assessment score.

Deploy the Spinnaker chart using Kubernetes Helm

Task 4. Building the Docker image

In this section, you configure Cloud Build to detect changes to your app source code, build a Docker image, and then push it to Container Registry.

Create your source code repository

  1. In Cloud Shell tab, download the sample application source code:

gsutil -m cp -r gs://spls/gsp114/sample-app.tar .
  1. Unpack the source code:

mkdir sample-app tar xvf sample-app.tar -C ./sample-app
  1. Change directories to the source code:

cd sample-app
  1. Set the username and email address for your Git commits in this repository. Replace [USERNAME] with a username you create:

git config --global user.email "$(gcloud config get-value core/account)" git config --global user.name "[USERNAME]"
  1. Make the initial commit to your source code repository:

git init git add . git commit -m "Initial commit"
  1. Create a repository to host your code:

gcloud source repos create sample-app Note: Disregard the "you may be billed for this repository" message. git config credential.helper gcloud.sh
  1. Add your newly created repository as remote:

export PROJECT=$(gcloud info --format='value(config.project)') git remote add origin https://source.developers.google.com/p/$PROJECT/r/sample-app
  1. Push your code to the new repository's master branch:

git push origin master
  1. Check that you can see your source code in the Console by clicking Navigation Menu > Source Repositories.

  2. Click sample-app.

Configure your build triggers

Configure Container Builder to build and push your Docker images every time you push Git tags to your source repository. Container Builder automatically checks out your source code, builds the Docker image from the Dockerfile in your repository, and pushes that image to Google Cloud Container Registry.

Container Builder flow diagram

  1. In the Cloud Platform Console, click Navigation menu > Cloud Build > Triggers.

  2. Click Create trigger.

  3. Set the following trigger settings:

  • Name: sample-app-tags

  • Event: Push new tag

  • Select your newly created sample-app repository.

  • Tag: .*(any tag)

  • Configuration: Cloud Build configuration file (yaml or json)

  • Cloud Build configuration file location: /cloudbuild.yaml

  1. Click CREATE.

CreateTrigger-1.png

From now on, whenever you push a Git tag (.*) to your source code repository, Container Builder automatically builds and pushes your application as a Docker image to Container Registry.

Prepare your Kubernetes Manifests for use in Spinnaker

Spinnaker needs access to your Kubernetes manifests in order to deploy them to your clusters. This section creates a Cloud Storage bucket that will be populated with your manifests during the CI process in Cloud Build. After your manifests are in Cloud Storage, Spinnaker can download and apply them during your pipeline's execution.

  1. Create the bucket:

export PROJECT=$(gcloud info --format='value(config.project)') gsutil mb -l us-east1 gs://$PROJECT-kubernetes-manifests
  1. Enable versioning on the bucket so that you have a history of your manifests:

gsutil versioning set on gs://$PROJECT-kubernetes-manifests
  1. Set the correct project ID in your kubernetes deployment manifests:

sed -i s/PROJECT/$PROJECT/g k8s/deployments/*
  1. Commit the changes to the repository:

git commit -a -m "Set project ID"

Build your image

Push your first image using the following steps:

  1. In Cloud Shell, still in the sample-app directory, create a Git tag:

git tag v1.0.0
  1. Push the tag:

git push --tags

Output:

To https://source.developers.google.com/p/qwiklabs-gcp-ddf2925f84de0b16/r/sample-app * [new tag] v1.0.0 -> v1.0.0
  1. Go to the Cloud Console. Still in Cloud Build, click History in the left pane to check that the build has been triggered. If not, verify that the trigger was configured properly in the previous section.

Stay on this page and wait for the build to complete before going on to the next section.

Note: If the Build fails, then click on the Build ID to open the Build details page and then click RETRY.

Test completed task

Click Check my progress to verify your performed task. If you have successfully built the Docker image, you will see an assessment score.

Build the Docker image

Task 5. Configuring your deployment pipelines

Now that your images are building automatically, you need to deploy them to the Kubernetes cluster.

You deploy to a scaled-down environment for integration testing. After the integration tests pass, you must manually approve the changes to deploy the code to production services.

Install the spin CLI for managing Spinnaker

spin is a command-line utility for managing Spinnaker's applications and pipelines.

  1. Download the 1.14.0 version of spin:

curl -LO https://storage.googleapis.com/spinnaker-artifacts/spin/1.14.0/linux/amd64/spin
  1. Make spin executable:

chmod +x spin

Create the deployment pipeline

  1. Use spin to create an app called sample in Spinnaker. Set the owner email address for the app in Spinnaker:

./spin application save --application-name sample \ --owner-email "$(gcloud config get-value core/account)" \ --cloud-providers kubernetes \ --gate-endpoint http://localhost:8080/gate

Next, you create the continuous delivery pipeline. In this tutorial, the pipeline is configured to detect when a Docker image with a tag prefixed with "v" has arrived in your Container Registry.

  1. From your sample-app source code directory, run the following command to upload an example pipeline to your Spinnaker instance:

export PROJECT=$(gcloud info --format='value(config.project)') sed s/PROJECT/$PROJECT/g spinnaker/pipeline-deploy.json > pipeline.json ./spin pipeline save --gate-endpoint http://localhost:8080/gate -f pipeline.json

Manually trigger and view your pipeline execution

The configuration you just created uses notifications of newly tagged images being pushed to trigger a Spinnaker pipeline. In a previous step, you pushed a tag to the Cloud Source Repositories which triggered Cloud Build to build and push your image to Container Registry. To verify the pipeline, manually trigger it.

  1. Switch to your browser tab displaying your Spinnaker UI.

If you are unable to find it, you can get to this tab again by selecting Web Preview > Preview on Port 8080 in your Cloud Shell window.

  1. In the Spinnaker UI, click Applications at the top of the screen to see your list of managed applications.

sample is your application. If you don't see sample, try refreshing the Spinnaker Applications tab.

  1. Click sample to view your application deployment.

  2. Click Pipelines at the top to view your applications pipeline status.

  3. Click Start Manual Execution, select Deploy in Select Pipeline, and then click Run to trigger the pipeline this first time.

  4. Click Execution Details to see more information about the pipeline's progress.

The progress bar shows the status of the deployment pipeline and its steps.

Progress bar

Steps in blue are currently running, green ones have completed successfully, and red ones have failed.

  1. Click a stage to see details about it.

After 3 to 5 minutes the integration test phase completes and the pipeline requires manual approval to continue the deployment.

  1. Hover over the yellow "person" icon and click Continue.

Your rollout continues to the production frontend and backend deployments. It completes after a few minutes.

  1. To view the app, at the top of the Spinnaker UI, select Infrastructure > Load Balancers.

  2. Scroll down the list of load balancers and click Default, under service sample-frontend-production. You will see details for your load balancer appear on the right side of the page. If you do not, you may need to refresh your browser.

  3. Scroll down the details pane on the right and copy your app's IP address by clicking the clipboard button on the Ingress IP. The ingress IP link from the Spinnaker UI may use HTTPS by default, while the application is configured to use HTTP.

Details pane

  1. Paste the address into a new browser tab to view the application. You might see the canary version displayed, but if you refresh you will also see the production version.

Production version of the application

You have now manually triggered the pipeline to build, test, and deploy your application.

Test Completed Task

Click Check my progress to verify your performed task. If you have successfully created service load balancers, you will see an assessment score.

Create service load balancers

Test completed task

Click Check my progress to verify your performed task. If you have successfully deployed an image to production, you will see an assessment score.

Deploy an image to production

Task 6. Triggering your pipeline from code changes

Now test the pipeline end to end by making a code change, pushing a Git tag, and watching the pipeline run in response. By pushing a Git tag that starts with "v", you trigger Container Builder to build a new Docker image and push it to Container Registry. Spinnaker detects that the new image tag begins with "v" and triggers a pipeline to deploy the image to canaries, run tests, and roll out the same image to all pods in the deployment.

  1. From your sample-app directory, change the color of the app from orange to blue:

sed -i 's/orange/blue/g' cmd/gke-info/common-service.go
  1. Tag your change and push it to the source code repository:

git commit -a -m "Change color to blue" git tag v1.0.1 git push --tags
  1. In the Console, in Cloud Build > History, wait a couple of minutes for the new build to appear. You may need to refresh your page. Wait for the new build to complete, before going to the next step.
Note: If the Build fails, please click on Build ID and then click RETRY.
  1. Return to the Spinnaker UI and click Pipelines to watch the pipeline start to deploy the image. The automatically triggered pipeline will take a few minutes to appear. You may need to refresh your page.

Pipelines tab in Spinaker UI

Test completed task

Click Check my progress to verify your performed task. If you have successfully triggered a pipeline from code changes, you will see an assessment score.

Triggering pipeline from code changes

Task 7. Observe the canary deployments

  1. When the deployment is paused, waiting to roll out to production, return to the web page displaying your running application and start refreshing the tab that contains your app. Four of your backends are running the previous version of your app, while only one backend is running the canary. You should see the new, blue version of your app appear about every fifth time you refresh.

  2. When the pipeline completes, your app looks like the following screenshot. Note that the color has changed to blue because of your code change, and that the Version field now reads canary.

Blue canary version

You have now successfully rolled out your app to your entire production environment!

  1. Optionally, you can roll back this change by reverting your previous commit. Rolling back adds a new tag (v1.0.2), and pushes the tag back through the same pipeline you used to deploy v1.0.1:

git revert v1.0.1

Press CTRL+O, ENTER, CTRL+X.

git tag v1.0.2 git push --tags
  1. When the build and then the pipeline completes, verify the roll back by clicking Infrastructure > Load Balancers, then click the service sample-frontend-production Default and copy the Ingress IP address into a new tab.

Now your app is back to orange and you can see the production version number.

Orange production version of the UI

Congratulations!

You have now successfully completed the Continuous Delivery Pipelines with Spinnaker and Kubernetes Engine lab.

Finish your quest

This self-paced lab is part of the Google Cloud Solutions I: Scaling Your Infrastructure and DevOps Essentials quests. A quest is a series of related labs that form a learning path. Completing this quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in any quest that contains this lab and get immediate completion credit. See the Google Cloud Skills Boost catalog to see all available quests.

Take your next lab

Continue your quest with Running Dedicated Game Servers in Google Kubernetes Engine

Next steps / Learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated: August 22, 2022

Lab Last Tested: July 12, 2022

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.