Automated canary deployments with Flagger and Istio

Automated canary deployments with Flagger and IstioStefan ProdanBlockedUnblockFollowFollowingFeb 20Continuous delivery is accepted as an enterprise software practice, and is a natural evolution of well-established continuous integration principles.

However continuous deployment continues to be notably rare, perhaps due to the complexity of management and the fear of failed deployments impacting system availability.

Flagger is an open source Kubernetes operator that aims to untangle this complexity.

It automates the promotion of canary deployments utilising Istio’s traffic shifting and Prometheus metrics to analyse an application’s behaviour during a controlled rollout.

What follows is a step-by-step guide to setting up and using Flagger on Google Kubernetes Engine (GKE).

Kubernetes cluster setupYou’ll begin by creating a GKE cluster with the Istio add-on (if you don’t have a GCP account you can sign up here for free credits).

Login into Google Cloud, create a project and enable billing for it.

Install the gcloud command line utility and configure your project with gcloud init.

Set the default project, compute region and zone (replace PROJECT_ID with your own project):gcloud config set project PROJECT_IDgcloud config set compute/region us-central1gcloud config set compute/zone us-central1-aEnable the GKE service and create a cluster with the HPA and Istio add-ons:gcloud services enable container.

googleapis.

comK8S_VERSION=$(gcloud beta container get-server-config –format=json | jq -r '.

validMasterVersions[0]')gcloud beta container clusters create istio –cluster-version=${K8S_VERSION} –zone=us-central1-a –num-nodes=2 –machine-type=n1-standard-2 –disk-size=30 –enable-autorepair –no-enable-cloud-logging –no-enable-cloud-monitoring –addons=HorizontalPodAutoscaling,Istio –istio-config=auth=MTLS_PERMISSIVEThe above command will create a default node pool consisting of two n1-standard-2 (vCPU: 2, RAM 7.

5GB, DISK: 30GB) VMs.

Ideally you would want to isolate the Istio components from your workloads but there is no easy way of running the Istio pods on a dedicated node pool.

The Istio manifests are considered read-only and GKE will undo any modification like node affinity or pod anti-affinity.

Set up credentials for kubectl:gcloud container clusters get-credentials istioCreate a cluster admin role binding:kubectl create clusterrolebinding "cluster-admin-$(whoami)" –clusterrole=cluster-admin –user="$(gcloud config get-value core/account)"Install the Helm command-line tool:brew install kubernetes-helmHomebrew 2.

0 is now also available for Linux.

Create a service account and a cluster role binding for Tiller:kubectl -n kube-system create sa tiller && kubectl create clusterrolebinding tiller-cluster-rule –clusterrole=cluster-admin –serviceaccount=kube-system:tillerDeploy Tiller in the kube-system namespace:helm init –service-account tillerYou should consider using SSL between Helm and Tiller, for more information on securing your Helm installation see docs.

helm.

sh.

Validate your setup with:kubectl -n istio-system get svcIn a couple of seconds GCP should allocate an external IP to the istio-ingressgateway service.

Istio ingress gateway setupCreate a static IP address named istio-gateway using the Istio ingress IP:export GATEWAY_IP=$(kubectl -n istio-system get svc/istio-ingressgateway -ojson | jq -r .

status.

loadBalancer.

ingress[0].

ip)gcloud compute addresses create istio-gateway –addresses ${GATEWAY_IP} –region us-central1Next you’ll need an internet domain and access to your DNS registrar.

Add two A records (replace example.

com with your domain):istio.

example.

com A ${GATEWAY_IP}*.

istio.

example.

com A ${GATEWAY_IP}Verify that the wildcard DNS is working:watch host test.

istio.

example.

comCreate a generic Istio gateway to expose services outside the mesh on HTTP:apiVersion: networking.

istio.

io/v1alpha3kind: Gatewaymetadata: name: public-gateway namespace: istio-systemspec: selector: istio: ingressgateway servers: – port: number: 80 name: http protocol: HTTP hosts: – "*"Save the above resource as public-gateway.

yaml and then apply it:kubectl apply -f .

/public-gateway.

yamlNo production system should expose services on the internet without SSL.

To secure the Istio ingress gateway with cert-manager, CloudDNS and Let’s Encrypt please read Flagger GKE documentation.

Install FlaggerThe GKE Istio add-on does not include a Prometheus instance that scrapes the Istio telemetry service.

Because Flagger uses the Istio HTTP metrics to run the canary analysis you have to deploy the following Prometheus configuration that’s similar to the one that comes with the official Istio Helm chart.

REPO=https://raw.

githubusercontent.

com/stefanprodan/flagger/masterkubectl apply -f ${REPO}/artifacts/gke/istio-prometheus.

yamlAdd Flagger Helm repository:helm repo add flagger https://flagger.

appDeploy Flagger in the istio-system namespace with Slack notifications enabled:helm upgrade -i flagger flagger/flagger –namespace=istio-system –set metricsServer=http://prometheus.

istio-system:9090 –set slack.

url=https://hooks.

slack.

com/services/YOUR-WEBHOOK-ID –set slack.

channel=general –set slack.

user=flaggerYou can install Flagger in any namespace as long as it can talk to the Istio Prometheus service on port 9090.

Flagger comes with a Grafana dashboard made for canary analysis.

Install Grafana in the istio-system namespace:helm upgrade -i flagger-grafana flagger/grafana –namespace=istio-system –set url=http://prometheus.

istio-system:9090 –set user=admin –set password=change-meExpose Grafana through the public gateway by creating a virtual service (replace example.

com with your domain):apiVersion: networking.

istio.

io/v1alpha3kind: VirtualServicemetadata: name: grafana namespace: istio-systemspec: hosts: – "grafana.

istio.

example.

com" gateways: – public-gateway.

istio-system.

svc.

cluster.

local http: – route: – destination: host: flagger-grafanaSave the above resource as grafana-virtual-service.

yaml and then apply it:kubectl apply -f .

/grafana-virtual-service.

yamlNavigate to http://grafana.

istio.

example.

com in your browser and you should be redirected to Grafana’s login page.

Deploy web applications with FlaggerFlagger takes a Kubernetes deployment and optionally a horizontal pod autoscaler (HPA), then creates a series of objects (Kubernetes deployments, ClusterIP services and Istio virtual services).

These objects expose the application on the mesh and drive the canary analysis and promotion.

Create a test namespace with Istio sidecar injection enabled:REPO=https://raw.

githubusercontent.

com/stefanprodan/flagger/masterkubectl apply -f ${REPO}/artifacts/namespaces/test.

yamlCreate a deployment and a horizontal pod autoscaler:kubectl apply -f ${REPO}/artifacts/canaries/deployment.

yamlkubectl apply -f ${REPO}/artifacts/canaries/hpa.

yamlDeploy the load testing service to generate traffic during the canary analysis:helm upgrade -i flagger-loadtester flagger/loadtester –namepace=testCreate a canary custom resource (replace example.

com with your own domain):apiVersion: flagger.

app/v1alpha3kind: Canarymetadata: name: podinfo namespace: testspec: targetRef: apiVersion: apps/v1 kind: Deployment name: podinfo progressDeadlineSeconds: 60 autoscalerRef: apiVersion: autoscaling/v2beta1 kind: HorizontalPodAutoscaler name: podinfo service: port: 9898 gateways: – public-gateway.

istio-system.

svc.

cluster.

local hosts: – app.

istio.

example.

com canaryAnalysis: interval: 30s threshold: 10 maxWeight: 50 stepWeight: 5 metrics: – name: istio_requests_total threshold: 99 interval: 30s – name: istio_request_duration_seconds_bucket threshold: 500 interval: 30s webhooks: – name: load-test url: http://flagger-loadtester.

test/ timeout: 5s metadata: cmd: "hey -z 1m -q 10 -c 2 http://podinfo.

test:9898/"Save the above resource as podinfo-canary.

yaml and then apply it:kubectl apply -f .

/podinfo-canary.

yamlThe above analysis, if it succeeds, will run for five minutes while validating the HTTP metrics every half minute.

You can determine the minimum time that it takes to validate and promote a canary deployment using the formula: interval * (maxWeight / stepWeight).

The Canary CRD fields are documented here.

After a couple of seconds Flagger will create the canary objects:# applied deployment.

apps/podinfohorizontalpodautoscaler.

autoscaling/podinfocanary.

flagger.

app/podinfo# generated deployment.

apps/podinfo-primaryhorizontalpodautoscaler.

autoscaling/podinfo-primaryservice/podinfoservice/podinfo-canaryservice/podinfo-primaryvirtualservice.

networking.

istio.

io/podinfoOpen your browser and navigate to app.

istio.

example.

com, you should see the version number of the demo app.

Automated canary analysis and promotionFlagger implements a control loop that gradually shifts traffic to the canary while measuring key performance indicators like HTTP requests success rate, requests average duration and pod health.

Based on analysis of the KPIs a canary is promoted or aborted, and the analysis result is published to Slack.

A canary deployment is triggered by changes in any of the following objects:Deployment PodSpec (container image, command, ports, env, etc)ConfigMaps mounted as volumes or mapped to environment variablesSecrets mounted as volumes or mapped to environment variablesTrigger a canary deployment by updating the container image:kubectl -n test set image deployment/podinfo podinfod=quay.

io/stefanprodan/podinfo:1.

4.

1Flagger detects that the deployment revision changed and starts to analyse it:kubectl -n test describe canary/podinfoEvents:New revision detected podinfo.

testScaling up podinfo.

testWaiting for podinfo.

test rollout to finish: 0 of 1 updated replicas are availableAdvance podinfo.

test canary weight 5Advance podinfo.

test canary weight 10Advance podinfo.

test canary weight 15Advance podinfo.

test canary weight 20Advance podinfo.

test canary weight 25Advance podinfo.

test canary weight 30Advance podinfo.

test canary weight 35Advance podinfo.

test canary weight 40Advance podinfo.

test canary weight 45Advance podinfo.

test canary weight 50Copying podinfo.

test template spec to podinfo-primary.

testWaiting for podinfo-primary.

test rollout to finish: 1 of 2 updated replicas are availablePromotion completed!.Scaling down podinfo.

testDuring the analysis the canary’s progress can be monitored with Grafana:Note that if new changes are applied to the deployment during the canary analysis, Flagger will restart the analysis phase.

List all canaries in your cluster with:watch kubectl get canaries –all-namespacesNAMESPACE NAME STATUS WEIGHT LASTTRANSITIONTIMEtest podinfo Progressing 15 2019-01-16T14:05:07Zprod frontend Succeeded 0 2019-01-15T16:15:07Zprod backend Failed 0 2019-01-14T17:05:07ZIf you’ve enabled the Slack notifications, you should receive the following messages:Automated rollbackDuring the canary analysis it is possible to generate synthetic HTTP 500 errors and high response latency to test if Flagger pauses the rollout.

Create a tester pod and exec into it:kubectl -n test run tester –image=quay.

io/stefanprodan/podinfo:1.

2.

1 — .

/podinfo –port=9898kubectl -n test exec -it tester-xx-xx shGenerate HTTP 500 errors:watch curl http://podinfo-canary:9898/status/500Generate latency:watch curl http://podinfo-canary:9898/delay/1When the number of failed checks reaches the canary analysis threshold, the traffic is routed back to the primary, the canary is scaled to zero and the rollout is marked as failed.

The canary errors and latency spikes have been recorded as Kubernetes events and logged by Flagger in JSON format:kubectl -n istio-system logs deployment/flagger -f | jq .

msgStarting canary deployment for podinfo.

testAdvance podinfo.

test canary weight 5Advance podinfo.

test canary weight 10Advance podinfo.

test canary weight 15Halt podinfo.

test advancement success rate 69.

17% < 99%Halt podinfo.

test advancement success rate 61.

39% < 99%Halt podinfo.

test advancement success rate 55.

06% < 99%Halt podinfo.

test advancement success rate 47.

00% < 99%Halt podinfo.

test advancement success rate 37.

00% < 99%Halt podinfo.

test advancement request duration 1.

515s > 500msHalt podinfo.

test advancement request duration 1.

600s > 500msHalt podinfo.

test advancement request duration 1.

915s > 500msHalt podinfo.

test advancement request duration 2.

050s > 500msHalt podinfo.

test advancement request duration 2.

515s > 500msRolling back podinfo.

test failed checks threshold reached 10Canary failed!.Scaling down podinfo.

testIf you’ve enabled the Slack notifications, you’ll receive a message if the progress deadline is exceeded, or if the analysis reached the maximum number of failed checks:Wrapping upRunning a service mesh like Istio on top of Kubernetes gives you automatic metrics, logs, and traces but deployment of workloads still relies on external tooling.

Flagger aims to change that by extending Istio with progressive delivery capabilities.

Flagger is compatible with any CI/CD solutions made for Kubernetes, and the canary analysis can be easily extended with webhooks for running system integration/acceptance tests, load tests, or any other custom validation.

Since Flagger is declarative and reacts to Kubernetes events, it can be used in GitOps pipelines together with Weave Flux or JenkinsX.

If you’re using JenkinsX you can install Flagger using the jx addons.

Flagger is sponsored by Weaveworks and powers the canary deployments in Weave Cloud.

The project is being tested on GKE, EKS and bare metal clusters provisioned with kubeadm.

If you have any suggestion on improving Flagger please submit an issue or PR on GitHub at stefanprodan/flagger.

Contributions are more than welcome!.

. More details

Leave a Reply