Writing

Google Kubernetes Engine basics

GeneralGoogle CloudTech trendsCanary deploymentsContinuous DeliveryContinuous DeploymentDockerDocker ImageGoogle Kubernetes EngineJenkinsJenkins with google cloud servicesKubernetesPODSSpinnakerSpinnaker with google cloud servicesclustergoogle cloud servicesmanage deployments

Hi, so this blog focuses on the basics of Docker, Kubernetes, Managing Deployment, Canary deployments, Continuous Deployment using Jenkins or Spinnaker along with google cloud services.

Docker:

Docker is an open platform for developing, shipping, and running applications. With Docker, you can separate your applications from your infrastructure and treat your infrastructure like a managed application. Docker helps you ship code faster, test faster, deploy faster, and shorten the cycle between writing code and running code.

Docker does this by combining kernel containerization features with workflows and tooling that helps you manage and deploy your applications.

Hello World:

Open up Cloud Shell and enter the following command to run a hello world container to get started:

docker run hello-world

The docker daemon searched for the hello-world image, didn’t find the image locally, pulled the image from a public registry called Docker Hub, created a container from that image, and ran the container for you.

Command to take a look at the container image it pulled from Docker Hub:

docker images

The second time you run this, the docker daemon finds the image in your local registry and runs the container from that image. It doesn’t have to pull the image from Docker Hub.

In order to see all containers, including ones that have finished executing,

docker ps -a

The container Names are also randomly generated but can be specified with docker run --name [container-name] hello-world.

How to build a Docker Image

Let’s build a Docker image that’s based on a simple node application,

1.Create a Docker file:

This file instructs the Docker daemon on how to build your image.

  1. The initial line specifies the base parent image, which in this case is the official Docker image for node version 6.
  2. In the second, we set the working (current) directory of the container.
  3. In the third, we add the current directory’s contents (indicated by the "." ) into the container.
  4. Then we expose the container’s port so it can accept connections on that port and finally run the node command to start the application.

This is a simple HTTP server that listens on port 80 and returns “Hello World.”,

cat > app.js <<EOF
const http = require('http');

const hostname = '0.0.0.0';
const port = 80;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
        res.end('Hello World\n');
});

server.listen(port, hostname, () => {
    console.log('Server running at http://%s:%s/', hostname, port);
});

process.on('SIGINT', function() {
    console.log('Caught interrupt signal and will exit');
    process.exit();
});
EOF

Now let’s build the image,

docker build -t node-app:0.1 .

The -t is to name and tag an image with the name:tag syntax. The name of the image is node-app and the tag is 0.1. The tag is highly recommended when building Docker image.

Command to look at the images you built:

docker images

Notice node is the base image and node-app is the image you built. You can’t remove node without removing node-app first. The size of the image is relatively small compared to VMs.

2.Run the image:

Command to run containers based on the image you built:

docker run -p 4000:80 --name my-app node-app:0.1

The --name flag allows you to name the container if you like. The -p instructs Docker to map the host’s port 4000 to the container’s port 80. Now you can reach the server at http://localhost:4000. Without port mapping, you would not be able to reach the container at localhost.

In another terminal, test the server :

curl http://localhost:4000

The container will run as long as the initial terminal is running. If you want the container to run in the background (not tied to the terminal’s session), you need to specify the -d flag.

3.some debugging practices:

1.You can look at the logs of a container using docker logs [container_id]. If you want to follow the log’s output as the container is running, use the -f option.

docker logs -f [container_id]

2.start an interactive Bash session inside the running container. You can use docker exec to do this.

docker exec -it [container_id] bash

3.You can examine a container’s metadata in Docker by using Docker inspect:

docker inspect [container_id]
4.Publish:

To push images to your private registry hosted by Google Container Registry, you need to tag the images with a registry name. The format is [hostname]/[project-id]/[image]:[tag].

For Google Container Registry:

  1. [hostname]= gcr.io
  2. [project-id]= your project’s ID
  3. [image]= your image name
  4. [tag]= any string tag of your choice. If unspecified, it defaults to “latest”.

1.Find your project id:

gcloud config list project

2.Push this image to gcr. Remember to replace [project-id]:

docker push gcr.io/[project-id]/node-app:0.2

Check that the image exists in Google Container Registry by visiting the image registry in your web browser. You can navigate via the console to Navigation menu > Container Registry or visit: http://gcr.io/[project-id]/node-app.

[Image no longer available]

For more information,

  1. https://docs.docker.com/engine/reference/builder/#known-issues-run
  2. https://hub.docker.com/_/node
  3. https://docs.docker.com/engine/reference/commandline/inspect/#examples
  4. https://docs.docker.com/engine/reference/commandline/exec/

Docker containers can be directly used in Kubernetes, which allows them to be run in the Kubernetes Engine with ease.

Kubernetes:

Google Kubernetes Engine provides a managed environment for deploying, managing, and scaling your containerized applications using Google infrastructure.

The Kubernetes Engine environment consists of multiple machines (specifically Compute Engine instances) grouped to form a container cluster.

For more information,

  1. https://cloud.google.com/kubernetes-engine/
  2. https://cloud.google.com/compute
  3. https://cloud.google.com/kubernetes-engine/docs/concepts/cluster-architecture

Cluster orchestration with Google Kubernetes Engine:

Google Kubernetes Engine (GKE) clusters are powered by the Kubernetes open-source cluster management system. Kubernetes provides the mechanisms through which you interact with your container cluster. You use Kubernetes commands and resources to deploy and manage your applications, perform administrative tasks, set policies, and monitor the health of your deployed workloads.

[Image no longer available]

Kubernetes on Google Cloud:

[Image no longer available]

1.Creating a Google Kubernetes Engine Cluster:

A cluster consists of at least one cluster master machine and multiple worker machines called nodes. Nodes are Compute Engine virtual machine (VM) instances that run the Kubernetes processes necessary to make them part of the cluster.

1. To create a cluster, run the following command,

gcloud container clusters create [CLUSTER-NAME]

2.To authenticate the cluster, run the following command,

gcloud container clusters get-credentials [CLUSTER-NAME]

GKE uses Kubernetes objects to create and manage your cluster’s resources. Kubernetes provides the Deployment object for deploying stateless applications like web servers.

2.Deploying a Google Kubernetes Engine Cluster:

1.To create a New Deployment hello-server from the hello-app container image, run the following kubectl create command:

kubectl create deployment hello-server --image=gcr.io/google-samples/hello-app:1.0

This Kubernetes command creates a Deployment object that represents hello-server. In this case, --image specifies a container image to deploy. The command pulls the example image from a Container Registry bucket. gcr.io/google-samples/hello-app:1.0 indicates the specific image version to pull. If a version is not specified, the latest version is used.

2.To create a Kubernetes Service, which is a Kubernetes resource that lets you expose your application to external traffic, run the following kubectl expose command:

kubectl expose deployment hello-server --type=LoadBalancer --port 8080

In this command,

  1. --port specifies the port that the container exposes.
  2. type="LoadBalancer" creates a Compute Engine load balancer for your container.

3.To inspect the hello-server Service, run kubectl get:

kubectl get service

4.To view the application from your web browser, open a new tab and enter the following address,

http://[EXTERNAL-IP]:8080

5.To delete the cluster, run the following command:

gcloud container clusters delete [CLUSTER-NAME]

For more information,

  1. https://cloud.google.com/kubernetes-engine/docs/concepts/cluster-architecture
  2. https://kubernetes.io/docs/concepts/workloads/controllers/deployment/
  3. https://kubernetes.io/docs/concepts/services-networking/service/
  4. https://cloud.google.com/kubernetes-engine/docs/how-to/deleting-a-cluster
Quick Kubernetes Demo

The easiest way to get started with Kubernetes is to use the kubectl create command. Use it to launch a single instance of the nginx container:

kubectl create deployment nginx --image=nginx:1.10.0

In Kubernetes, all containers run in a pod. Use the kubectl get pods command to view the running nginx container:

kubectl get pods

Once the nginx container has a Running status you can expose it outside of Kubernetes using the kubectl expose command:

kubectl expose deployment nginx --port 80 --type LoadBalancer

Behind the scenes Kubernetes created an external Load Balancer with a public IP address attached to it. Any client who hits that public IP address will be routed to the pods behind the service. In this case that would be the nginx pod.

List our services now using the kubectl get services command:

kubectl get services

Add the External IP to this command to hit the Nginx container remotely:

curl http://<External IP>:80

[Image no longer available]

Pods:

At the core of Kubernetes is the Pod. Pods represent and hold a collection of one or more containers. Generally, if you have multiple containers with a hard dependency on each other, you package the containers inside a single pod.

fb02d86798243fcb.png

Pods also have Volumes. Volumes are data disks that live as long as the pods live, and can be used by the containers in that pod. Pods provide a shared namespace for their contents which means that the two containers inside of our example pod can communicate with each other, and they also share the attached volumes.

1.Creating Pods

1. Create the monolith pod using kubectl:

kubectl create -f pods/monolith.yaml

2.Examine your pods. Use the kubectl get pods a command to list all pods running in the default namespace:

kubectl get pods

3.Once the pod is running, use kubectl describe command to get more information about the monolith pod:

kubectl describe pods monolith

Kubernetes makes it easy to create pods by describing them in configuration files and easy to view information about them when they are running.

2.Interacting with Pods

Use the kubectl logs command to view the logs for the monolith Pod.

kubectl logs monolith

use the -f flag to get a stream of the logs happening in real-time:

Use the kubectl exec command to run an interactive shell inside the Monolith Pod. This can come in handy when you want to troubleshoot from within a container:

kubectl exec monolith --stdin --tty -c monolith /bin/sh

As you can see, interacting with pods is as easy as using the kubectl command. If you need to hit a container remotely or get a login shell, Kubernetes provides everything you need to get up and going.

3.Services:

Pods aren’t meant to be persistent. They can be stopped or started for many reasons – like failed live-ness or readiness checks – and this leads to a problem:

What happens if you want to communicate with a set of Pods? When they get restarted they might have a different IP address.

That’s where Services come in. Services provide stable endpoints for Pods.

Services use labels to determine what Pods they operate on. If Pods have the correct labels, they are automatically picked up and exposed by our services.

The level of access service provides a set of pods depends on the Service’s type,

  1. ClusterIP (internal) — the default type means that this Service is only visible inside of the cluster,
  2. NodePort gives each node in the cluster an externally accessible IP and
  3. LoadBalancer adds a load balancer from the cloud provider which forwards traffic from the service to Nodes within it.

3.1.Creating a Service:

1.Secure Pod:

1.Create the secure-monolith pods and their configuration data:

kubectl create secret generic tls-certs --from-file tls/
kubectl create configmap nginx-proxy-conf --from-file nginx/proxy.conf
kubectl create -f pods/secure-monolith.yaml

Expose the secure-monolith Pod externally. To do that, create a Kubernetes service.

2.Use the kubectl create a command to create the monolith service from the monolith service configuration file:

kubectl create -f services/monolith.yaml

3.Use the gcloud compute firewall-rules a command to allow traffic to the monolith service on the exposed node port:

gcloud compute firewall-rules create allow-monolith-nodeport \
  --allow=tcp:31000

Currently, the monolith service does not have endpoints. One way to troubleshoot an issue like this is to use the kubectl get pods command with a label query.

4.Use the kubectl label a command to add to the secure-monolith Pod. Afterwards, you can check and see that your labels have been updated.

kubectl label pods secure-monolith 'secure=enabled'
kubectl get pods secure-monolith --show-labels

5.View the list of endpoints on the monolith service:

kubectl describe services monolith | grep Endpoints

2.Testing:

Let’s test this out by hitting one of our nodes again.

gcloud compute instances list
curl -k https://<EXTERNAL_IP>:31000

3.Deploying Applications with Kubernetes:

Deployments are a declarative way to ensure that the number of Pods running is equal to the desired number of Pods, specified by the user.

The main benefit of Deployments is in abstracting away the low-level details of managing Pods. Behind the scenes, Deployments use Replica Sets to manage to start and stopping the Pods.

b2e31eed284e4cfe.png

Pods are tied to the lifetime of the Node they are created on. In the example above, Node3 went down (taking a Pod with it). Instead of manually creating a new Pod and finding a Node for it, your Deployment created a new Pod and started it on Node2.

4.Creating Deployments:

We’re going to break the monolith app into three separate pieces:

  1. auth – Generates JWT tokens for authenticated users.
  2. hello – Greet authenticated users.
  3. frontend – Routes traffic to the auth and hello services.

You should be able to interact with the microservices just like with Monolith only now each piece will be able to be scaled and deployed, independently!

When you run the kubectl create command to create the auth deployment it will make one pod that conforms to the data in the Deployment manifest. This means you can scale the number of Pods by changing the number specified in the Replicas field.

1.create your deployment object:

kubectl create -f deployments/auth.yaml

2.create a service for your auth deployment.

kubectl create -f services/auth.yaml

3.Create and expose the hello deployment:

kubectl create -f deployments/hello.yaml
kubectl create -f services/hello.yaml

4.Create and expose the frontend Deployment.

kubectl create configmap nginx-frontend-conf --from-file=nginx/frontend.conf
kubectl create -f deployments/frontend.yaml
kubectl create -f services/frontend.yaml

There is one more step to creating the frontend because you need to store some configuration data with the container.

Interact with the frontend by grabbing it’s External IP and then curling to it:

kubectl get services frontend
curl -k https://<EXTERNAL-IP>

For more information,

  1. https://kubernetes.io/docs/concepts/workloads/pods/
  2. http://kubernetes.io/docs/user-guide/services/
  3. http://kubernetes.io/docs/user-guide/deployments/#what-is-a-deployment

[Image no longer available]

Managing Deployments Using Kubernetes Engine:

1.learn about the deployment object

Take a look at the Deployment object.

kubectl explain deployment

We can also see all of the fields using the --recursive option.

You can use the explain command as you go through the lab to help you understand the structure of a Deployment object and understand what the individual fields do.

kubectl explain deployment.metadata.name

2.Create a deployment:

When you run the kubectl create command to create the auth deployment, it will make one pod that conforms to the data in the Deployment manifest. This means we can scale the number of Pods by changing the number specified in the replicas field.

1.create your deployment object using kubectl create:

kubectl create -f deployments/auth.yaml

2.verify that it was created.

kubectl get deployments

3.Once the deployment is created, Kubernetes will create a ReplicaSet for the Deployment. We can verify that a ReplicaSet was created for our Deployment:

kubectl get replicasets

4.Finally, we can view the Pods that were created as part of our Deployment. The single Pod is created by the Kubernetes when the ReplicaSet is created

kubectl get pods

5.It’s time to create a service for our auth deployment. You’ve already seen service manifest files, so we won’t go into the details here. Use the kubectl create command to create the auth service.

kubectl create -f services/auth.yaml

6.create and expose the frontend Deployment.

kubectl create secret generic tls-certs --from-file tls/
kubectl create configmap nginx-frontend-conf --from-file=nginx/frontend.conf
kubectl create -f deployments/frontend.yaml
kubectl create -f services/frontend.yaml

Interact with the frontend by grabbing its external IP and then curling to it.

3.Scale a Deployment:

Now that we have a Deployment created, we can scale it. Do this by updating the spec.replicas field. After the Deployment is updated, Kubernetes will automatically update the associated ReplicaSet and start new Pods to make the total number of Pods equal 5.

kubectl explain deployment.spec.replicas

The replicas field can be most easily updated using the kubectl scale command:

kubectl scale deployment hello --replicas=5

After the Deployment is updated, Kubernetes will automatically update the associated ReplicaSet and start new Pods to make the total number of Pods equal 5.

Rolling update:

Deployments support updating images to a new version through a rolling update mechanism.

Trigger a rolling update,

1. Update your deployment

2.The updated Deployment will be saved to your cluster and Kubernetes will begin a rolling update.

kubectl get replicaset

3.You can also see a new entry in the rollout history:

kubectl rollout history deployment/hello

4.Pause a rolling update

If you detect problems with a running rollout, pause it to stop the update:

kubectl rollout pause deployment/hello

Verify the current state of the rollout:

kubectl rollout status deployment/hello

5.Resume a rolling update

The rollout is paused which means that some pods are at the new version and some pods are at the older version. We can continue the rollout using the resume command.

kubectl rollout resume deployment/hello

Verify the current state of the rollout:

kubectl rollout status deployment/hello

6.Rollback an update

Assume that a bug was detected in your new version. Since the new version is presumed to have problems, any users connected to the new Pods will experience those issues.

Use the rollout command to roll back to the previous version:

kubectl rollout undo deployment/hello

Verify the roll back in the history:

kubectl rollout history deployment/hello

Canary deployments:

When you want to test a new deployment in production with a subset of your users, use a canary deployment. Canary deployments allow you to release a change to a small subset of your users to mitigate risk associated with new releases.

1.Create a new canary deployment for the new version:

cat deployments/hello-canary.yaml

2.Create the canary deployment:

kubectl create -f deployments/hello-canary.yaml

3.After the canary deployment is created, you should have two deployments, hello and hello-canary:

kubectl get deployments

4.Verify the canary deployment:

curl -ks https://`kubectl get svc frontend -o=jsonpath="{.status.loadBalancer.ingress[0].ip}"`/version

1.Blue-green deployments

Rolling updates are ideal because they allow you to deploy an application slowly with minimal overhead, minimal performance impact, and minimal downtime.

Kubernetes achieves this by creating two separate deployments; one for the old “blue” version and one for the new “green” version. Use your existing hello deployment for the “blue” version. The deployments will be accessed via a Service which will act as the router. Once the new “green” version is up and running, you’ll switch over to using that version by updating the Service.

9e624196fdaf4534.png

A major downside of blue-green deployments is that you will need to have at least 2x the resources in your cluster necessary to host your application.

1.Updating using Blue-Green Deployment

In order to support a blue-green deployment style, we will create a new “green” deployment for our new version. The green deployment updates the version label and the image path.

1.Create the green deployment:

kubectl create -f deployments/hello-green.yaml

2.Verify that the current version of 1.0.0:

curl -ks https://`kubectl get svc frontend -o=jsonpath="{.status.loadBalancer.ingress[0].ip}"`/version

3.Now, update the service to point to the new version:

kubectl apply -f services/hello-green.yaml

4.With the service is updated, the “green” deployment will be used immediately. You can now verify that the new version is always being used.

curl -ks https://`kubectl get svc frontend -o=jsonpath="{.status.loadBalancer.ingress[0].ip}"`/version

2.Blue-Green Rollback:

If necessary, you can roll back to the old version in the same way. While the “blue” deployment is still running, just update the service back to the old version.

kubectl apply -f services/hello-blue.yaml

Once you have updated the service, your rollback will have been successful. Again, verify that the right version is now being used:

curl -ks https://`kubectl get svc frontend -o=jsonpath="{.status.loadBalancer.ingress[0].ip}"`/version

Continuous Delivery in Kubernetes Engine

What is Continuous Delivery / Continuous Deployment?

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.

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.

[Image no longer available]

What is Jenkins?

Jenkins is an open-source automation server that lets you flexibly orchestrate your build, test, and deployment pipelines. Jenkins allows developers to iterate quickly on projects without worrying about overhead issues that can stem from continuous delivery.

For more information,

  1. https://cloud.google.com/solutions/jenkins-on-kubernetes-engine
  2. https://plugins.jenkins.io/kubernetes/

Provisioning Jenkins

1.Creating a Kubernetes cluster

1.Provision a Kubernetes cluster:

gcloud container clusters create jenkins-cd \
--num-nodes 2 \
--machine-type n1-standard-2 \
--scopes "https://www.googleapis.com/auth/source.read_write,cloud-platform"

Verify that your cluster is running :

gcloud container clusters list

Now, get the credentials for your cluster:

gcloud container clusters get-credentials jenkins-cd

Kubernetes Engine uses these credentials to access your newly provisioned cluster—confirm that you can connect to it by running the following command:

kubectl cluster-info
Setup Helm:

You can use Helm to install Jenkins from the Charts repository. Helm is a package manager that makes it easy to configure and deploy Kubernetes applications. Once you have Jenkins installed, you’ll be able to set up your CI/CD pipeline.

  1. Add Helm’s stable chart repo:
helm repo add stable https://kubernetes-charts.storage.googleapis.com/
  1. Ensure the repo is up to date:
helm repo update

Configure and Install Jenkins

  1. Use the Helm CLI to deploy the chart with your configuration settings.
helm install cd stable/jenkins -f jenkins/values.yaml --version 1.2.2 --wait
  1. Once that command completes ensure the Jenkins pod goes to the Running state and the container is in the READY state:
kubectl get pods
  1. Configure the Jenkins service account to be able to deploy to the cluster.
kubectl create clusterrolebinding jenkins-deploy --clusterrole=cluster-admin --serviceaccount=default:cd-jenkins
  1. Run the following command to setup port forwarding to the Jenkins UI from the Cloud Shell
export POD_NAME=$(kubectl get pods --namespace default -l "app.kubernetes.io/component=jenkins-master" -l "app.kubernetes.io/instance=cd" -o jsonpath="{.items[0].metadata.name}")
kubectl port-forward $POD_NAME 8080:8080 >> /dev/null &
  1. Now, check that the Jenkins Service was created properly:
kubectl get svc

You are using the Kubernetes Plugin so that our builder nodes will be automatically launched as necessary when the Jenkins master requests them.

For more information,

  1. https://plugins.jenkins.io/kubernetes/

Connect to Jenkins

  1. The Jenkins chart will automatically create an admin password for you. To retrieve it, run:
printf $(kubectl get secret cd-jenkins -o jsonpath="{.data.jenkins-admin-password}" | base64 --decode);echo
  1. To get to the Jenkins user interface, click on the Web Preview button in cloud shell, then click Preview on port 8080:

web_prev.png

  1. You should now be able to log in with username admin and your auto-generated password.

Understanding the Application

The application mimics a microservice by supporting two operation modes.

  1. In backend mode: gceme listens on port 8080 and returns Compute Engine instance metadata in JSON format.
  2. In frontend mode: gceme queries the backend gceme service and renders the resulting JSON in the user interface.

fc22b68ab20dfe0e.png

Deploying the Application

You will deploy the application into two different environments:

  1. Production: The live site that your users access.
  2. Canary: A smaller-capacity site that receives only a percentage of your user traffic. Use this environment to validate your software with live traffic before it’s released to all of your users.

1.Create the Kubernetes namespace to logically isolate the deployment:

kubectl create ns production

2.Create the production and canary deployments, and the services using the kubectl apply commands:

kubectl apply -f k8s/production -n production

kubectl apply -f k8s/canary -n production

kubectl apply -f k8s/services -n production

By default, only one replica of the frontend is deployed. Use the kubectl scale command to ensure that there are at least 4 replicas running at all times.

3.Scale up the production environment frontends by running the following command:

kubectl scale deployment gceme-frontend-production -n production --replicas 4

4.Confirm that you have your pods running for the frontend and backend,

kubectl get pods -n production -l app=gceme -l role=frontend

kubectl get pods -n production -l app=gceme -l role=backend

5.Retrieve the external IP for the production services:

kubectl get service gceme-frontend -n production

6.Now, store the frontend service load balancer IP in an environment variable for use later:

export FRONTEND_SERVICE_IP=$(kubectl get -o jsonpath="{.status.loadBalancer.ingress[0].ip}" --namespace=production services gceme-frontend)

Confirm that both services are working by opening the frontend external IP address in your browser.

Creating the Jenkins Pipeline

Creating a repository to host the sample app source code

1.Create a copy of the gceme sample app and push it to a Cloud Source Repository:

gcloud source repos create default

2.Initialize the sample-app directory as its own Git repository:

git config credential.helper gcloud.sh

3.Run the following command:

git remote add origin https://source.developers.google.com/p/$DEVSHELL_PROJECT_ID/r/default

4.Set the username and email address for your Git commits. Replace [EMAIL_ADDRESS] with your Git email address and [USERNAME] with your Git username:

git config --global user.email "[EMAIL_ADDRESS]"

git config --global user.name "[USERNAME]"

5.Add, commit, and push the files:

git add .

git commit -m "Initial commit"

git push origin master

Adding your service account credentials

Configure your credentials to allow Jenkins to access the code repository. Jenkins will use your cluster’s service account credentials in order to download code from the Cloud Source Repositories.

1. In the Jenkins user interface, click Manage Jenkins in the left navigation then click Manage Credentials.

**2.**Click Jenkins stored_scoped_cred.png

3.Click Global credentials (unrestricted).

4.Click Add Credentials in the left navigation.

5.Select Google Service Account from metadata from the Kind drop-down and click OK.

global_cred.png

Creating the Jenkins job

Navigate to your Jenkins user interface and follow these steps to configure a Pipeline job.

1.Click Jenkins > New Item in the left navigation:

86e92964a4599231.png

2.Name the project sample-app, then choose the Multibranch Pipeline option and click OK.

3.On the next page, in the Branch Sources section, click Add Source and select git.

4.Paste the HTTPS clone URL of your sample-app repo in Cloud Source Repositories into the Project Repository field. Replace [PROJECT_ID] with your Project ID:

https://source.developers.google.com/p/[PROJECT_ID]/r/default

5.From the Credentials drop-down, select the name of the credentials you created when adding your service account in the previous steps.

6.Under Scan Multibranch Pipeline Triggers section, check the Periodically if not otherwise run box and set the Interval value to 1 minute.

7.Your job configuration should look like this:

general_tab_jenkins.png

branch_source_jenkins.png

build_conf_jenkins.png

8.Click Save leaving all other options with their defaults

Creating the Development Environment

1.Create a development branch, to create a development environment from a feature branch, you can push the branch to the Git server and let Jenkins deploy your environment:

2.Modifying the pipeline definition

The Jenkinsfile that defines that pipeline is written using the Jenkins Pipeline Groovy syntax. Pipelines support powerful features like parallelization and require manual user approval.

1.Modify the site

2.Kick off Deployment

Commit and push your changes:

git add .

git commit -m "Version 2.0.0"

git push origin new-feature

This will kick off a build of your development environment.

After the change is pushed to the Git repository, navigate to the Jenkins user interface where you can see that your build started for the new-feature branch. It can take up to a minute for the changes to be picked up.

757c7d394c91b309.png

After the build is running, click the down arrow next to the build in the left navigation and select Console output:

6ea3b2ed776e3b29.png

To help secure your application, you can use kubectl proxy. The proxy authenticates itself with the Kubernetes API and proxies requests from your local machine to the service in the cluster without exposing your service to the Internet.

3.Deploying a Canary Release

You have verified that your app is running the latest code in the development environment, so now deploy that code to the canary environment.

Create a canary branch and push it to the Git server:

git checkout -b canary

git push origin canary

In Jenkins, you should see the canary pipeline has kicked off. Once complete, you can check the service URL to ensure that some of the traffic is being served by your new version.

export FRONTEND_SERVICE_IP=$(kubectl get -o \
jsonpath="{.status.loadBalancer.ingress[0].ip}" --namespace=production services gceme-frontend)
while true; do curl http://$FRONTEND_SERVICE_IP/version; sleep 1; done

4.Deploying to production

Create a canary branch and push it to the Git server:

git checkout master

git merge canary

git push origin master

In Jenkins, you should see the master pipeline has kicked off. Once complete (which may take a few minutes), you can check the service URL to ensure that all of the traffic is being served by your new version, 2.0.0.

export FRONTEND_SERVICE_IP=$(kubectl get -o \
jsonpath="{.status.loadBalancer.ingress[0].ip}" --namespace=production services gceme-frontend)
while true; do curl http://$FRONTEND_SERVICE_IP/version; sleep 1; done
kubectl get service gceme-frontend -n production

Continuous Delivery Pipelines with Spinnaker and Kubernetes Engine

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.

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. When a given change has been vetted through automation, you can also validate the application manually and conduct further pre-release testing.

1.Create a Kubernetes Engine using the Spinnaker tutorial sample application:

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

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

Deploying Spinnaker using Helm

Helm is a package manager you can use to configure and deploy Kubernetes applications.

Install Helm

  1. Download and install the helm binary:
wget https://get.helm.sh/helm-v3.1.0-linux-amd64.tar.gz
  1. Unzip the file to your local system:
tar zxfv helm-v3.1.0-linux-amd64.tar.gz

cp linux-amd64/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://kubernetes-charts.storage.googleapis.com
./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-central1 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:
  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
  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.

bde9fe42e27656fb.png

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

8c03705c17bf3b7f.png

Building the Docker image

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 and download the sample application source code:
gsutil -m cp -r gs://spls/gsp114/sample-app.tar .
  1. Unpack the source code and Change directories

3.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]"

4.Make the initial commit to your source code repository:

git init

git add .

git commit -m "Initial commit"

5.Create a repository to host your code:

gcloud source repos create sample-app

6.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

7.Push your code to the new repository’s master branch:

git push origin master

8.Check that you can see your source code in the Console by clicking Navigation Menu > Source Repositories.

9.Click View All Repositories and select sample-app.

source-repo.png

Configure your build triggers

Configure Container Builder to build and push your Docker images every time you push Git tags to your source repository.

bcab2f07975c8776.png

  1. In the Cloud Platform Console, click Navigation menu > Cloud Build > Triggers.
  2. Click Create trigger.

CloudBuild_BuildTriggers.png

  1. Set the trigger settings

  2. Click CREATE.

create_trigger_console.png

Prepare your Kubernetes Manifests for use in Spinnaker

Spinnaker needs access to your Kubernetes manifests in order to deploy them to your clusters. 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-central1 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
  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.

CloudBuild_BuildHistory.png

Configuring your deployment pipelines

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

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
  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. To verify the pipeline, manually trigger it.

  1. In the Spinnaker UI and 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.

app-sample.png

  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 to trigger the pipeline this first time.

start-man-ex.png

  1. Click Run.
  2. Click Execution Details to see more information about the pipeline’s progress.

man-start-detail.png

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

progress-bar.png

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.

  2. Hover over the yellow “person” icon and click Continue.

continue-to-deploy.png

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

infrasturcture-lb.png

  1. Scroll down the list of load balancers and click Default, under service sample-frontend-production.
  2. 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.

ingress.png

  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.

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

Triggering your pipeline from code changes

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.
  2. 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.

d006977feef1a15d.png

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.

  3. 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

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.

For more information,

  1. https://spinnaker.io/reference/providers/kubernetes/
  2. https://spinnaker.io/concepts/
  3. https://cloud.google.com/solutions/continuous-delivery-toolchain-spinnaker-cloud

For basics of Google cloud services covered in in the Cloud Engineering Track:

https://programmerprodigy.code.blog/2020/11/10/google-cloud-services-basics/

I have mostly picked up information from Google documentation, and pictures i have used to explain concepts are not by me, I just found them online.