<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gerd Koenig on Medium]]></title>
        <description><![CDATA[Stories by Gerd Koenig on Medium]]></description>
        <link>https://medium.com/@gerd-koenig?source=rss-3cfdef22ab87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j7RIP_fvtCVY25JO.jpeg</url>
            <title>Stories by Gerd Koenig on Medium</title>
            <link>https://medium.com/@gerd-koenig?source=rss-3cfdef22ab87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:29:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gerd-koenig/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tracing Kafka messages on K8s with Strimzi and Jaeger]]></title>
            <link>https://medium.com/geekculture/tracing-kafka-messages-on-k8s-with-strimzi-and-jaeger-5f2e737c69ea?source=rss-3cfdef22ab87------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f2e737c69ea</guid>
            <category><![CDATA[jaegertracing]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Gerd Koenig]]></dc:creator>
            <pubDate>Thu, 27 May 2021 14:07:56 GMT</pubDate>
            <atom:updated>2021-05-30T07:52:28.669Z</atom:updated>
            <content:encoded><![CDATA[<p>This post and moreover the <a href="https://github.com/gkoenig/strimzi-jaeger-eval">underlying GitHub repo</a>, provides a Hands-On style intro into highly requested topics in todays IT industry:</p><ul><li><a href="https://kafka.apache.org/">Kafka</a> : very popular stream messaging platform / data hub</li><li><a href="https://kubernetes.io/">Kubernetes</a> : container orchestration framework, or better: “operating system” for modern cloud native applications</li><li>Tracing : as part of Observability, based on <a href="https://opentelemetry.io/">OpenTelemetry framework</a> (emerged from OpenTracing and OpenCensus)</li></ul><p>What this post doesn’t provide, is an introduction into the concepts of the tools which are used, hence if you do not know what Kafka or Kubernetes is, please check out that documentation first (e.g. via the links above in the bullet list). It also doesn’t cover how to implement Kafka producers / consumers. <br>On the other hand, it will provide a quick “Walkthrough” style guide of <strong>how to glue the different pieces together to receive a running system</strong> and get you started…..from a system architecture / engineering point of view ;)</p><p><strong>! K</strong>udos to the Strimzi and Flux teams for their great documentation !!!!!</p><h3>Which tools / environments are we going to use ?</h3><p>The overall setup consists of</p><ul><li><strong>GKE</strong> : we will use Google Cloud Platform to setup a Kubernetes cluster, but any other way of starting a Kubernetes cluster will work as well. The Hands-On steps have no dependencies on any dedicated Kubernetes provider.</li><li>Kafka : we’ll setup Kafka on Kubernetes by using <a href="https://strimzi.io/"><strong>Strimzi</strong></a>. It provides a very elegant way (via Operators) to configure different components of the Kafka ecosystem within a Kubernetes cluster. Tracing support in Strimzi is provided by OpenTracing and Jaeger.</li><li><a href="https://www.jaegertracing.io/"><strong>Jaeger</strong></a> : popular tool(set) for collecting and visualizing distributed traces</li><li>optionally <a href="https://fluxcd.io/"><strong>Flux v2</strong></a> : GitOps tool to deply applications to Kubernetes by “git push”. Within the detailled instructions I’ll show two options to setup Kafka&amp;Topics. You can choose between the “manual” approach by applying yaml manifests through kubectl cli, or by using GitOps approach and let Flux observe a Git repo ….. and let it apply manifests/kustomize templates/helm charts from there. In my example it will be <a href="https://kustomize.io/">Kustomize</a>.</li><li>all code and detailed step-by-step instructions you’ll find in <a href="https://github.com/gkoenig/strimzi-jaeger-eval">this GitHub repo</a></li></ul><h3>What do we want to achieve ?</h3><p>To make this very short, we want to see traces from messages while they are flowing through Kafka topics, displayed in the Jaeger UI.</p><h3>How do we achieve that ?</h3><p>Not to repeat myself from the very detailled instructions in <a href="https://github.com/gkoenig/strimzi-jaeger-eval/blob/main/Readme.md">the Readme of the Git repo</a>, I’ll describe the main topics here. Hopefully it is not too confusing to switch between the Readme in GitHub and this post, but it doesn’t make sense to copy over the whole, long story here …</p><p><strong>launch K8s cluster on GCP</strong><br>- create a new project within GCP, called <em>strimzi-and-jaeger-eval</em><br>- <a href="https://cloud.google.com/sdk/docs/install#rpm">install <em>gcloud</em> cli</a><br>- execute :</p><pre>gcloud config configuration create strimzi-jaeger<br>gcloud config set project strimzi-and-jaeger-eval<br>gcloud auth login<br>gcloud container clusters create strimzi-jaeger-eval \<br> --num-nodes=2 \<br> --zone=europe-central2-a \<br> --machine-type=e2-standard-2</pre><p><strong>deploy the Strimzi operator in its own namespace “kafka-op”</strong><br>The instructions to configure and deploy the operator you’ll find <a href="https://github.com/gkoenig/strimzi-jaeger-eval#deploy-strimzi-operator">here</a>. At the end you should see the deployment of the operator up and running:</p><pre>#&gt;kubectl get deployments -n kafka-op<br>NAME                    READY UP-TO-DATE AVAILABLE AGE<br>strimzi-cluster-operator 1/1       1         1     51s</pre><p>To be very precise, we installed 3 Strimzi operators in total (see also overview picture below next chapter):<br>- <em>Cluster operator</em>: to manage Kafka cluster components from the Kafka ecosystem<br>- <em>Topic operator</em> : manages Kafka topics<br>- <em>Entity operator</em> : manages mainly users and their privileges</p><p><strong>Next, let’s setup a 3-node Kafka cluster with a single-node Zookeeper<br></strong>At the moment Zookeeper is still required, but the Kafka community already has a solution for upcoming versions where Zookeeper is removed, hence you do not longer have the dependecy from Kafka to Zookeeper anymore :D<br>Kafka will be reachable via port 9092 without authentication and encryption, as well as on port 9093 tls encrypted. Additionally we have an external facing listener on port 9094, which is created via a NodePort service.</p><p>To actually deploying the Kafka cluster I’ll provide two different approaches. One is applying the plain yaml manifests by executing <em>kubectl</em> commands, and the other approach is to use GitOps-tool Flux, so that Kafka specs are being applied to the K8s cluster as soon as you push them to Git.</p><p>Just pick one of them:<br>- <a href="https://github.com/gkoenig/strimzi-jaeger-eval/blob/main/Kafka-setup-manual.md">manual</a> <br>- <a href="https://github.com/gkoenig/strimzi-jaeger-eval/blob/main/Kafka-setup-GitOps.md">the GitOps way</a></p><p>Basically, what we have so far is, a Strimzi Cluster operator, which is observing the namespace “kafka-cluster” for Kafka components to be deployed. This means whenever later on you write manifest(s) for further components of the Kafka ecosystem, this operator kicks in. As long as you put them into the correct namespace (in our case “kafka-cluster”) ! This is a common source of confusion, if you e.g. deploy a Kafka-Connect resource into the default namespace and you are wondering why nothing is being created ;)</p><p><strong>Current setup overview</strong> (base picture taken from Strimzi documentation):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VDXCNd0yKt5lsXT4SBeHA.png" /></figure><p>To test the Kafka setup we can quickly start a producer and a consumer to send &amp; receive some messages. We will use the topic “my-first-topic”, which was part of the Kafka setup (independant from the option you’ve chosen, manual or GitOps)</p><p>Open a terminal and Start a Producer:</p><pre>kubectl run kafka-producer -ti \<br>--image=strimzi/kafka:latest-kafka-2.4.0 \<br>--rm=true — restart=Never \<br>--bin/kafka-console-producer.sh — broker-list strimzi-cluster-kafka-bootstrap.kafka-cluster:9092 — topic my-first-topic</pre><p>and in another terminal, start a Consumer:</p><pre>kubectl run kafka-consumer -ti \<br>--image=strimzi/kafka:latest-kafka-2.4.0 \<br>--rm=true — restart=Never \<br>--bin/kafka-console-consumer.sh — bootstrap-server strimzi-cluster-kafka-bootstrap.kafka-cluster:9092 — topic my-first-topic — from-beginning</pre><p>Now simply enter some text in the terminal where the producer is running, after pressing &lt;ENTER&gt; each line of text should appear in the consumer terminal</p><h3>For the tracing part, let’s setup Jaeger now</h3><p>Again, the detailled step-by-step instruction you’ll find in the <a href="https://github.com/gkoenig/strimzi-jaeger-eval#deploying-jager-core-components">Readme of the GitHub repo</a>.</p><p>For demo purposes it is sufficient that we use the Jaeger All-in-one bundle. This means all Jaeger components are within one binary. For real production use-cases you don’t want to go with that approach, and use a <a href="https://www.jaegertracing.io/docs/1.22/operator/#deployment-strategies">production strategy</a> instead.<br>Especially the storage backend you will want to change for real-world scenarios, the All-in-One bundle only comes with In-Memory storage and you cannot scale it beyond one replica.</p><p>Let’s open the Jaeger UI !</p><p>Since the Jaeger-UI (default port 16686) is not accessible from outside the K8s cluster in our setup, we simply forwarding local port 8080 to it via kubectl =&gt;</p><pre>kubectl port-forward service/my-jaeger-query 8080:16686</pre><p>Now you can access the Jaeger-UI by opening</p><pre>http://localhost:8080</pre><p>Here we are =&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcFK5Tys6hQ3IaDDpT8Spg.png" /></figure><p>Cool, so <strong>let’s create some Kafka messages including tracing information</strong>, so that we can display them in the Jaeger-UI.</p><p>To cover that, we’ll use a Java based scenario from the strimzi-examples, which consists of<br>- producer : produces Kafka messages, plain strings, to topic “my-topic”<br>- streams app : reads from topic “my-topic”, reverses the strings and stores them in topic “my-reversed-topic”<br>- consumer : reads the reversed strings’ topic</p><p>The apps are written in Java, and they use “interceptors” for the core Kafka producer/consumer classes, to create &amp; emit the traces to the Jaeger agent. Full step-by-step instruction again, is in the <a href="https://github.com/gkoenig/strimzi-jaeger-eval#first-tracing-in-action">GitHub repo</a> , again you can choose between manual setup and the GitOps way.</p><p>As an example here the config of the producer. The property JAEGER_AGENT_HOST needs to be set to the servicename of the Jaeger agent. The value for the JAEGER_SERVICE_NAME will appear within the Jaeger-UI to select certain services:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  labels:<br>    app: java-kafka-producer<br>  name: java-kafka-producer<br>  namespace: kafka-cluster<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: java-kafka-producer</pre><pre>template:<br>  metadata:<br>    labels:<br>      app: java-kafka-producer<br>  spec:<br>    containers:<br>    - name: java-kafka-producer<br>      image: quay.io/strimzi-examples/java-kafka-producer:latest<br>      env:<br>        - name: BOOTSTRAP_SERVERS<br>          value: strimzi-cluster-kafka-bootstrap.kafka-cluster:9092<br>        - name: TOPIC<br>          value: my-topic<br>        - name: DELAY_MS<br>          value: &quot;1000&quot;<br>        - name: LOG_LEVEL<br>          value: &quot;INFO&quot;<br>        - name: MESSAGE_COUNT<br>          value: &quot;1000000&quot;<br>        - name: JAEGER_SERVICE_NAME<br>          value: java-kafka-producer<br>        - name: JAEGER_AGENT_HOST<br>          value: my-jaeger-agent.default<br>        - name: JAEGER_SAMPLER_TYPE<br>          value: const<br>        - name: JAEGER_SAMPLER_PARAM<br>          value: &quot;1&quot;</pre><p>As soon as the producer+streams app+consumer are deployed, they will start producing messages and of course traces as well.</p><p>Now head back to the Jaeger-UI (http://localhost:8080), refresh the page and click on the dropdown box “Services” at the top left. Here you should see 3 additional services, one for each of our deployed apps, and the name should match the JAEGER_SERVICE_NAME properties of each of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uveDRi8ietK30yhWIPLSw.png" /></figure><p>Excellent !! this means our apps emitted traces to the Jaeger agent, then they got forwarded to the Jaeger collector and stored in the backend (only in-memory since we used the all-in-one jaeger bundle).</p><p>Pick your desired service and click on “Find Traces” button to display all the traces. From the list of results you can again click on one of the results to open the detailled view of that particular trace.</p><p>If you e.g. open the service “java-kafka-producer” and click on a trace, you’ll see something similar to =&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_52Zwq-crfWjss0v2_ITBw.png" /></figure><p>Here you can follow along the different stages of that kafka message. The producer produced it into topic “my-topic”, followed by 2 activities from the streams app, because it has to consume (from my-topic) and produce (to my-topic-reversed). At the end , the consumer reads from topic “my-topic-reversed”. You can see timings and additional information of each particular step if you click on your desired step from the chain.</p><p>If you made it up to this point, many thanks for your patience, it was a rather long one. Hopefully I was able to raise your interest in the topics of how to setup Kafka on Kubernetes and create traces within Kafka messages and I am more than happy if this kickstarts your journey into those areas.</p><p>Of course, there is always more than one way of deploying and configuring tools, but <strong>you somehow have to start</strong>. E.g. you can setup Strimzi via Helm chart as well, but I simply didn’t want to have Helm as additional tool for this demo, or if you are e.g. on AWS you can use X-Ray instead of Jaeger, instead of using Flux there are other tools as well providing GitOps style solutions, and so on and on.<br>Important for me (and this post) is the fact that you start working with it and thinking about how to apply it for your UseCases. If you replace one tool by another at the end, is less important. You have to digest the concepts first.</p><p>I will work on enhancing the setup by deploying additional tools of the Kafka ecosystem, mainly Kafka-Connect, within this setup, so stay tuned for upcoming news.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f2e737c69ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/tracing-kafka-messages-on-k8s-with-strimzi-and-jaeger-5f2e737c69ea">Tracing Kafka messages on K8s with Strimzi and Jaeger</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy AWS Lambda by Terraform]]></title>
            <link>https://gerd-koenig.medium.com/deploy-aws-lambda-by-terraform-38b6019d7c95?source=rss-3cfdef22ab87------2</link>
            <guid isPermaLink="false">https://medium.com/p/38b6019d7c95</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Gerd Koenig]]></dc:creator>
            <pubDate>Mon, 07 Oct 2019 17:54:19 GMT</pubDate>
            <atom:updated>2019-10-07T17:54:19.808Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the 2nd, and last, part of a small series about <br>=&gt; <a href="https://medium.com/@gerd_koenig/frequently-terminating-ec2-via-aws-lambda-6e2ce3f94304">writing a Lambda function which does kind of “chaos monkey”-termination of EC2 instances behind a classic ELB ( Part I )</a><br>=&gt; deploying the lambda function and creating all necessary AWS resources via Terraform</p><p>This post focusses on the deployment of the lambda function and the creation of the AWS resources to get it into place.</p><p><strong>Now</strong> that we have the lambda function implemented (<a href="https://medium.com/@gerd_koenig/frequently-terminating-ec2-via-aws-lambda-6e2ce3f94304">see Part I</a>), it is time to figure out what is needed to publish it to AWS, hence which additional resources are required.</p><p>The terraform documentation is your best friend, it is very well written and with lots of examples.</p><p>Since we are dealing with AWS cloud, it is obvious that we need the<strong> </strong><a href="https://www.terraform.io/docs/providers/aws/index.html"><strong>AWS provider</strong></a><strong> of Terraform</strong>.</p><p><strong>Permissions<br></strong>To be able to access ELB, ASG, EC2 and Cloudwatch I defined the proper policies for the lambda function, as show below.<br>To limit the possibility to terminate EC2 instances I injected a filter to restrict to the current user’s account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/852004e40b9cdfbcd40f015023f323ec/href">https://medium.com/media/852004e40b9cdfbcd40f015023f323ec/href</a></iframe><p>With that policy in place, next step is to create a role and attach the policy to that role, and finally the lambda function assumes this role on execution time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1552b752f572872078e83a9fc77982b1/href">https://medium.com/media/1552b752f572872078e83a9fc77982b1/href</a></iframe><p>The creation of the lambda function resource itself is quite straighforward. For deployment you need a .zip archive of the lambda implementation itself, then add the previously created role and the environment parameters for the lambda function. Most importantly this is our name of the loadbalancer which shall be considered for terminating EC2 instances which are targets of it.</p><p>For the archive we create a terraform data source of type zip, then we use it as parameter within the lambda function resource</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dae92fe711e94c3d75b4963c308250c4/href">https://medium.com/media/dae92fe711e94c3d75b4963c308250c4/href</a></iframe><p><strong>Scheduling</strong><br>Now let’s have a look at the final “challenge”….how to schedule the lambda function ?</p><p>I wanted to have a cron-like schedule to be as flexible as possible, and lambda offers that as well. In Terraform we need 3 resources for that</p><ul><li>an <em>aws_cloudwatch_event_rule</em> : responsible for triggering per our specification</li><li>an <em>aws_cloudwatch_event_target</em> : which connects the event rule to our lambda function arn</li><li>an <em>aws_lambda_permission</em> : to allow the event rule to invoke our lambda function</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7130b56f313f896e63d05a4f5675abf0/href">https://medium.com/media/7130b56f313f896e63d05a4f5675abf0/href</a></iframe><p>The final scheduling definition is provided in file variables.tf , in variable named <em>lambda_schedule . </em>I wanted to have it being triggered hourly, between 8–17h (UTC) on weekdays (mon-fri), which results in the following setting</p><pre>variable “lambda_schedule” {<br> description = “cron(Minutes Hours Day-of-month Month Day-of-week Year), default: hourly on week days 8–15h UTC”<br> default=”cron(0 8–17 ? * MON-FRI *)” <br>}</pre><p><strong>Deplooooy</strong><br>After having specified all our resources, we are good to go and deploy :D</p><pre>terraform init #just once initially to fetch the aws provider</pre><pre>terraform validate # do a syntax check</pre><pre>terraform plan # check whats going to be created/modified/destroyed</pre><pre>terraform apply</pre><p>There are 2 options to provide the required parameter for the loadbalancer name “lb_name”. Either you put it into the variables.tf and run terraform as show before, or you specify it on the commandline at terraform execution time.</p><p>For the latter, just execute</p><pre>terraform plan -var lb_name=&lt;your-loadbalancer-name&gt;<br>terraform apply -var lb_name=&lt;your-loadbalancer-name&gt;</pre><p>Voila:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPfAYD-f0D5dRDIoIFK9yg.png" /></figure><p>The whole setup and deployment you can <a href="https://github.com/gkoenig/lambda-ec2-terminator">find on GitHub</a></p><p>Have fun playing with AWS Lambda and Terraform, hope you enjoyed reading !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38b6019d7c95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frequently terminating EC2 via AWS Lambda]]></title>
            <link>https://gerd-koenig.medium.com/frequently-terminating-ec2-via-aws-lambda-6e2ce3f94304?source=rss-3cfdef22ab87------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e2ce3f94304</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Gerd Koenig]]></dc:creator>
            <pubDate>Mon, 07 Oct 2019 17:05:47 GMT</pubDate>
            <atom:updated>2019-10-07T17:55:44.167Z</atom:updated>
            <content:encoded><![CDATA[<p>In todays distributed, highly-available systems we see often times chaos-monkey style tooling to randomly kill/stop services/processes/nodes to ensure the overall systems stability and resilience.</p><p>For the impatient, here the <a href="https://github.com/gkoenig/lambda-ec2-terminator">github repo</a> :D</p><p>This is a 2-part post, where this first part considers the Lambda function itself and the environment. The <a href="https://medium.com/@gerd_koenig/deploy-aws-lambda-by-terraform-38b6019d7c95">second part</a> focusses on <a href="https://medium.com/@gerd_koenig/deploy-aws-lambda-by-terraform-38b6019d7c95">deploying the lambda function to AWS by using Terraform</a>, according to Infrastructure-As-Code.<br>This small series doesn’t focus on explaining the basics of AWS Lambda or Terraform, but more on actually how to use it.</p><p>For starters, here some good intros:<br>* <a href="https://aws.amazon.com/lambda/">AWS Lambda</a> : run your code without dealing with underlying resources (“serverless”). AWS takes care of the required infrastructure to execute your function<br>* <a href="https://www.terraform.io/">Terraform</a> : declarative way to provision infrastructure, on various providers (AWS, GCloud, Vagrant, …)</p><p><strong>Environment</strong><br>Recently I had to implement some “kind of chaos monkey” for an AWS environment consisting of:</p><ul><li>AWS (classic) Loadbalancer</li><li>3 ASGs (Autoscaling groups), configured as targets of the Loadbalancer</li><li>a bunch of EC2 instances in each ASG</li></ul><p>The EC2 instances include a user_data section, from where at initial launch an application is getting set up.</p><p><strong>Requirement(s)</strong><br>To prove resilience, I wanted to frequently terminate the “oldest running” EC2 instance which is part of an ASG behind a classic ELB, but <strong>just if all desired number of instances from the autoscaling-groups are “in service”</strong>. This just as a safety measure, not to terminate instances if others are out-of-service as well.</p><p><strong>How?</strong><br>Since I didn’t want to launch an additional EC2 just to run a cronjob for terminating other instances, I went for <strong>AWS Lambda</strong> , which is a perfect fit to cover my needs. I decided to go with Python as runtime, since I am most comfortable compared to the other runtimes.<br>To keep the usage as simple as possible, I only want to provide the <strong>name of the loadbalancer as input</strong> to the lambda function. The function shall determine which EC2 is going to be terminated at the end.<br>In addition to that, and since I am highly addicted to <strong>Infrastructure-As-Code</strong>, I wanted to have the deployment in declarative way, and automated….via <strong>Terraform</strong> (but, as already mentioned, is content of Part II of this blog series)</p><p><strong>The Lambda function</strong><br>The first kind of challenge was to dive into the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">Boto3 doc</a>, to figure out the ways to gather information from the different AWS resources I need. Very well documented and self-explanatory it quickly turned out to structure like the following:</p><ul><li>calculating the sum of desired number of instances from all the involved ASGs was not that straightforward as I initially thought. <br>1. I had to fiddle through all ASGs<br>2. filtering the ones which are assigned to the loadbalancer, then <br>3. sum up the desired count of EC2 instances.<br>The loadbalancer which should be considered, is given as parameter to this function</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27d346bf61373a018a99af82b29aace0/href">https://medium.com/media/27d346bf61373a018a99af82b29aace0/href</a></iframe><ul><li>as entry point for the Lambda execution, there is the <strong>function lambda_handler</strong> , where the EC2 instance is being discovered, which will be terminated at the end.<br>The function<br>- checks parameter <em>DRY_RUN</em>, to determine if the command to terminate shall be executed really, or just simulated<br>- loops over the EC2 instances which are behind the loadbalancer as per the provided parameter “<em>LB_NAME</em>”<br>- checks if the EC2 instance status is “<em>InService</em>”, then determines the oldest EC2 instance based on their “<em>launch_time</em>”<br>- if enough healthy instances are available, the oldest EC2 instance will be terminated</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb119ad1b9bc0dbf7e1ff1b71c434e38/href">https://medium.com/media/eb119ad1b9bc0dbf7e1ff1b71c434e38/href</a></iframe><p>The full implementation of the lambda function is shown below (which can be used to paste into the AWS Lambda management console and triggered for testing purposes)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4e934926918dd6ebf91d37c3b219e41/href">https://medium.com/media/e4e934926918dd6ebf91d37c3b219e41/href</a></iframe><p>To test the function you can simply use AWS Lambda console, providing the parameter manually and click button “Test” to trigger the execution.</p><p>All the log outputs (<em>print</em> statements) are being transferred to CloudWatch. You can have a look by navigating to Cloudwatch console and open the related <strong>CloudWatch LogGroup</strong>, by default <strong>/aws/lambda/ec-terminator</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5XUkigvD79wZQIXcqKDgg.png" /></figure><p>This was part one of the story. Next step is to use Terraform to deploy our lambda function to AWS, since we want to apply Infrastructure-As-Code best practices ;)</p><p>How this is implemented outlines <a href="https://medium.com/@gerd_koenig/deploy-aws-lambda-by-terraform-38b6019d7c95">part II of this series</a>.</p><p>Have fun playing around with Lambda and Terraform. Hope you enjoyed reading !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e2ce3f94304" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>