<?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 Bora Köstem on Medium]]></title>
        <description><![CDATA[Stories by Bora Köstem on Medium]]></description>
        <link>https://medium.com/@fenari.kostem?source=rss-b00cda164c1e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Fn8QVDSs2KqlAX_p1QPxLg@2x.jpeg</url>
            <title>Stories by Bora Köstem on Medium</title>
            <link>https://medium.com/@fenari.kostem?source=rss-b00cda164c1e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:13:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fenari.kostem/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[AWS Lens V1: A Terraform-First Desktop Workspace for AWS Operators]]></title>
            <link>https://medium.com/@fenari.kostem/aws-lens-v1-a-terraform-first-desktop-workspace-for-aws-operators-d056977cdafa?source=rss-b00cda164c1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d056977cdafa</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Bora Köstem]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 18:41:49 GMT</pubDate>
            <atom:updated>2026-03-31T18:41:49.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vX1WUbhEo4reJOA6_0CeZQ.png" /></figure><p>Most AWS tools are either too broad or too fragmented for day-to-day infrastructure work. You jump between the Terraform CLI, cloud consoles, state files, drift checks, credential switching, and a terminal full of one-off commands. Nothing is technically impossible, but the workflow is noisy, brittle, and easy to get wrong.</p><p>That is the problem AWS Lens V1 is designed to solve.</p><p>AWS Lens is a desktop operator workspace built with Electron, React, and TypeScript, but the important part is not the stack. The important part is the operating model: Terraform is treated as a first-class control surface, not as a side feature hidden behind a generic AWS dashboard.</p><p>This first version focuses on giving Terraform-heavy AWS teams a tighter loop between planning, applying, reviewing drift, handling state safely, and keeping the active AWS context visible at all times.</p><h3>Why focus on Terraform first</h3><p>Terraform is usually where intent lives, but not where operations end.</p><p>In real environments, teams still need to answer questions like:</p><ul><li>Which workspace is active right now?</li><li>Which inputs are being applied?</li><li>Is this plan safe, destructive, or replacement-heavy?</li><li>Has the real AWS environment drifted away from state?</li><li>Are governance checks clean enough to allow apply?</li><li>If a refactor goes wrong, what is the safest way to handle state mv, state rm, or force-unlock?</li></ul><p>Most teams answer those questions by stitching together multiple tools and personal habits. AWS Lens V1 turns that into one workflow.</p><h3>What ships in AWS Lens V1 for Terraform teams</h3><h3>1. Workspace-aware Terraform project management</h3><p>AWS Lens can discover and track Terraform projects locally, keep project metadata per AWS profile, and expose workspace operations directly in the UI.</p><p>That includes:</p><ul><li>workspace detection via Terraform CLI, with a filesystem fallback when needed</li><li>create, switch, and delete workspace flows</li><li>environment metadata persisted for fast context recovery</li><li>Git metadata such as branch, commit, dirty status, and changed Terraform files</li></ul><p>This matters because Terraform mistakes are often context mistakes. Running the right command in the wrong workspace is still the wrong command.</p><h3>2. Input layering and secret-aware runtime configuration</h3><p>V1 includes a structured input model instead of treating variables as an afterthought.</p><p>Operators can work with:</p><ul><li>named variable sets</li><li>base values plus environment-specific overlays</li><li>inline editing and validation</li><li>sensitive value masking</li><li>values pulled from AWS Secrets Manager and SSM Parameter Store</li><li>temporary runtime input file generation for operations that need it</li></ul><p>The goal is simple: make the active Terraform context inspectable before execution, not after damage control starts.</p><h3>3. Plan visualization beyond a raw CLI dump</h3><p>AWS Lens V1 supports multiple plan modes:</p><ul><li>standard plan</li><li>refresh-only plan</li><li>targeted plan</li><li>replace plan</li></ul><p>Instead of leaving the output as a wall of text, the app parses plan artifacts into grouped change summaries, action counts, replacement signals, delete-heavy warnings, and per-resource change cards.</p><p>That makes reviews faster, especially when a plan is technically valid but operationally risky.</p><p>For teams that rely on review discipline, this is one of the most important V1 capabilities: the plan becomes something you can inspect structurally, not just scroll through.</p><h3>4. Governance checks that can block bad applies</h3><p>Terraform formatting and validation are table stakes. V1 goes further by detecting and running a small governance toolkit around the project:</p><ul><li>terraform fmt</li><li>terraform validate</li><li>tflint</li><li>tfsec</li><li>checkov</li></ul><p>Required checks and optional checks are separated clearly. Findings are normalized into a shared report model with severity, file location, raw output, and blocking status.</p><p>Most importantly, AWS Lens can block apply and destroy when required governance checks fail.</p><p>That changes the product from a passive dashboard into an active safety layer.</p><h3>5. Drift reconciliation against live AWS</h3><p>One of the strongest parts of AWS Lens V1 is that drift is not treated as a vague warning.</p><p>The app compares Terraform-managed inventory against live AWS resources for supported types such as EC2, security groups, VPCs, subnets, route tables, internet gateways, NAT gateways, network interfaces, S3 buckets, Lambda, RDS, ECR, and EKS.</p><p>Each item is classified with statuses like:</p><ul><li>in_sync</li><li>drifted</li><li>missing_in_aws</li><li>unmanaged_in_aws</li><li>unsupported</li></ul><p>The app also distinguishes between verified results and inferred signals. That distinction matters. A lot of internal tools blur confidence levels and make operators overtrust the output. AWS Lens V1 explicitly shows where it has direct verification and where it is only giving heuristics.</p><p>Snapshot history is also stored locally, so drift can be tracked over time instead of treated as a one-off scan.</p><h3>6. A guided State Operations Center</h3><p>State work is where infrastructure tooling usually becomes the least forgiving.</p><p>AWS Lens V1 adds a dedicated State Operations Center for:</p><ul><li>terraform import</li><li>terraform state mv</li><li>terraform state rm</li><li>terraform force-unlock</li></ul><p>These flows are wrapped with practical safeguards:</p><ul><li>typed confirmation for destructive actions</li><li>local backup creation before risky state operations</li><li>state source inspection</li><li>lock metadata inspection when available</li><li>plan artifact invalidation after state-changing operations</li><li>drift cache invalidation after relevant commands</li></ul><p>This is not trying to replace Terraform’s authority. It is trying to make state operations less error-prone for humans.</p><h3>7. Run history and auditability</h3><p>Every important Terraform command should leave a readable trail.</p><p>AWS Lens V1 records command history with timestamps, redacted arguments, execution results, duration, workspace context, and follow-up state details where relevant. Combined with local backup retention and drift snapshots, this creates a much better operational memory than “someone probably ran it in a terminal yesterday.”</p><h3>Why a desktop app instead of another web tool</h3><p>This project is intentionally local-first.</p><p>AWS Lens is not trying to become a hosted control plane. It uses secure local persistence, keeps app-managed credentials in an encrypted local vault, stores temporary assume-role sessions in memory, and preserves the operator’s active AWS context across the UI and embedded terminal.</p><p>That local model is a feature, not a limitation.</p><p>Terraform execution, workspace files, state inspection, and terminal-driven recovery are all already local workflows for many teams. V1 accepts that reality and builds around it instead of pretending every serious infrastructure action needs a browser tab and a backend service.</p><h3>What I wanted V1 to feel like</h3><p>The bar for V1 was not “support every Terraform edge case.”</p><p>The bar was:</p><ul><li>make the active context obvious</li><li>make plans readable</li><li>make drift review practical</li><li>make state operations safer</li><li>make governance visible before execution</li><li>keep Terraform and AWS context in one place</li></ul><p>If the product does those things reliably, it earns the right to expand.</p><h3>What comes next</h3><p>AWS Lens V1 is the foundation, not the final shape.</p><p>There is still plenty to improve across provider coverage, deeper plan intelligence, richer remediation workflows, and broader cross-service operational views. But the core idea is now concrete: Terraform deserves an operator workspace that understands the difference between configuration, live cloud state, governance posture, and execution risk.</p><p>That is what AWS Lens V1 starts to deliver.</p><p>If you spend a meaningful part of your day moving between terraform plan, terraform apply, state cleanup, drift investigation, and AWS console checks, this is the workflow I wanted to compress into one product.</p><p>V1 is the first version of that answer.</p><p>Repo: <a href="https://github.com/BoraKostem/AWS-Lens">https://github.com/BoraKostem/AWS-Lens</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d056977cdafa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Monitored My Flask App With Elastic APM]]></title>
            <link>https://medium.com/@fenari.kostem/how-i-monitored-my-flask-app-with-elastic-apm-7d17ef9bda37?source=rss-b00cda164c1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d17ef9bda37</guid>
            <category><![CDATA[elastic]]></category>
            <category><![CDATA[kibana]]></category>
            <category><![CDATA[elastic-apm]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Bora Köstem]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 21:01:56 GMT</pubDate>
            <atom:updated>2025-01-27T21:01:56.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*84HdgNXdjk-U5UMl.png" /></figure><p>Monitoring is an essential part of application development, as it provides insights into an application&#39;s performance, behavior, and issues in real-time. Identifying bottlenecks or diagnosing problems in production environments can become daunting without proper monitoring. This is where Elastic APM (Application Performance Monitoring) comes into play.</p><p>Elastic APM, a part of the Elastic Stack, is a powerful tool for monitoring applications, collecting performance metrics, and visualizing data. It allows developers to track transactions, measure latencies, and capture errors with ease. By integrating Elastic APM into your application, you can comprehensively understand its runtime behavior.</p><p>In this article, I’ll walk you through how I integrated Elastic APM with my Flask application. From setting up Elastic APM using Docker Compose to enriching application data with geo-location and user-agent details. Finally, I’ll demonstrate how to create custom dashboards in Kibana to visualize this data effectively.</p><p>Let’s get started!</p><h3>Setting Up Elastic APM With Docker Compose</h3><p>To begin monitoring your Flask app, you need to set up the Elastic Stack components required for Elastic APM. This section covers the setup process using Docker Compose to create an APM server, Elasticsearch for data storage, and Kibana for data visualization.</p><h4>Docker Compose Configuration</h4><pre>version: &#39;2.2&#39;<br>services:<br>  apm-server:<br>    image: docker.elastic.co/apm/apm-server:7.17.26<br>    depends_on:<br>      elasticsearch:<br>        condition: service_healthy<br>      kibana:<br>        condition: service_healthy<br>    cap_add: [&quot;CHOWN&quot;, &quot;DAC_OVERRIDE&quot;, &quot;SETGID&quot;, &quot;SETUID&quot;]<br>    cap_drop: [&quot;ALL&quot;]<br>    ports:<br>    - 8200:8200<br>    networks:<br>    - elastic<br>    command: &gt;<br>       apm-server -e<br>         -E apm-server.rum.enabled=true<br>         -E setup.kibana.host=kibana:5601<br>         -E output.elasticsearch.username=elastic<br>         -E output.elasticsearch.password=12345678<br>         -E setup.template.settings.index.number_of_replicas=0<br>         -E apm-server.kibana.enabled=true<br>         -E apm-server.kibana.host=kibana:5601<br>         -E apm-server.kibana.username=elastic<br>         -E apm-server.kibana.password=12345678<br>         -E output.elasticsearch.hosts=[&quot;elasticsearch:9200&quot;]<br><br>  elasticsearch:<br>    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.26<br>    environment:<br>    - bootstrap.memory_lock=true<br>    - cluster.name=docker-cluster<br>    - ELASTIC_PASSWORD=12345678<br>    - xpack.security.enabled=true<br>    - xpack.security.authc.api_key.enabled=true<br>    - cluster.routing.allocation.disk.threshold_enabled=false<br>    - discovery.type=single-node<br>    - ES_JAVA_OPTS=-XX:UseAVX=2 -Xms1g -Xmx1g<br>    ulimits:<br>      memlock:<br>        hard: -1<br>        soft: -1<br>    volumes:<br>    - esdata:/usr/share/elasticsearch/data<br>    ports:<br>    - 9200:9200<br>    networks:<br>    - elastic<br><br>  kibana:<br>    image: docker.elastic.co/kibana/kibana:7.17.26<br>    environment:<br>      ELASTICSEARCH_URL: http://elasticsearch:9200<br>      ELASTICSEARCH_HOSTS: http://elasticsearch:9200<br>      ELASTICSEARCH_USERNAME: elastic<br>      ELASTICSEARCH_PASSWORD: 12345678<br>    ports:<br>    - 5601:5601<br>    networks:<br>    - elastic<br><br>volumes:<br>  esdata:<br>    driver: local<br><br>networks:<br>  elastic:<br>    driver: bridge</pre><h4>Starting the Elastic Stack</h4><p>To start the Elastic Stack:</p><ol><li>Save the docker-compose.yml file in a directory of your choice.</li><li>Open a terminal, navigate to the directory, and run:</li></ol><pre>docker-compose up -d</pre><p>This will pull the necessary images, create the containers, and start the services in the background.</p><p><strong>Access Kibana:</strong> Open your browser and navigate to http://localhost:5601. Log in using the default credentials:</p><ul><li>Username: elastic</li><li>Password: 12345678</li></ul><p><strong>Test the APM server:</strong> Visit http://localhost:8200 to confirm the APM server is accessible.</p><h3>Integrating Elastic APM with Flask</h3><p>Now that Elastic APM is set up and running, the next step is to integrate it with your Flask application. This involves adding the Elastic APM client to your Flask app, capturing application transactions, and enriching the data with custom labels for better observability.</p><h4>Step 1: Install Required Dependencies</h4><p>To use Elastic APM in a Flask app, install the following Python packages:</p><pre>pip install elastic-apm[flask] geoip2 user-agents</pre><ul><li>elastic-apm[flask]: The official Elastic APM client for Flask integration.</li><li>geoip2: For extracting geo-location data based on client IP. (You need to download MaxMind’s DB)</li><li>user-agents: For parsing user-agent strings to extract device and OS details.</li></ul><h4>Step 2: Initialize Flask and Elastic APM</h4><pre>app = Flask(__name__)<br><br># Initialize Elastic APM Client<br>apm = Client(<br>    service_name=&#39;my-flask-app&#39;,  # Unique identifier for the service<br>    server_url=&#39;http://localhost:8200&#39;,  # URL of the APM server<br>    capture_body=&#39;all&#39;,  # Capture body of requests<br>    environment=&#39;development&#39;  # Application environment (e.g., development, production)<br>)<br># Optional: Log a custom message when the server starts<br>apm.capture_message(&#39;Server Start!&#39;)</pre><ul><li><strong>service_name</strong>: Identifies your application in the Elastic APM UI.</li><li><strong>server_url</strong>: The URL where the APM server is running.</li><li><strong>capture_body</strong>: Specifies whether request/response bodies should be captured.</li><li><strong>environment</strong>: Helps categorize services by environment (e.g., staging, production).</li><li><strong>capture_message</strong>: Logs a custom message in the APM server.</li></ul><h4>Step 3: Enrich Transactions with Labels</h4><p>The following middleware hooks (before_request and after_request) capture and enrich transaction data.</p><pre>@app.before_request<br>def start_transaction():<br>    apm.begin_transaction(&#39;request&#39;)  # Start a new transaction named &#39;request&#39;<br><br>    client_ip = request.remote_addr  # Get client IP address<br>    user_agent_string = request.headers.get(&#39;User-Agent&#39;, &#39;&#39;)  # Fetch User-Agent header<br>    user_agent = user_agents.parse(user_agent_string)  # Parse user-agent<br>    # Extract Geo-location from IP<br>    try:<br>        response = reader.city(client_ip)  # Query GeoIP database<br>        lat = response.location.latitude<br>        lon = response.location.longitude<br>        country = response.country.iso_code<br>        city = response.city.name<br>    except Exception:<br>        lat, lon = 0.0, 0.0  # Default to Null Island if GeoIP fails<br>        country, city = &quot;Null Island&quot;, &quot;None&quot;<br><br>    # Add custom labels to the APM transaction<br>    elasticapm.label(<br>        location=f&quot;{lat},{lon}&quot;,  # Geo-coordinates as a label<br>        location_country=country,<br>        location_city=city,<br>        client_ip=client_ip,<br>        user_os=user_agent.os.family  # Extract OS name from user-agent<br>    )</pre><ul><li>apm.begin_transaction(&#39;request&#39;): Starts a new APM transaction with the name &#39;request&#39;.</li><li>elasticapm.label: Adds custom labels to the transaction for better categorization. In this case:</li><li>location: Latitude and longitude of the client.</li><li>client_ip: The client&#39;s IP address.</li><li>user_os: The operating system detected from the user-agent.</li></ul><h4>Step 4: End Transactions and Log Response</h4><pre>@app.after_request<br>def end_transaction(response):<br>    apm.end_transaction(response.status_code)  # End the transaction with the response status code<br>    return response</pre><ul><li><strong>apm.end_transaction(response.status_code)</strong>: Ends the current transaction and associates it with the HTTP status code of the response.</li></ul><h4>Step 5: Capturing Errors</h4><p>Elastic APM automatically captures uncaught exceptions, but you can also explicitly log errors and exceptions:</p><pre>@app.errorhandler(404)<br>def page_not_found(e):<br>    elasticapm.set_transaction_name(&#39;404&#39;)  # Name the transaction as &#39;404&#39;<br>    apm.capture_message(f&#39;404 error: {request.url} not found&#39;)  # Log the error<br>    return &#39;This page does not exist&#39;, 404<br><br>@app.errorhandler(500)<br>def internal_server_error(e):<br>    elasticapm.set_transaction_name(&#39;500&#39;)  # Name the transaction as &#39;500&#39;<br>    apm.capture_exception()  # Capture the full exception stack trace<br>    return &#39;An internal server error occurred&#39;, 500</pre><ul><li><strong>elasticapm.set_transaction_name()</strong>: Sets a specific name for the transaction.</li><li><strong>apm.capture_message()</strong>: Logs a specific error message to Elastic APM.</li><li><strong>apm.capture_exception()</strong>: Captures the stack trace and logs the exception for debugging.</li></ul><h4>Full Code</h4><pre>import elasticapm.context<br>from flask import Flask, request<br>from elasticapm.contrib.flask import ElasticAPM<br>import elasticapm<br>from elasticapm import Client<br>import user_agents<br><br>import geoip2.database # For IP lookup<br>app = Flask(__name__)<br><br>apm = Client(service_name=&#39;my-flask-app&#39;, server_url=&#39;http://localhost:8200&#39;, capture_body=&#39;all&#39;, environment=&#39;development&#39;)<br>apm.capture_message(&#39;Server Start!&#39;)<br><br><br>reader = geoip2.database.Reader(&#39;./GeoLite2-City.mmdb&#39;) #This is the MaxMind&#39;s DB that you downloaded<br><br>@app.before_request<br>def start_transaction():<br>    apm.begin_transaction(&#39;request&#39;)<br>    client_ip = request.remote_addr<br><br>    user_agent_string = request.headers.get(&#39;User-Agent&#39;, &#39;&#39;)<br>    user_agent = user_agents.parse(user_agent_string)<br>    try:<br>        response = reader.city(client_ip)<br>        lat = response.location.latitude<br>        lon = response.location.longitude<br>        country = response.country.iso_code<br>        city = response.city.name<br>    except Exception:<br>        lat = 0.0<br>        lon = 0.0<br>        country = &quot;Null Island&quot;<br>        city = &quot;None&quot;<br><br>    elasticapm.label(<br>        location=f&quot;{lat},{lon}&quot;,     # or just store lat/lon separately<br>        location_country=country,<br>        location_city=city<br>    )<br><br>    user_os = user_agent.os.family  # Extract OS name<br>    elasticapm.label(client_ip=client_ip, user_os=user_os)<br><br>@app.after_request<br>def end_transaction(response):<br>    apm.end_transaction(response.status_code)<br>    return response<br><br>@app.errorhandler(404)<br>def page_not_found(e):<br>    url = request.url<br>    elasticapm.set_transaction_name(&#39;404&#39;)<br>    apm.capture_message(f&#39;404 error: {url} not found&#39;)<br>    return &#39;This page does not exist&#39;, 404<br><br>@app.errorhandler(500)<br>def internal_server_error(e):<br>    elasticapm.set_transaction_name(&#39;500&#39;)<br>    apm.capture_exception()<br>    return &#39;An internal server error occurred&#39;, 500<br><br>@app.errorhandler(405)<br>def method_not_allowed(e):<br>    elasticapm.set_transaction_name(&#39;405&#39;)<br>    apm.capture_message(&#39;Method not allowed&#39;)<br>    elasticapm.set_custom_context({<br>        &#39;request&#39;: {<br>            &#39;url&#39;: request.url,<br>            &#39;method&#39;: request.method<br>        }<br>    })<br>    return &#39;Method not allowed&#39;, 405<br><br>@app.route(&#39;/&#39;)<br>def home():<br>    elasticapm.set_transaction_name(&#39;home&#39;)<br>    try:<br>        return &#39;Hello, World!&#39;<br>    except Exception:<br>        apm.capture_exception()<br><br>@app.route(&#39;/zerodivision&#39;)<br>def zero():<br>    elasticapm.set_transaction_name(&#39;zero-division&#39;)<br>    try:<br>        1 / 0<br>    except Exception:<br>        apm.capture_exception()<br>        return &#39;An error occurred&#39;, 500<br><br>@app.route(&#39;/post-test&#39;, methods=[&#39;POST&#39;])<br>def post_test():<br>    elasticapm.set_transaction_name(&#39;post-test&#39;)<br>    try:<br>        return &#39;Post request received&#39;<br>    except Exception:<br>        apm.capture_exception()<br><br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFkPDXp66tHy2RtJwNdaTQ.png" /><figcaption>my-flask-app should be visible inside Observability -&gt; APM -&gt; Services</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drUCWwXcy8Fp9qOSeR-JZQ.png" /><figcaption>Inside the my-flask-app</figcaption></figure><h3>Building a Pipeline to Convert Flask Location to Geo-location</h3><p>To visualize geo-location data in Kibana, we need to convert the labels.location field, captured by Elastic APM, into a geo_point field that Elasticsearch can use for geographic visualizations. This can be achieved by creating an <strong>Ingest Pipeline</strong> in Elasticsearch.</p><h4>What is an Ingest Pipeline?</h4><p>An <strong>Ingest Pipeline</strong> in Elasticsearch processes and transforms incoming data before it is indexed. It consists of a sequence of <strong>processors</strong> that manipulate or enrich the data. In this case, we will parse the labels.location field, which contains latitude and longitude as a string, and transform it into a geo_point field.</p><h4>Pipeline Definition</h4><p>The following pipeline, named convert_lat_lon, converts the labels.location field into a geo_point field named client.geo.location.</p><pre>{<br>  &quot;description&quot;: &quot;Parse labels.location into a geo_point field&quot;,<br>  &quot;processors&quot;: [<br>    {<br>      &quot;grok&quot;: {<br>        &quot;field&quot;: &quot;labels.location&quot;,<br>        &quot;patterns&quot;: [<br>          &quot;%{NUMBER:lat},%{NUMBER:lon}&quot;<br>        ],<br>        &quot;ignore_missing&quot;: true<br>      }<br>    },<br>    {<br>      &quot;convert&quot;: {<br>        &quot;field&quot;: &quot;lat&quot;,<br>        &quot;type&quot;: &quot;float&quot;,<br>        &quot;ignore_missing&quot;: true<br>      }<br>    },<br>    {<br>      &quot;convert&quot;: {<br>        &quot;field&quot;: &quot;lon&quot;,<br>        &quot;type&quot;: &quot;float&quot;,<br>        &quot;ignore_missing&quot;: true<br>      }<br>    },<br>    {<br>      &quot;set&quot;: {<br>        &quot;field&quot;: &quot;client.geo.location&quot;,<br>        &quot;value&quot;: &quot;{{lat}},{{lon}}&quot;,<br>        &quot;override&quot;: true,<br>        &quot;ignore_empty_value&quot;: true<br>      }<br>    }<br>  ]<br>}</pre><p>To create this pipeline you can use DevTools in Kibana:</p><pre>PUT _ingest/pipeline/convert_lat_lon<br>{<br>  &quot;description&quot;: &quot;Parse labels.location (e.g. &#39;40.7128,-74.0060&#39;) into a geo_point field&quot;,<br>  &quot;processors&quot;: [<br>    {<br>      &quot;grok&quot;: {<br>        &quot;field&quot;: &quot;labels.location&quot;,<br>        &quot;patterns&quot;: [<br>          &quot;%{NUMBER:lat},%{NUMBER:lon}&quot;<br>        ],<br>        &quot;ignore_missing&quot;: true<br>      }<br>    },<br>    {<br>      &quot;convert&quot;: {<br>        &quot;field&quot;: &quot;lat&quot;,<br>        &quot;type&quot;: &quot;float&quot;,<br>        &quot;ignore_missing&quot;: true<br>      }<br>    },<br>    {<br>      &quot;convert&quot;: {<br>        &quot;field&quot;: &quot;lon&quot;,<br>        &quot;type&quot;: &quot;float&quot;,<br>        &quot;ignore_missing&quot;: true<br>      }<br>    },<br>    {<br>      &quot;set&quot;: {<br>        &quot;field&quot;: &quot;client.geo.location&quot;,<br>        &quot;value&quot;: &quot;{{lat}},{{lon}}&quot;,<br>        &quot;override&quot;: true,<br>        &quot;ignore_empty_value&quot;: true<br>      }<br>    }<br>  ]<br>}</pre><p>Click <strong>Run</strong> to create the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Vl8orl-_OEmC5IRSFkOnA.png" /></figure><h4>Modifying the APM Pipeline to Use the convert_lat_lon Pipeline Using Kibana UI</h4><p>To ensure your convert_lat_lon pipeline is used within the default APM pipeline, you can edit the default pipeline and replace the existing geo-location logic with your custom pipeline. Follow these steps using Kibana’s user interface:</p><p>To modify the APM pipeline in Kibana to include your convert_lat_lon pipeline, navigate to <strong>Stack Management</strong> &gt; <strong>Ingest Pipelines</strong>, and search for the apm pipeline. Edit the processors section to include the following JSON structure, ensuring that your convert_lat_lon pipeline is added after the relevant processors:</p><pre>[<br>  {<br>    &quot;pipeline&quot;: {<br>      &quot;name&quot;: &quot;apm_ingest_timestamp&quot;<br>    }<br>  },<br>  {<br>    &quot;pipeline&quot;: {<br>      &quot;name&quot;: &quot;apm_user_agent&quot;<br>    }<br>  },<br>  {<br>    &quot;pipeline&quot;: {<br>      &quot;name&quot;: &quot;convert_lat_lon&quot;<br>    }<br>  },<br>  {<br>    &quot;pipeline&quot;: {<br>      &quot;name&quot;: &quot;apm_remove_span_metadata&quot;<br>    }<br>  },<br>  {<br>    &quot;pipeline&quot;: {<br>      &quot;if&quot;: &quot;ctx.processor?.event == &#39;error&#39;&quot;,<br>      &quot;name&quot;: &quot;apm_error_grouping_name&quot;<br>    }<br>  },<br>  {<br>    &quot;pipeline&quot;: {<br>      &quot;if&quot;: &quot;ctx.processor?.event == &#39;metric&#39;&quot;,<br>      &quot;name&quot;: &quot;apm_metrics_dynamic_template&quot;<br>    }<br>  }<br>]</pre><p>Save the updated pipeline and verify it by testing sample data in <strong>Dev Tools</strong> to ensure labels.location is correctly processed into client.geo.location.</p><h3>Creating a Custom Dashboard in Kibana</h3><p>Custom dashboards in Kibana allow you to visualize and explore your application’s data collected through Elastic APM. Here’s how you can create a custom dashboard to monitor metrics such as user locations, response times, error rates, and OS distributions.</p><h4>Step 1: Navigate to the Dashboard App</h4><ol><li>Open Kibana (http://localhost:5601) and log in.</li><li>Go to <strong>Dashboard</strong> from the left-hand menu.</li></ol><h4>Step 2: Create a New Dashboard</h4><ol><li>Click the <strong>Create Dashboard</strong> button.</li><li>Optionally, name your dashboard.</li></ol><h4>Step 3: Add Visualizations</h4><p>Click <strong>Create Visualization</strong> to add visualizations based on the APM data. Below are some examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vigAdvOHfEHrTq0JVJP7Yg.png" /><figcaption>OS Usage Dashboard By Percentage</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNQQsqpO1JttZW8nFjXimA.png" /><figcaption>Transaction Response Time Averages by milliseconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWnejs0pwOrNq7NHZwbKlw.png" /><figcaption>World Map with User Locations (green dots)</figcaption></figure><h4>Step 4: Customize the Dashboard Layout</h4><ul><li>Drag and resize visualizations to organize them effectively.</li><li>Use grid alignment to ensure a clean and readable layout.</li></ul><h4>Step 5: Save and Share</h4><ol><li>Click <strong>Save</strong> to store the dashboard.</li><li>Optionally, share the dashboard with your team by clicking <strong>Share</strong> and generating a public or private link.</li></ol><h3>Conclusion</h3><p>In this guide, we explored the process of monitoring a Flask application using Elastic APM, from setting up the Elastic Stack with Docker Compose to integrating Elastic APM into the Flask app. We also demonstrated how to enrich APM data with geo-location and user agent details, convert this data into geo_point fields using a custom ingest pipeline, and visualize it effectively in Kibana through custom dashboards.</p><p>By implementing Elastic APM, you can gain valuable insights into your application’s performance, user behavior, and error trends. The ability to monitor metrics like response times, errors, and user distribution in real-time empowers developers to proactively address issues and optimize their applications. Elastic Stack’s flexibility makes it a powerful tool for building observability pipelines tailored to your specific use case.</p><p>With this setup, you have a fully operational monitoring system for your Flask app, providing both technical metrics and business insights. Whether you’re managing a small project or scaling to handle millions of users, this integration ensures your app remains robust and reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d17ef9bda37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securely Publish Your Web Apps with Cloudflare and HAProxy Load Balancer]]></title>
            <link>https://medium.com/@fenari.kostem/securely-publish-your-web-apps-with-cloudflare-and-haproxy-load-balancer-d73cbb25ea96?source=rss-b00cda164c1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d73cbb25ea96</guid>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[haproxy]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[cloudflare]]></category>
            <dc:creator><![CDATA[Bora Köstem]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 15:26:29 GMT</pubDate>
            <atom:updated>2024-12-07T15:26:29.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jYb1w-RNrmI77hUi.png" /></figure><p>Publishing web applications securely is a critical step in today’s online landscape, where threats like data breaches and malicious attacks are ever-present. While creating a robust application is essential, ensuring its safe delivery to users is just as important. This is where tools like Cloudflare and HAProxy come into play.</p><p><a href="https://www.cloudflare.com/">Cloudflare </a>is a powerful shield, offering advanced DNS management, content delivery, and SSL encryption. On the other hand, HAProxy excels as a reliable load balancer, efficiently routing traffic to your applications while exposing only the ports you need. Together, they form a robust solution to publish web apps securely, providing both performance and protection.</p><p>In this article, I will walk you through my journey of setting up a secure web app publication pipeline. We’ll start with configuring Cloudflare for domain and SSL management, move to generating origin server certificates, and finally configure HAProxy to terminate SSL and load balance traffic. By the end, you’ll have a setup that ensures your applications are served over HTTPS, with only port 443 exposed to the outside world.</p><p>Whether you’re securing a personal project or deploying production-grade applications, this guide provides the foundational steps to safeguard your web apps with confidence. Let’s get started!</p><h3>Setting Up Cloudflare</h3><h4>Step 1: Create a Cloudflare Account and Add Your Domain</h4><p>Start by creating an account on <a href="https://www.cloudflare.com/">Cloudflare</a> if you don’t already have one. Once logged in, add your domain by clicking the <strong>“Add a domain”</strong> button. This step ensures Cloudflare begins managing your domain’s DNS records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nq45bdfcfmx3kgEJgoxsNg.png" /></figure><h4>Step 2: Review and Configure DNS Settings</h4><p>After adding your domain, you’ll be taken to the <strong>DNS Records</strong> page. Here, Cloudflare will automatically import your existing records. Review these entries and ensure they are correct. You can also add, edit, or delete records as needed.</p><p>For optimal protection, ensure the critical record proxy status is set to <strong>“Proxied”</strong> (denoted by the orange cloud icon). This routes traffic through Cloudflare for enhanced security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAW0Rh7ndoV6kC4kk-TJqQ.png" /></figure><h4>Step 3: Configure SSL/TLS Encryption</h4><p>Navigate to the <strong>SSL/TLS</strong> section in the Cloudflare dashboard and set the encryption mode to <strong>“Full (strict)”</strong>. This ensures end-to-end encryption, both between your visitors and Cloudflare and between Cloudflare and your origin server.</p><ol><li>Click the <strong>“Configure”</strong> button to set the encryption mode.</li><li>Select <strong>“Full (strict)”</strong> and save the settings.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVt5YPqV5rkGgkgxZU4XHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHIAYfeeudBfQQzNMAE5ug.png" /></figure><h4>Step 4: Generate an Origin Server Certificate</h4><p>To securely encrypt traffic between Cloudflare and your origin server, you need to generate an SSL certificate.</p><ol><li>Go to the <strong>Origin Server</strong> section under SSL/TLS.</li><li>Click <strong>“Create Certificate”</strong> and follow the instructions to generate a certificate.</li><li>Download the certificate and private key files.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0cMgQcqubysZbemFwGQqg.png" /></figure><p>With Cloudflare configured and your certificates downloaded, you’re now ready to prepare the SSL files for your HAProxy load balancer. In the next section, we’ll combine these files and configure HAProxy to securely route traffic to your applications.</p><h3>Preparing SSL Certificates for HAProxy</h3><p>Once you have downloaded the SSL certificate and private key files from Cloudflare, the next step is to prepare them for use in your HAProxy configuration. HAProxy requires these two files to be combined into a single .pem file for SSL termination.</p><h4>Combining the Certificate and Private Key</h4><p>To create the .pem file, use the cat command to combine the certificate and private key files into one:</p><pre>cat your_certificate.pem your_private_key.pem &gt; combined.pem</pre><p>This command merges the certificate (your_certificate.pem) and private key (your_private_key.pem) into a new file called combined.pem. Ensure that the certificate file comes first, followed by the private key, as HAProxy expects this order.</p><h3>Installing and Configuring HAProxy</h3><p>After preparing your SSL certificates, the next step is to install and configure HAProxy as your load balancer. HAProxy will handle incoming HTTPS requests, terminate SSL, and route traffic to the appropriate backend servers based on the requested hostname.</p><h4>Step 1: Install HAProxy</h4><p>Install HAProxy on your server using your package manager. For example:</p><ul><li><strong>Ubuntu/Debian</strong>:</li></ul><pre>sudo apt update &amp;&amp; sudo apt install haproxy -y</pre><ul><li><strong>CentOS/RHEL</strong>:</li></ul><pre>sudo yum install haproxy -y</pre><p>After installation, verify the version to ensure it’s installed correctly:</p><pre>haproxy -v</pre><h4>Step 2: Configure HAProxy</h4><p>Edit the HAProxy configuration file, typically located at /etc/haproxy/haproxy.cfg. Replace the default configuration with the following example configuration tailored for routing traffic based on hostname.</p><pre>global<br>    log /dev/log local0<br>    log /dev/log local1 notice<br>    maxconn 2000<br>    tune.bufsize 32768<br>    daemon<br><br>defaults<br>    mode tcp<br>    log global<br>    option tcplog<br>    option dontlognull<br>    retries 5<br>    timeout client 10m<br>    timeout server 10m<br>    timeout http-request 10m<br>    timeout check 15s<br><br>frontend https_front<br>    bind *:443 ssl crt /etc/haproxy/certs/combined.pem alpn h2,http/1.1<br>    mode http<br>    option httplog<br>    http-request set-header Host %[hdr(host)]<br>    http-request set-header X-Real-IP %[src]<br>    http-request set-header X-Forwarded-For %[src]<br>    http-request set-header X-Forwarded-Proto https<br><br>    acl host_your_adress1 hdr(host) -i your_adress1.kostem.net<br>    acl host_your_adress2 hdr(host) -i your_adress2.kostem.net<br>    acl host_your_adress3 hdr(host) -i your_adress3.kostem.net<br>    acl host_www_kostem hdr(host) -i www.kostem.net<br><br>    use_backend your_adress1_backend if host_your_adress1<br>    use_backend your_adress2_backend if host_your_adress2<br>    use_backend your_adress3_backend if host_your_adress3<br>    use_backend www_kostem_backend if host_www_kostem<br><br>backend your_adress1_backend<br>    mode http<br>    balance roundrobin<br>    server server1 192.168.2.0:80 check<br><br>backend your_adress2_backend<br>    mode http<br>    balance roundrobin<br>    server server2 192.168.2.1:80 check<br><br>backend your_adress3_backend<br>    mode http<br>    balance roundrobin<br>    server server3 192.168.2.2:80 check<br><br>backend www_kostem_backend<br>    mode http<br>    balance roundrobin<br>    server www_server 192.168.2.3:80 check</pre><h4>Key Features of the Configuration:</h4><h4><strong>Global Section:</strong></h4><ul><li>Sets logging and buffer size parameters.</li><li>Enables daemon mode for background operation.</li></ul><p><strong>Defaults Section</strong>:</p><ul><li>Configures TCP logging and connection timeouts.</li></ul><p><strong>Frontend Section</strong>:</p><ul><li>Binds to port 443 with SSL termination using the combined certificate (combined.pem).</li><li>Adds headers for forwarded requests to pass client information.</li><li>Uses Access Control Lists (ACLs) to match incoming requests based on the Host header.</li><li>Routes requests to appropriate backends using the use_backend directive.</li></ul><p><strong>Backend Sections</strong>:</p><ul><li>Defines each backend server group with a load-balancing strategy (roundrobin).</li><li>Health checks are enabled (check) to ensure servers are available.</li></ul><h4>Step 3: Place the SSL Certificate</h4><p>Move your combined SSL certificate (combined.pem) to the directory specified in the configuration:</p><pre>sudo mkdir -p /etc/haproxy/certs<br>sudo mv combined.pem /etc/haproxy/certs/combined.pem<br>sudo chmod 600 /etc/haproxy/certs/combined.pem</pre><h4>Step 4: Test and Restart HAProxy</h4><p>Check the configuration for errors:</p><pre>haproxy -f /etc/haproxy/haproxy.cfg -c</pre><p>If there are no errors, restart HAProxy to apply the changes:</p><pre>sudo systemctl restart haproxy<br>sudo systemctl enable haproxy</pre><h4>Step 5: Verify the Setup</h4><ul><li>Use curl to test the SSL termination and routing:</li></ul><pre>curl -I https://your_adress1.kostem.net</pre><h3>Conclusion</h3><p>In this guide, we started by setting up Cloudflare, adding a domain, and configuring SSL/TLS encryption with strict settings to ensure end-to-end security. We then generated and prepared SSL certificates to integrate seamlessly with HAProxy. Finally, we configured HAProxy to terminate SSL and route traffic based on hostname, ensuring your applications are accessible via HTTPS on port 443 only.</p><p>This journey not only secures your web apps but also enhances their performance by leveraging Cloudflare’s proxy services and HAProxy’s efficient routing capabilities. With this setup, you’ve taken a significant step toward building a secure and scalable infrastructure for your projects.</p><p>Remember, security is an ongoing process. Regularly update your certificates, monitor your traffic, and explore advanced features of Cloudflare and HAProxy to further enhance your setup. With these tools, you can confidently deliver your web apps to users while keeping them safe from potential threats.</p><p>Feel free to share your feedback or ask questions — I’d love to hear about your experiences in implementing this setup!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d73cbb25ea96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortless Kubernetes Deployment: Setting Up a Cluster with Ansible and kubeadm]]></title>
            <link>https://medium.com/@fenari.kostem/effortless-kubernetes-deployment-setting-up-a-cluster-with-ansible-and-kubeadm-cc40f9e716f4?source=rss-b00cda164c1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc40f9e716f4</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[kubeadm]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Bora Köstem]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 20:56:43 GMT</pubDate>
            <atom:updated>2024-11-08T07:42:10.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AHHTlZ9B4y-Yzrn7.png" /></figure><p>Creating a Kubernetes cluster from scratch can seem like a daunting task, especially for those new to orchestration or infrastructure automation. However, by combining the power of Ansible for streamlined configuration management with kubeadm’s ease in setting up Kubernetes, you can quickly build a robust and scalable cluster. In this guide, we’ll walk through the process of creating a Kubernetes cluster using Ansible and kubeadm, breaking down each step to simplify the setup. By the end, you’ll have a flexible, automated deployment method that can be adapted for various environments, empowering you to handle real-world Kubernetes deployments with confidence.</p><h3>Kubeadm Config File</h3><p>We’ll save this configuration file as kubeadm-conf.j2, a Jinja2 template, to take advantage of Ansible’s variable substitution capabilities. The kubeadm configuration file provided here defines key settings for initializing and configuring a Kubernetes cluster. It includes two main configurations: InitConfiguration, ClusterConfiguration</p><pre>apiVersion: kubeadm.k8s.io/v1beta3<br>kind: InitConfiguration<br>nodeRegistration:<br>  criSocket: &quot;unix:///var/run/cri-dockerd.sock&quot;  # Set CRI socket to cri-dockerd<br>localAPIEndpoint:<br>  advertiseAddress: &quot;{{ ansible_host }}&quot;  # Host IP for the Kubernetes API<br>  bindPort: 6443<br><br>---<br>apiVersion: kubeadm.k8s.io/v1beta3<br>kind: ClusterConfiguration<br>networking:<br>  podSubnet: &quot;10.244.0.0/16&quot;  # This is the Pod CIDR for Flannel<br>  serviceSubnet: &quot;10.96.0.0/12&quot;<br>kubernetesVersion: &quot;v1.30.0&quot;<br>controlPlaneEndpoint: &quot;{{ ansible_host }}:6443&quot;  # Control plane endpoint (host IP)<br></pre><ul><li><strong>InitConfiguration</strong>: This section sets up the node registration parameters and API endpoint. The criSocket is defined as &quot;unix:///var/run/cri-dockerd.sock&quot;, specifying the container runtime interface (CRI) socket used by cri-dockerd for Docker compatibility. The localAPIEndpoint includes the advertiseAddress, which uses the host&#39;s IP ({{ ansible_host }}) for the Kubernetes API, and bindPort, set to 6443, which is the default port for Kubernetes API communication.</li><li><strong>ClusterConfiguration</strong>: This segment configures the broader cluster settings. The networking subsection defines podSubnet as &quot;10.244.0.0/16&quot;, which is the CIDR range for Pods, tailored for use with the Flannel CNI (Container Network Interface). The serviceSubnet is set to &quot;10.96.0.0/12&quot;, defining the IP range for Kubernetes Services. The kubernetesVersion specifies the Kubernetes version as &quot;v1.30.0&quot;. Additionally, controlPlaneEndpoint is set to {{ ansible_host }}:6443, making the host IP the endpoint for the control plane.</li></ul><p>Together, these configurations enable a consistent, repeatable setup of a Kubernetes control plane, providing the essential network, control plane, and node configurations needed for a stable cluster. Using Ansible to dynamically inject the ansible_host variable allows flexibility in deployment across different hosts.</p><h3>Inventory</h3><p>The inventory.ini file specifies the infrastructure layout for Ansible to manage our Kubernetes cluster setup. It includes two groups: Worker and Master.</p><ul><li>The Worker group contains the IP address designating it as a node that will run application workloads.</li><li>The Master group identifies the control plane node responsible for managing the Kubernetes cluster.</li><li>The [all:vars] section sets common variables across all hosts, defining ansible_ssh_user as ubuntu, which is the default SSH user for these instances, and ansible_ssh_private_key_file as ./aws_key.pem, the private key used for secure SSH access. This file provides Ansible with the necessary host details and access credentials to automate the configuration of both master and worker nodes within the cluster.</li></ul><pre>[Worker]<br>34.219.90.197<br><br>[Master]<br>18.236.242.163<br><br>[all:vars]<br>ansible_ssh_user=ubuntu<br>ansible_ssh_private_key_file=./aws_key.pem</pre><h3>Initialization</h3><p>The setup_docker_kubernetes.yaml playbook automates the installation of Docker, CRI-Dockerd, and Kubernetes packages on all target hosts, ensuring that each node is configured for Kubernetes readiness.</p><pre># setup_docker_kubernetes.yaml<br>---<br>- name: Install Docker, CRI-Dockerd, and Kubernetes packages<br>  hosts: all<br>  become: true<br>  vars:<br>    link: &quot;https://github.com/Mirantis/cri-dockerd/releases/download/v0.3.15/cri-dockerd_0.3.15.3-0.ubuntu-jammy_amd64.deb&quot;<br>  tasks:<br>    - name: Update APT package index<br>      apt:<br>        update_cache: true<br><br>    - name: Install required packages<br>      apt:<br>        name:<br>          - apt-transport-https<br>          - ca-certificates<br>          - curl<br>        state: present<br><br>    - name: Create directory for APT keyrings<br>      file:<br>        path: /etc/apt/keyrings<br>        state: directory<br>        mode: &#39;0755&#39;<br><br>    - name: Download Docker&#39;s official GPG key<br>      command: curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc<br>      changed_when: false<br><br>    - name: Add Docker repository to APT sources<br>      command: &gt;<br>        sh -c &#39;echo &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable&quot; &gt; /etc/apt/sources.list.d/docker.list&#39;<br>      changed_when: false<br><br>    - name: Update APT package index again<br>      apt:<br>        update_cache: true<br><br>    - name: Install Docker packages<br>      apt:<br>        name:<br>          - docker-ce<br>          - docker-ce-cli<br>          - containerd.io<br>          - docker-buildx-plugin<br>          - docker-compose-plugin<br>        state: present<br><br>    - name: Download CRI-Dockerd package<br>      get_url:<br>        url: &quot;{{ link }}&quot;<br>        dest: /tmp/cri-dockerd.deb<br><br>    - name: Install CRI-Dockerd package<br>      command: dpkg -i /tmp/cri-dockerd.deb<br>      changed_when: false<br><br>    - name: Download Kubernetes GPG key<br>      get_url:<br>        url: https://pkgs.k8s.io/core:/stable:/v1.30/deb/Release.key<br>        dest: /tmp/kubernetes-apt-keyring.gpg<br><br>    - name: Save Kubernetes GPG key<br>      command: gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg /tmp/kubernetes-apt-keyring.gpg<br>      changed_when: false<br><br>    - name: Add Kubernetes repository to APT sources<br>      copy:<br>        content: |<br>          deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.30/deb/ /<br>        dest: /etc/apt/sources.list.d/kubernetes.list<br>        mode: &#39;0644&#39;<br><br>    - name: Update APT package index for Kubernetes<br>      apt:<br>        update_cache: true<br><br>    - name: Install Kubernetes packages<br>      apt:<br>        name:<br>          - kubelet<br>          - kubeadm<br>          - kubectl<br>        state: present<br><br>    - name: Hold Kubernetes packages<br>      command: apt-mark hold kubelet kubeadm kubectl<br>      changed_when: false<br><br>    - name: Disable swap<br>      command: sudo swapoff -a<br>      changed_when: false<br><br>    - name: Comment out swap in /etc/fstab<br>      command: sudo sed -i &#39;/ swap / s/^\(.*\)$/#\1/g&#39; /etc/fstab<br>      changed_when: false<br><br>    - name: Load overlay kernel module<br>      command: sudo modprobe overlay<br>      changed_when: false<br><br>    - name: Load br_netfilter kernel module<br>      command: sudo modprobe br_netfilter<br>      changed_when: false<br><br>    - name: Configure sysctl for Kubernetes<br>      copy:<br>        content: |<br>          net.bridge.bridge-nf-call-iptables  = 1<br>          net.bridge.bridge-nf-call-ip6tables = 1<br>          net.ipv4.ip_forward                 = 1<br>        dest: /etc/sysctl.d/k8s.conf<br>        mode: &#39;0644&#39;<br><br>    - name: Apply sysctl settings<br>      command: sudo sysctl --system<br>      changed_when: false</pre><ol><li><strong>Update APT and Install Required Packages</strong>: The playbook starts by updating the APT package index and installing necessary packages, such as apt-transport-https, ca-certificates, and curl.</li><li><strong>Add Docker Repository</strong>: It sets up Docker’s official GPG key and adds Docker’s repository to APT sources, ensuring secure and verified package installations.</li><li><strong>Install Docker and CRI-Dockerd</strong>: Docker packages (e.g., docker-ce, containerd.io) are installed, and the CRI-Dockerd package, downloaded using a URL variable, is set up to allow Docker to act as the Kubernetes container runtime.</li><li><strong>Add Kubernetes Repository</strong>: The Kubernetes repository is added after downloading and saving its GPG key, allowing the installation of the latest Kubernetes packages.</li><li><strong>Install and Hold Kubernetes Packages</strong>: Essential Kubernetes packages (kubelet, kubeadm, and kubectl) are installed and marked on hold to prevent unintended upgrades.</li><li><strong>Disable Swap and Configure System for Kubernetes</strong>: Swap is disabled for Kubernetes compatibility, and entries in /etc/fstab are commented out to make this change permanent. Required kernel modules (overlay and br_netfilter) are loaded, and sysctl configurations are applied to enable IP forwarding and bridge traffic, essential for Kubernetes networking.</li></ol><p>This playbook sets up each host with Docker and Kubernetes prerequisites, ensuring consistency across the environment for a reliable Kubernetes cluster deployment.</p><h3>Control Plane Setup</h3><p>The kubernetes_cluster_setup.yaml playbook handles the initialization of the Kubernetes control plane on the master node</p><pre># kubernetes_cluster_setup.yaml<br>---<br>- name: Initialize Kubernetes Cluster<br>  hosts: Master<br>  become: true<br>  vars:<br>    local_kubeadmin_config: &quot;./kubeadm-conf.j2&quot;<br>    remote_kubeadmin_config: &quot;/home/{{ ansible_user }}/kubeadm-conf.yaml&quot;<br>  tasks:<br>    - name: Copy kubeadmin-config.yaml to remote machine<br>      template:<br>        src: &quot;{{ local_kubeadmin_config }}&quot;<br>        dest: &quot;{{ remote_kubeadmin_config }}&quot;<br>        owner: &quot;{{ ansible_user }}&quot;<br>        mode: &#39;0644&#39;<br><br>    - name: Ensure kubelet is enabled and started<br>      systemd:<br>        name: kubelet<br>        enabled: yes<br>        state: started<br><br>    - name: Initialize Kubernetes cluster<br>      command: kubeadm init --config {{ remote_kubeadmin_config }} --ignore-preflight-errors=NumCPU,Mem<br>      args:<br>        creates: /etc/kubernetes/admin.conf<br>      register: kubeadm_init<br>      changed_when: kubeadm_init.rc == 0<br><br>    - name: Create .kube directory<br>      file:<br>        path: /home/{{ ansible_user }}/.kube<br>        state: directory<br>        mode: &#39;0755&#39;<br>        owner: &quot;{{ ansible_user }}&quot;<br><br>    - name: Copy Kubernetes admin.conf to user&#39;s home directory<br>      copy:<br>        src: /etc/kubernetes/admin.conf<br>        dest: /home/{{ ansible_user }}/.kube/config<br>        owner: &quot;{{ ansible_user }}&quot;<br>        mode: &#39;0644&#39;<br><br>    - name: Change ownership of admin.conf<br>      file:<br>        path: /home/{{ ansible_user }}/.kube/config<br>        owner: &quot;{{ ansible_user }}&quot;<br>        group: &quot;{{ ansible_user }}&quot;<br>        mode: &#39;0644&#39;<br><br>    - name: Install Flannel CNI<br>      command: kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml<br>      changed_when: false</pre><ol><li><strong>Copy kubeadm Configuration</strong>: The playbook copies the kubeadm-conf.j2 configuration template to the remote master node, saving it as kubeadm-conf.yaml. This configuration file contains all necessary parameters for initializing the cluster.</li><li><strong>Start and Enable Kubelet</strong>: The kubelet service, essential for Kubernetes operations, is enabled and started to ensure it runs as part of the system&#39;s startup processes.</li><li><strong>Initialize Kubernetes Cluster</strong>: The kubeadm init command is executed with the copied configuration file, kubeadm-conf.yaml. The --ignore-preflight-errors=NumCPU,Mem flag bypasses CPU and memory checks, allowing initialization to proceed even on low-resource setups. This command sets up the control plane and generates essential cluster configuration files.</li><li><strong>Configure kubectl for the User</strong>: After initialization, the playbook creates a .kube directory in the user’s home directory and copies the admin.conf file, which allows the user to execute kubectl commands from their local environment. File permissions and ownership are adjusted for secure access.</li><li><strong>Install Flannel CNI</strong>: Finally, the Flannel CNI (Container Network Interface) is applied by downloading and applying its YAML configuration. This CNI is required for Kubernetes networking and allows Pods to communicate across the cluster.</li></ol><p>This setup ensures that the control plane node is fully initialized, networked, and ready for worker nodes to join, forming the foundation of the Kubernetes cluster.</p><h3>Add Worker Node</h3><p>The add_worker_node.yaml playbook allows worker nodes to join the Kubernetes cluster by retrieving a join command from the master node and executing it on each worker node.</p><pre># add_worker_node.yaml<br>---<br>- name: Get join command from master<br>  hosts: Master<br>  become: true<br>  tasks:<br>    - name: Get kubeadm join command<br>      command: kubeadm token create --print-join-command<br>      register: join_command<br><br>- name: Join worker nodes to the cluster<br>  hosts: Worker<br>  become: true<br>  tasks:<br>    - name: Execute join command<br>      command: &quot;{{ hostvars[groups[&#39;Master&#39;][0]].join_command.stdout }} --cri-socket /var/run/cri-dockerd.sock  --ignore-preflight-errors=NumCPU,Mem&quot;<br><br>    - name: Label the node<br>      command: kubectl label node {{ inventory_hostname }} node-role.kubernetes.io/worker=worker<br>      delegate_to: Master</pre><p><strong>Retrieve Join Command from Master</strong>:</p><ul><li>The first play runs on the Master node, where it generates the kubeadm join command using kubeadm token create --print-join-command. This command, stored in the join_command variable, includes the necessary token and CA hash required for secure communication between nodes.</li></ul><p><strong>Execute Join Command on Worker Nodes</strong>:</p><ul><li>The second play runs on Worker nodes, where each node executes the join command obtained from the master. The --cri-socket /var/run/cri-dockerd.sock parameter specifies the container runtime interface, and --ignore-preflight-errors=NumCPU,Mem allows nodes with fewer resources to join the cluster.</li></ul><p><strong>Label the Worker Node</strong>:</p><ul><li>After joining, each worker node is labeled with node-role.kubernetes.io/worker=worker, marking its role within the cluster. This command is executed on the Master node using delegate_to to apply the label centrally.</li></ul><p>This playbook automates the process of adding worker nodes to the cluster, making them available for running application workloads and distributing the load in the Kubernetes environment.</p><h3>Main.yaml</h3><p>The main.yaml playbook serves as the primary orchestrator, sequentially running the necessary playbooks to set up and configure the entire Kubernetes cluster. It imports three key playbooks:</p><pre># main.yaml<br>---<br>- name: Setup Docker and Kubernetes<br>  import_playbook: setup-docker-kuber.yaml<br><br>- name: Initialize Kubernetes Cluster<br>  import_playbook: kubernetes_cluster_setup.yaml<br><br>- name: Add Worker Nodes to Kubernetes Cluster<br>  import_playbook: add_worker_node.yaml</pre><p><strong>Setup Docker and Kubernetes</strong>:</p><ul><li>This section imports setup-docker-kuber.yaml, which installs Docker, CRI-Dockerd, and essential Kubernetes packages, ensuring each node is prepared for Kubernetes.</li></ul><p><strong>Initialize Kubernetes Cluster</strong>:</p><ul><li>The next playbook, kubernetes_cluster_setup.yaml, initializes the control plane on the master node, setting up the cluster&#39;s core components and networking.</li></ul><p><strong>Add Worker Nodes to Kubernetes Cluster</strong>:</p><ul><li>Finally, add_worker_node.yaml is imported to join the worker nodes to the cluster, allowing them to participate in workload distribution.</li></ul><p>This structure provides clear, step-by-step automation for creating a Kubernetes cluster. It handles everything from initial setup to cluster-wide integration, ensuring a streamlined, repeatable deployment process.</p><h3>Conclusion</h3><p>By following this guide, we’ve automated the setup of a Kubernetes cluster using Ansible and kubeadm, streamlining what would otherwise be a complex and time-consuming process. From configuring Docker and CRI-Dockerd as the container runtime, initializing the control plane, to seamlessly adding worker nodes, each step was handled efficiently with Ansible playbooks. This approach not only saves time but also ensures consistency across all nodes, reducing the chances of manual error. With your Kubernetes environment fully deployed, you’re now equipped to scale applications, experiment with container orchestration, and explore Kubernetes’ vast ecosystem. This foundation serves as a powerful starting point for managing containerized applications and enhancing your DevOps workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc40f9e716f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Your Web App with Prometheus and Grafana: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@fenari.kostem/monitoring-your-web-app-with-prometheus-and-grafana-a-step-by-step-guide-8286dae606c7?source=rss-b00cda164c1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8286dae606c7</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Bora Köstem]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 07:35:13 GMT</pubDate>
            <atom:updated>2024-10-27T07:35:13.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bC_eGX_lufHiTIYb.png" /></figure><p>Monitoring web applications is essential for ensuring optimal performance and reliability. As applications grow in complexity, tracking their health becomes increasingly vital, not just for maintaining uptime but also for proactively addressing performance issues. Effective monitoring can alert you to potential problems before they escalate, ultimately leading to a better experience for end-users and peace of mind for developers and operators.</p><p>Prometheus and Grafana are two powerful tools that make this level of monitoring achievable. Prometheus is an open-source monitoring system that collects real-time metrics from your application and infrastructure, enabling in-depth analysis of their performance. With Prometheus, you can track specific metrics, set up custom alerts, and gain insights into your application’s behavior. Grafana complements Prometheus by offering a visual layer — transforming raw metrics into interactive dashboards. These dashboards make it easier to interpret complex data and spot trends or anomalies at a glance.</p><p>In this article, I’ll walk you through my journey of setting up a monitoring system for a Flask application using Prometheus and Grafana, detailing each step from installation to dashboard creation. Whether you’re a developer looking to enhance your app’s observability or just exploring monitoring tools, this guide will provide a practical overview to get you started.</p><h3>Setup</h3><p>To monitor our Flask app, we need to set up Prometheus for collecting metrics, Node Exporter to capture system-level metrics, and Grafana to visualize them. Using Docker Compose simplifies the setup by allowing us to define and manage each service in one file. Below is the configuration to start these services.</p><h4>Docker Compose Configuration</h4><p><strong>Prometheus</strong>: Prometheus serves as the core of our monitoring setup, gathering metrics from our Flask application and Node Exporter. This service uses the prom/prometheus:latest image, with the configuration file bound to /etc/prometheus/prometheus.yml. (We will configure prometheus.yml later)</p><pre>services:<br>  prometheus:<br>    image: prom/prometheus:latest<br>    container_name: prometheus<br>    volumes:<br>      - ./prometheus.yml:/etc/prometheus/prometheus.yml  # Bind mount the config file<br>    ports:<br>      - &quot;9090:9090&quot;  # Expose Prometheus on port 9090<br>    command:<br>      - &#39;--config.file=/etc/prometheus/prometheus.yml&#39;  # Specify the config file location<br>    restart: unless-stopped</pre><p><strong>Node Exporter</strong>: Node Exporter collects system metrics, such as CPU, memory, and disk usage, making them available to Prometheus. It’s configured to run with the host network and PID settings for comprehensive data collection.</p><pre>services:<br>  node_exporter:<br>    image: quay.io/prometheus/node-exporter:latest<br>    container_name: node_exporter<br>    command:<br>      - &#39;--path.rootfs=/host&#39;<br>    network_mode: host<br>    pid: host<br>    restart: unless-stopped<br>    volumes:<br>      - &#39;/:/host:ro,rslave&#39;</pre><p><strong>Grafana</strong>: Grafana provides a user-friendly interface to visualize and analyze the data collected by Prometheus. Using the grafana/grafana-enterprise image, it’s configured to store persistent data in a Docker volume.</p><pre>services:<br>  grafana:<br>    image: grafana/grafana-enterprise<br>    container_name: grafana<br>    restart: unless-stopped<br>    ports:<br>      - &#39;3000:3000&#39;<br>    environment:<br>      - GF_PATHS_CONFIG=/etc/grafana/grafana.ini<br>    volumes:<br>      - grafana-storage:/var/lib/grafana<br>      - /path/to/grafana_ini:/etc/grafana/grafana.ini<br><br>volumes:<br>  grafana-storage:</pre><h4>Starting the Setup</h4><p>To get this setup running:</p><ol><li>Ensure your prometheus.yml file is in the same directory as your Docker Compose file.</li><li>Run docker-compose up -d to start Prometheus, Node Exporter, and Grafana in detached mode.</li></ol><p>With this configuration, Prometheus will be accessible at http://localhost:9090, Grafana at http://localhost:3000, and we’ll be ready to start collecting and visualizing metrics in Grafana&#39;s dashboards. In the next sections, we’ll configure Prometheus to scrape metrics from our Flask app and set up dashboards in Grafana.</p><h3>Flask App Configuration</h3><h4>Initial Setup and Imports</h4><p>We start by importing the necessary modules for Flask, Prometheus metrics, and environment variables. The prometheus_client package provides counters, histograms, and gauges to monitor various aspects of the app.</p><pre>from flask import Flask, request, abort<br>import requests<br>from prometheus_client import Counter, Histogram, generate_latest, Gauge<br>import time<br>from dotenv import load_dotenv<br>import os<br><br>load_dotenv()<br>app = Flask(__name__)</pre><h3>Securing the Metrics Endpoint</h3><p>To secure access to the /metrics endpoint, we generate a shared secret key using:</p><pre>openssl rand -hex 32</pre><p>This hex key is stored in an .env file and loaded into the app to ensure that only authorized clients (in this case, Prometheus) can access the endpoint.</p><pre>SHARED_KEY = os.getenv(&#39;PROMETHEUS_HEX&#39;)</pre><h3>Defining Prometheus Metrics</h3><p><strong>Endpoint Clicks Counter</strong>: Counts the total number of clicks for each endpoint, labeled by the endpoint path.</p><pre># Counter to count endpoint clicks<br>endpoint_clicks = Counter(&#39;endpoint_clicks&#39;, &#39;Total clicks per endpoint&#39;, [&#39;endpoint&#39;])</pre><p><strong>Response Time Histogram</strong>: Measures the response time for each endpoint to respond in seconds, enabling us to monitor performance.</p><pre># Histogram to track response times<br>endpoint_latency = Histogram(&#39;endpoint_latency_seconds&#39;, &#39;Endpoint response time&#39;, [&#39;endpoint&#39;])</pre><p><strong>Unique User Locations Counter</strong>: Tracks unique user locations based on their IP address, with latitude and longitude labels.</p><pre># Counter for unique user locations based on latitude and longitude<br>user_locations = Counter(&#39;unique_user_locations&#39;, &#39;Unique user locations&#39;, [&#39;latitude&#39;, &#39;longitude&#39;])</pre><p><strong>Error Counter</strong>: Counts errors for each endpoint, tracking them by endpoint and error code.</p><pre># Counter to track errors<br>error_counter = Counter(&#39;endpoint_errors&#39;, &#39;Total errors per endpoint and status code&#39;, [&#39;endpoint&#39;, &#39;status_code&#39;])</pre><h4>Helper Function to Get User Location</h4><p>This function uses the ip-api.com service to fetch the location of a user by IP address. If successful, it returns the latitude and longitude; otherwise, it defaults to the coordinates [0.0, 0.0].</p><pre>def get_location(ip):<br>    try:<br>        response = requests.get(f&#39;http://ip-api.com/json/{ip}&#39;)<br>        data = response.json()<br>        if data[&#39;status&#39;] == &#39;success&#39;:<br>            return [data[&#39;lat&#39;], data[&#39;lon&#39;]]<br>        else:<br>            return [0.0, 0.0]<br>    except Exception as e:<br>        return [0.0, 0.0]</pre><h4>Tracking Metrics in Flask Middleware</h4><ol><li><strong>Start Timer</strong>: Sets the start time for each request to calculate response time.</li><li><strong>After Request Hook</strong>: For each response, increment the endpoint click counter, observe response time, and record user location. Excludes /favicon.ico and /metrics to avoid unnecessary logging.</li></ol><pre>@app.before_request<br>def start_timer():<br>    request.start_time = time.time()<br><br>@app.after_request<br>def track_metrics(response):<br>    if request.path != &#39;/favicon.ico&#39; and request.path != &#39;/metrics&#39;:<br>        # Track endpoint clicks<br>        endpoint_clicks.labels(endpoint=request.path).inc()<br><br>        # Track load time<br>        latency = time.time() - request.start_time<br>        endpoint_latency.labels(endpoint=request.path).observe(latency)<br><br>        # Track user locations<br>        location = get_location(request.remote_addr)<br>        user_locations.labels(latitude=location[0], longitude=location[1]).inc()<br>    return response</pre><h4>Error Handling</h4><p>Custom error handlers increment the error counter to track application errors, labeling them by endpoint and status code. This setup is especially useful for monitoring 500, 404, and 403 errors.</p><pre>@app.errorhandler(Exception)<br>def handle_exception(e):<br>    error_counter.labels(endpoint=request.path, status_code=&quot;500&quot;).inc()<br>    return &quot;An error occurred&quot;, 500<br><br>@app.errorhandler(404)<br>def page_not_found(e):<br>    error_counter.labels(endpoint=request.path, status_code=&quot;404&quot;).inc()<br>    return &quot;404 Not Found&quot;<br><br>@app.errorhandler(403)<br>def page_not_found(e):<br>    error_counter.labels(endpoint=request.path, status_code=&quot;403&quot;).inc()<br>    return &quot;403 Forbidden&quot;</pre><h4>Metrics Endpoint</h4><p>The /metrics endpoint exposes the collected metrics, secured with a Bearer token. Only requests with a valid token, which matches the generated SHARED_KEY, can access the metrics data. Unauthorized access returns an 401 Unauthorized or 403 Forbidden error.</p><pre>@app.route(&#39;/metrics&#39;)<br>def metrics():<br>    auth_header = request.headers.get(&quot;Authorization&quot;)<br>    if auth_header is None or not auth_header.startswith(&quot;Bearer &quot;):<br>        abort(401)  # Unauthorized if no bearer token is provided<br><br>    token = auth_header.split(&quot; &quot;)[1]<br>    if token != SHARED_KEY:<br>        abort(403)  # Forbidden<br>    return generate_latest(), 200, {&#39;Content-Type&#39;: &#39;text/plain&#39;}</pre><h4>Sample Endpoints</h4><p>The app includes sample endpoints (/, /about, /contact, /error1, /error2) to simulate various scenarios, including deliberate error generation for monitoring purposes.</p><pre>@app.route(&#39;/&#39;)<br>def home():<br>    return &quot;Welcome to the Home Page!&quot;<br><br>@app.route(&#39;/about&#39;)<br>def about():<br>    return &quot;This is the about page!&quot;<br><br>@app.route(&#39;/contact&#39;)<br>def contact():<br>    return &quot;This is the contact page!&quot;<br><br>@app.route(&#39;/error1&#39;)<br>def error1():<br>    raise Exception(&quot;This is a test error 1&quot;)<br><br>@app.route(&#39;/error2&#39;)<br>def error2():<br>    raise Exception(&quot;This is a test error 2&quot;)</pre><h4>Full Code</h4><pre>from flask import Flask, request, abort<br>import requests<br>from prometheus_client import Counter, Histogram, generate_latest, Gauge<br>import time<br>from dotenv import load_dotenv<br>import os<br><br>load_dotenv()<br><br>app = Flask(__name__)<br>SHARED_KEY = os.getenv(&#39;PROMETHEUS_HEX&#39;)<br># Counter to count endpoint clicks<br>endpoint_clicks = Counter(&#39;endpoint_clicks&#39;, &#39;Total clicks per endpoint&#39;, [&#39;endpoint&#39;])<br><br># Histogram to track response times<br>endpoint_latency = Histogram(&#39;endpoint_latency_seconds&#39;, &#39;Endpoint response time&#39;, [&#39;endpoint&#39;])<br><br>user_locations = Counter(&#39;unique_user_locations&#39;, &#39;Unique user locations&#39;, [&#39;latitude&#39;, &#39;longitude&#39;])<br><br># Counter to track errors<br>error_counter = Counter(&#39;endpoint_errors&#39;, &#39;Total errors per endpoint and status code&#39;, [&#39;endpoint&#39;, &#39;status_code&#39;])<br><br>def get_location(ip):<br>    try:<br>        response = requests.get(f&#39;http://ip-api.com/json/{ip}&#39;)<br>        data = response.json()<br>        if data[&#39;status&#39;] == &#39;success&#39;:<br>            # Return latitude and longitude as a string, e.g., &quot;40.7128,-74.0060&quot;<br>            return [data[&#39;lat&#39;],data[&#39;lon&#39;]]<br>        else:<br>            return [0.0,0.0]  # Default coordinates when location is unknown<br>    except Exception as e:<br>        return [0.0,0.0]  # Default coordinates on error<br><br>    <br>@app.before_request<br>def start_timer():<br>    request.start_time = time.time()<br><br>@app.after_request<br>def track_metrics(response):<br>    if request.path != &#39;/favicon.ico&#39; and request.path != &#39;/metrics&#39;:<br>        # Track endpoint clicks<br>        endpoint_clicks.labels(endpoint=request.path).inc()<br><br>        # Track load time<br>        latency = time.time() - request.start_time<br>        endpoint_latency.labels(endpoint=request.path).observe(latency)<br><br>        # Track user locations<br>        location = get_location(request.remote_addr)<br>        user_locations.labels(latitude=location[0], longitude=location[1]).inc()<br><br>    return response<br><br>@app.errorhandler(Exception)<br>def handle_exception(e):<br>    error_counter.labels(endpoint=request.path, status_code=&quot;500&quot;).inc()<br>    return &quot;An error occurred&quot;, 500<br><br>@app.errorhandler(404)<br>def page_not_found(e):<br>    error_counter.labels(endpoint=request.path, status_code=&quot;404&quot;).inc()<br>    return &quot;404 Not Found&quot;<br><br>@app.errorhandler(403)<br>def page_not_found(e):<br>    error_counter.labels(endpoint=request.path, status_code=&quot;403&quot;).inc()<br>    return &quot;403 Forbidden&quot;<br><br>@app.route(&#39;/metrics&#39;)<br>def metrics():<br>    auth_header = request.headers.get(&quot;Authorization&quot;)<br>    if auth_header is None or not auth_header.startswith(&quot;Bearer &quot;):<br>        abort(401)  # Unauthorized if no bearer token is provided<br><br>    token = auth_header.split(&quot; &quot;)[1]<br>    if token != SHARED_KEY:<br>        abort(403)  # Forbidden<br>    return generate_latest(), 200, {&#39;Content-Type&#39;: &#39;text/plain&#39;}<br><br>@app.route(&#39;/&#39;)<br>def home():<br>    return &quot;Welcome to the Home Page!&quot;<br><br>@app.route(&#39;/about&#39;)<br>def about():<br>    return &quot;This is the about page!&quot;<br><br>@app.route(&#39;/contact&#39;)<br>def contact():<br>    return &quot;This is the contact page!&quot;<br><br>@app.route(&#39;/error1&#39;)<br>def error1():<br>    raise Exception(&quot;This is a test error 1&quot;)<br><br>@app.route(&#39;/error2&#39;)<br>def error2():<br>    raise Exception(&quot;This is a test error 2&quot;)<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=5001, debug=True)</pre><h3>Prometheus Configuration</h3><p>The Prometheus configuration file defines how Prometheus will collect data from different endpoints. Here, we set up two scrape jobs: one for the Flask app metrics and another for system metrics via Node Exporter.</p><h4>Flask App Metrics</h4><p>This job collects metrics exposed by our Flask app on port 5001. To ensure only authorized access, we secure this job with a bearer_token containing our hex key.</p><pre># prometheus.yml<br>global:<br>  scrape_interval: 15s  # How often Prometheus will scrape targets<br><br>scrape_configs:<br>  - job_name: &#39;flask_app&#39;<br>    scrape_interval: 5s   # Frequency for scraping this specific job<br>    metrics_path: &#39;/metrics&#39;  # Flask app metrics endpoint<br>    static_configs:<br>      - targets: [&#39;localhost:5001&#39;]  # Flask app service name and port in Docker Compose<br>    scheme: http<br>    bearer_token: hex key here</pre><h4>Node Exporter Metrics</h4><p>Node Exporter, running on port 9100, exposes system-level metrics such as CPU, memory, and disk usage. This data provides insight into the overall health and performance of the server where our Flask app is hosted.</p><pre>- job_name: &#39;node-exporter&#39;<br>    static_configs:<br>      - targets: [&#39;localhost:9100&#39;]</pre><p>With these configurations in place, Prometheus will periodically scrape data from both the Flask application and Node Exporter. This setup allows us to monitor application-specific metrics, like endpoint clicks and response times, alongside broader system metrics for a complete view of our app’s performance and server health.</p><h3>Grafana Dashboard</h3><p>To begin visualizing our metrics in Grafana, we need to add Prometheus as a data source. This step establishes the connection between Grafana and Prometheus, allowing us to query and display the collected metrics.</p><p><strong>Access Grafana</strong>:</p><ul><li>Open your web browser and navigate to http://localhost:3000.</li></ul><p><strong>Add Data Source</strong>:</p><ul><li>In the Grafana UI, go to <strong>Connections</strong> on the left sidebar and select <strong>Data Sources</strong>.</li><li>Click on <strong>Add data source</strong>, then select <strong>Prometheus</strong> from the list.</li></ul><p><strong>Configure Prometheus Settings</strong>:</p><ul><li>In the <strong>URL</strong> field, enter http://localhost:9090 (or the URL where your Prometheus instance is running).</li><li>Leave the other fields with their default values unless you have specific authentication or advanced configurations.</li><li>Click <strong>Save &amp; Test</strong> to verify the connection. Grafana should display a success message if the connection is successful.</li></ul><p>Once Prometheus is successfully added as a data source, Grafana can pull in metrics from Prometheus and visualize them on custom dashboards. With the data source configured, you’re ready to create and customize dashboards for monitoring your Flask application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GRKXNyNtW252nSp7TE1m3w.png" /><figcaption>Adding prometheus as data source</figcaption></figure><h4><strong>Exploring Metrics with Grafana Dashboard</strong></h4><p>With Prometheus added as a data source, Grafana allows us to explore and visualize metrics quickly by using dashboards. This helps us see the types of metrics available and understand what data we can monitor without creating a custom dashboard from scratch.</p><p><strong>Adding a Dashboard</strong>:</p><ul><li>In the Grafana UI, go to <strong>Dashboards</strong> in the left sidebar and select <strong>New</strong>.</li><li>Click on <strong>Add </strong>then<strong> Visualization </strong>to start configuring your first panel.</li></ul><p><strong>Selecting the Data Source</strong>:</p><ul><li>In the panel editor, locate the <strong>Data source</strong> dropdown at the top and select <strong>Prometheus</strong> as the data source.</li><li>With Prometheus selected, Grafana will allow you to query and visualize metrics stored in Prometheus.</li></ul><p><strong>Exploring the Metrics</strong>:</p><ul><li>In the <strong>Metrics</strong> field, start typing or use the <strong>Metrics Browser</strong> to see all available metrics from Prometheus.</li><li>Metrics specific to our Flask app (e.g., endpoint_clicks, endpoint_latency_seconds, unique_user_locations) will be available, along with Node Exporter metrics like node_cpu_seconds_total or node_memory_MemAvailable_bytes.</li><li>Select a metric to see real-time data plotted on the panel. You can adjust time ranges and visualization settings to suit your preferences.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsR_832SSMbwU9TSfkWRhQ.png" /></figure><p>With Prometheus set up to scrape metrics from the Flask app and Grafana configured as the visualization layer, we can now create a dedicated dashboard to monitor key metrics. In this example, we’ll focus on visualizing the total endpoint clicks with a bar gauge to show how often each endpoint is accessed.</p><h4>Step 1: Create a New Dashboard</h4><ol><li>In the Grafana UI, go to <strong>Dashboard</strong> (four squares icon) on the left sidebar, then click <strong>New Dashboard</strong>.</li><li>Select <strong>Add a new panel</strong> to start building your first visualization.</li></ol><h4>Step 2: Select the Metric (Endpoint Clicks)</h4><ol><li>In the <strong>Query</strong> section at the bottom, select <strong>Prometheus</strong> as the data source.</li><li>In the <strong>Metric</strong> field, start typing endpoint_clicks_total and select it from the list. This metric will track the number of times each endpoint in the Flask app has been clicked.</li></ol><h4>Step 3: Set Up Visualization as a Bar Gauge</h4><ol><li>In the <strong>Panel</strong> settings on the right, under <strong>Visualization</strong>, select <strong>Bar gauge</strong>. This visualization displays each endpoint as a bar, with the height representing the number of clicks.</li><li>In the <strong>Value options</strong> section, choose <strong>Last</strong> as the calculation method. This will display the latest count of clicks for each endpoint.</li><li>Customize the <strong>Legend</strong> field with {{endpoint}} to label each bar by endpoint.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwNKUkEyGwvioS83TleN9g.png" /></figure><h4>Step 4: Apply and Save</h4><ol><li>Click <strong>Apply</strong> in the upper right to save the panel configuration to your dashboard.</li><li>Adjust other visual options like color schemes, min and max thresholds, or orientation (vertical or horizontal) to fit your preference.</li></ol><h4>Step 5: Adding More Panels (Optional)</h4><p>You can continue adding panels for other metrics, such as <strong>Endpoint Latency</strong>:</p><ul><li><strong>Latency by URL</strong>: Use endpoint_latency_seconds with a <strong>Gauge</strong> visualization to show the response time for each endpoint.</li><li><strong>Error Counts</strong>: Use endpoint_errors with a <strong>Table</strong> or <strong>Stat</strong> panel to track errors for each endpoint by status code.</li></ul><p>Each panel can be customized similarly by selecting the metric, choosing appropriate visualization types, and configuring labels and thresholds.</p><h4>Finalizing the Dashboard</h4><p>Once satisfied, click <strong>Save Dashboard</strong> and provide a name like “Flask App Monitoring.” This dashboard now offers an at-a-glance view of key metrics for your Flask application, making it easy to monitor traffic patterns, response times, and error counts for each endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7qTSQrON2rqrzA_JxViwA.png" /><figcaption>Final Dashboard</figcaption></figure><h3>Conclusion</h3><p>Prometheus offers a vast array of exporters that collect metrics from different sources, making it incredibly versatile for monitoring various aspects of your infrastructure and applications. With exporters like the <strong>Node Exporter</strong> for system metrics (CPU, memory, disk usage), the <strong>NVIDIA Exporter</strong> for GPU monitoring, and many others tailored for specific databases, web servers, and hardware, you can capture and visualize nearly any metric you need. By combining Prometheus with Grafana, you can create custom dashboards to monitor everything from hardware health to application performance, providing a comprehensive view tailored to your unique requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zPLD9JNKSGNmnw0ikc8Ffg.png" /><figcaption>Server Temp and Energy Consumption Monitoring</figcaption></figure><h3><strong>Bonus: Setting Up Alerts</strong></h3><p>Setting up alerts in Grafana enables you to receive real-time notifications whenever a metric crosses a defined threshold. This way, you can proactively monitor your application and take action before issues escalate. To enable email notifications, we’ll configure Grafana to send alerts using a Gmail account.</p><h4><strong>Configuring Grafana for Email Alerts</strong></h4><p>To allow Grafana to send email alerts, we’ll edit the grafana.ini file with the following settings:</p><pre>[smtp]<br>enabled = true<br>host = smtp.gmail.com:587<br>from_address = your_email@gmail.com  # Replace with your Gmail address<br>user = your_email@gmail.com  # Replace with your Gmail address<br>from_name = Grafana<br>password = your_password  # Replace with your Gmail app-specific password<br>skip_verify = true<br>startTLS_policy = Yes</pre><p><strong>[smtp]</strong></p><p><strong>enabled:</strong> Enables SMTP email notifications in Grafana.</p><p><strong>host:</strong> Specifies Gmail’s SMTP server (smtp.gmail.com) and port (587) for sending emails.</p><p><strong>from_address:</strong> The email address that will appear as the sender in alerts.</p><p><strong>user</strong>: Your Gmail address, used for authentication.</p><p><strong>password: </strong>The app-specific password generated for your Gmail account. You’ll need to create this password through your Google account if you have two-factor authentication enabled.</p><p><strong>startTLS_policy: </strong>Ensures a secure connection to the Gmail server</p><h4><strong>Creating an Alert Rule in Grafana</strong></h4><p>Once the email is configured, you can set up alert rules in your Grafana dashboard:</p><p>1. Open Your Dashboard: Go to the panel you want to monitor, and click on the panel title (three dots), then select more then click new alert rule.</p><p>2. Set Conditions: Define the condition for the alert, such as when a metric crosses a specific threshold. For example, you can set an alert if the response time for an endpoint exceeds a certain value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rgn_RJbMwzZ45I5QKpNdjQ.png" /></figure><p>3. Define Contact Point: In the alert rule, set up the contact point to Email and specify the email address to receive alerts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpDg-NP2-Y78GsK8fxstvQ.png" /></figure><p>4. Save: Click Save to apply the alert configuration.</p><p>With this setup, Grafana will send an email notification whenever the specified condition is met, ensuring you’re immediately informed of any critical issues. This email configuration with Gmail provides a straightforward way to receive alerts, helping you maintain close oversight of your application’s health and performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8286dae606c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitOps in Action: Deploying Flask with GitHub Actions, Helm, and ArgoCD]]></title>
            <link>https://medium.com/@fenari.kostem/gitops-in-action-deploying-flask-with-github-actions-helm-and-argocd-0817956b8878?source=rss-b00cda164c1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0817956b8878</guid>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Bora Köstem]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 15:56:02 GMT</pubDate>
            <atom:updated>2024-10-01T09:06:36.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*L3btadSG3UTrVxJGSQBNOw.png" /></figure><p>In the world of modern software development, the demand for efficient, automated deployment pipelines has never been higher. GitOps practices, combined with tools like GitHub Actions, Helm, and ArgoCD, offer a powerful way to achieve streamlined continuous integration and continuous delivery (CI/CD) for Kubernetes environments. By leveraging these tools, teams can ensure that their infrastructure is both manageable and scalable through automation and declarative configurations.</p><p>In this article, I will guide you through the process of setting up a GitOps pipeline with GitHub Actions, Helm, and ArgoCD. This builds on my <a href="https://medium.com/@fenari.kostem/from-code-to-kubernetes-building-a-full-gitops-pipeline-with-gitlab-ci-and-fluxcd-aa6188ca517f">previous work</a> where I demonstrated a similar pipeline using GitLab CI and FluxCD. After this, I will follow up with a comparison between FluxCD vs ArgoCD in my next article to help you choose the right tools for your DevOps needs.</p><h3>ArgoCD Installation With Helm</h3><p>You can install ArgoCD in your Kubernetes cluster using Helm, which makes the process simple and customizable. In this section, we’ll install ArgoCD using Helm and configure it to use NodePort, allowing easy access to the ArgoCD web UI. By changing a few default settings, we’ll make sure the installation is straightforward and accessible. Let’s go through the installation steps below.</p><pre>helm repo add argo https://argoproj.github.io/argo-helm<br>helm install argo-cd argo/argo-cd --version 7.5.2 --set server.service.type=NodePort --set applicationSet.service.type=NodePort</pre><blockquote>Note: In this helm install command we have changed the default ClusterIp value to NodePort in server.service.type, applicationSet.service.type for simplicity.</blockquote><p>After the installation you can get the admin password by writing the following:</p><pre>kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot; | base64 -d</pre><p>Now, after acquiring the initial password find out the node port of the ArgoCD server (default is 30080 for http and 30443 for https)</p><pre>kubectl get svc -n argocd</pre><p>If the installation is correct, when you go into the site with http:&lt;ip&gt;:30080 you will be asked to enter username and password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNAobZcQPtsIeundXWCgYQ.png" /><figcaption>ArgoCD Web UI</figcaption></figure><p>You can use the already defined default project, however in this example I will create a new project in ArgoCD. To create a new project in ArgoCD using the UI, navigate to the <strong>Settings </strong>section in the left sidebar and click the <strong>Projects</strong> section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTrEYiYnpiQ_GIuZYuCWuw.png" /><figcaption>Project Creation Form</figcaption></figure><p>In the project creation form, provide a name for your project and configure any restrictions, such as allowed source repositories, target cluster URLs, or specific namespaces (In my example I used wildcard “*” to allow everything). Once the required details are filled out, click <strong>Create</strong> to finalize the project setup. This project will now manage your GitOps deployments, allowing you to connect it with your repositories and clusters for automated synchronization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*eaAR8yGLWOlP9W-OCA7e_A.png" /><figcaption>Project Resource and Namespace allow/deny settings.</figcaption></figure><p>To add your GitHub repository to the ArgoCD project using HTTPS, go to the <strong>Repositories</strong> tab in the <strong>Settings</strong> and click <strong>Connect Repo</strong>. Select HTTPS for connection method, then enter the repository URL and use your GitHub username as the username, and your Personal Access Token (PAT) as the password. This repository will store the ArgoCD application configurations and manifests, not the actual application code itself. Once the repository is connected, ArgoCD can pull and manage the deployment definitions from this repo, ensuring your apps stay in sync with the desired state.</p><blockquote><strong>Note:</strong> <em>Ensure that your Personal Access Token (PAT) has only the permissions necessary for ArgoCD to function and avoid granting excessive access.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EsN4-enxCThg5SCrJY9CQ.png" /><figcaption>Connecting the repository</figcaption></figure><h3>Creating Helm Charts</h3><p>Before we start, make sure you have the Helm CLI installed on your machine. We’ll use Helm to create charts that define the Kubernetes resources for our application. These Helm charts will be stored in separate repository from ArgoCD and the application itself. In this case, I’ll store them in the <a href="https://github.com/BoraKostem/demo-app-Helm">demo-app-Helm repository</a>.</p><p>To create the initial Helm chart, run the following command:</p><pre>helm create demo-app</pre><p>This command will generate a template Helm chart in the demo-app directory. We’ll modify this chart to include only the resources we need: namespace.yaml, deployment.yaml, service.yaml, and hpa.yaml.</p><h4>Deployment.yaml</h4><p>The deployment.yaml file defines how our application will be deployed on the Kubernetes cluster. We use {{ include &quot;demo-app.name&quot; . }} to reference values dynamically from the chart&#39;s values file. The replicas field specifies the number of app instances, while the containers section defines the Docker image and port the app will use.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: {{ include &quot;demo-app.fullname&quot; . }}<br>  namespace: {{ include &quot;demo-app.namespace&quot; . | default &quot;demo-app&quot; }}<br>  labels:<br>    app: {{ include &quot;demo-app.name&quot; . }}<br>spec:<br>  replicas: {{ include &quot;demo-app.replicas&quot; . | default 1 }}<br>  selector:<br>    matchLabels:<br>      app: {{ include &quot;demo-app.name&quot; . }}<br>  template:<br>    metadata:<br>      labels:<br>        app: {{ include &quot;demo-app.name&quot; . }}<br>    spec:<br>      containers:<br>      - name: {{ include &quot;demo-app.name&quot; . }}<br>        image: {{ include &quot;demo-app.image.repository&quot; . }}:{{ include &quot;demo-app.image.tag&quot; . | default &quot;latest&quot; }}<br>        ports:<br>        - containerPort: {{ include &quot;demo-app.containerPort&quot; . | default 5000 }}<br>        resources:<br>          requests:<br>            cpu: {{ .Values.resources.requests.cpu }}<br>          limits:<br>            cpu: {{ .Values.resources.limits.cpu }}</pre><h4>HorizontalPodAutoscaler.yaml</h4><p>The hpa.yaml file configures autoscaling for our deployment based on CPU utilization. It automatically adjusts the number of replicas between the defined minimum and maximum based on CPU usage.</p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: {{ include &quot;demo-app.fullname&quot; . }}-hpa<br>  namespace: {{ include &quot;demo-app.namespace&quot; . | default &quot;demo-app&quot; }}<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: {{ include &quot;demo-app.fullname&quot; . }}<br>  minReplicas: {{ include &quot;demo-app.hpa.minReplicas&quot; . | default 1 }}<br>  maxReplicas: {{ include &quot;demo-app.hpa.maxReplicas&quot; . | default 5 }}<br>  metrics:<br>  - type: Resource<br>    resource:<br>      name: cpu<br>      target:<br>        type: Utilization<br>        averageUtilization: {{ include &quot;demo-app.hpa.targetCPUUtilizationPercentage&quot; . | default 70 }}</pre><h4>Namespace.yaml</h4><p>The namespace.yaml file ensures that the necessary namespace for our app is created. This helps keep our application resources organized in their own space within the Kubernetes cluster.</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: {{ include &quot;demo-app.namespace&quot; . | default &quot;demo-app&quot; }}<br>  labels:<br>    name: {{ include &quot;demo-app.namespace&quot; . | default &quot;demo-app&quot; }}</pre><h4>Service.yaml</h4><p>The service.yaml file defines the network service that exposes our application to the outside world. We’ve configured it as a NodePort service to make it accessible from outside the cluster, using the specified nodePort.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: {{ include &quot;demo-app.fullname&quot; . }}-service<br>  namespace: {{ include &quot;demo-app.namespace&quot; . | default &quot;demo-app&quot; }}<br>spec:<br>  selector:<br>    app: {{ include &quot;demo-app.name&quot; . }}<br>  ports:<br>    - protocol: TCP<br>      port: {{ include &quot;demo-app.containerPort&quot; . | default 5000 }}<br>      targetPort: {{ include &quot;demo-app.containerPort&quot; . | default 5000 }}<br>      nodePort: {{ include &quot;demo-app.service.nodePort&quot; . | default 30088 }}<br>  type: NodePort</pre><p>These Helm charts will provide the necessary Kubernetes resources for our app, ensuring that the deployment, service, and autoscaling are all configured properly.</p><p>Here is the configuration for the values file that we will reference throughout our Helm charts:</p><pre>namespace: demo-app<br>replicas: 1<br>image:<br>  repository: borakostem/demo-app<br>  tag: latest<br>containerPort: 5000<br>hpa:<br>  minReplicas: 1<br>  maxReplicas: 3<br>  targetCPUUtilizationPercentage: 70<br>service:<br>  nodePort: 30088<br>resources:<br>  requests:<br>    cpu: 100m<br>  limits:<br>    cpu: 600m</pre><h3>Creating ArgoCD Application File</h3><p>To deploy our application using ArgoCD, we need to define an Application resource in a YAML file. This file describes the source of the application manifests, the destination in the Kubernetes cluster, and the synchronization policies for managing the deployment. Let’s break down the key elements of the following YAML configuration step by step:</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: demo-app<br>  namespace: argocd<br>spec:<br>  destination:<br>    namespace: demo-app<br>    server: https://kubernetes.default.svc<br>  source:<br>    path: manifests/apps/demo-app<br>    repoURL: https://github.com/BoraKostem/demo-app-ArgoCD.git<br>    targetRevision: HEAD<br>  project: argocd-demo<br>  syncPolicy:<br>    automated:<br>      prune: true<br>      selfHeal: true<br>    syncOptions:<br>      - CreateNamespace=true<br>      - ApplyOutOfSyncOnly=true<br>      - SyncWave=0</pre><p>The spec section defines the core functionality of the ArgoCD application, including the target environment, source repository, and synchronization behavior.</p><p><strong>destination:</strong></p><ul><li><strong>namespace:</strong> This field tells ArgoCD in which Kubernetes namespace the app should be deployed. In our case, it’s demo-app, which is consistent with the namespace specified in our Helm chart.</li><li><strong>server:</strong> Defines the Kubernetes cluster where ArgoCD will deploy the app. https://kubernetes.default.svc points to the internal Kubernetes API server, meaning the app will be deployed in the same cluster where ArgoCD is running.</li></ul><p><strong>source:</strong></p><ul><li><strong>path:</strong> This specifies the path within the Git repository where the Kubernetes manifests for the app are located. In this case, it’s manifests/apps/demo-app, where the YAML manifests for demo-app are stored.</li><li><strong>repoURL:</strong> This is the URL of the Git repository where our ArgoCD application files are located. In this case, I use the URL https://github.com/BoraKostem/demo-app-ArgoCD.git, which points to the repository containing the application manifests.</li></ul><blockquote><strong>Make sure that this repository is added to the ArgoCD settings under the repositories section, or ArgoCD will throw an error when syncing the application.</strong></blockquote><ul><li><strong>targetRevision:</strong> Defines the branch, tag, or commit SHA that ArgoCD should track. HEAD means it will always track the latest commit in the default branch.</li><li><strong>project:</strong> Specifies the ArgoCD project to which this application belongs. Here, it’s set to argocd-demo, which is the project we’ve defined earlier for managing applications.</li></ul><h4>syncPolicy</h4><p>The syncPolicy section defines how ArgoCD manages the synchronization between the repository and the Kubernetes cluster.</p><p><strong>automated:</strong></p><ul><li><strong>prune:</strong> If set to true, ArgoCD will automatically remove any resources from the Kubernetes cluster that are no longer defined in the Git repository. This helps keep the cluster clean and in sync with the repository.</li><li><strong>selfHeal:</strong> When set to true, ArgoCD will continuously monitor the application and automatically correct any drift between the desired state (in Git) and the actual state in the cluster.</li></ul><p><strong>syncOptions:</strong> These options further customize the behavior of the sync process.</p><ul><li><strong>CreateNamespace=true:</strong> Ensures that the namespace specified in the destination (demo-app) is created if it doesn’t already exist.</li><li><strong>ApplyOutOfSyncOnly=true:</strong> This tells ArgoCD to apply changes only to resources that are out of sync with the desired state, reducing unnecessary updates.</li><li><strong>SyncWave=0:</strong> Defines the sync wave for the application. Sync waves allow you to control the order in which resources are applied during synchronization. SyncWave=0 means this resource will be applied in the first wave of sync operations.</li></ul><h3>Defining Github Actions Stages</h3><p>This workflow is designed to automate the CI/CD process for our demo app, integrating with ArgoCD to handle continuous delivery to a Kubernetes cluster. The pipeline consists of four key stages: build, test, dockerize, and deploy. Let’s break down each step in detail:</p><h4>Triggering the Workflow</h4><p>This workflow runs on every push or pull_request to the main branch. This ensures that any updates to the code in the main branch automatically trigger the pipeline.</p><pre>name: Demo App ArgoCD CI/CD Pipeline<br>on:<br>  push:<br>    branches:<br>      - main<br>  pull_request:<br>    branches:<br>      - main</pre><h4>Build Job</h4><pre>build:<br>    runs-on: ubuntu-latest<br>    steps:<br>        - name: Checkout code<br>          uses: actions/checkout@v4<br>        - name: Set up Python<br>          uses: actions/setup-python@v5<br>          with:<br>            python-version: 3.9<br>        - name: Install dependencies<br>          run: |<br>            cd app<br>            pip install -r requirements.txt<br>        - name: Run Flask application for a short period<br>          run: |<br>            cd app<br>            nohup flask run &amp;<br>            sleep 5<br>            pkill -f &quot;flask&quot;</pre><p>In most projects, such as .NET or Maven-based applications, there’s typically a build step to compile the code. However, Python Flask does not require compilation since it’s an interpreted language. Therefore, in the <strong>build</strong> job, our primary goal is to verify that the code runs without issues.</p><p>This job performs the following:</p><ol><li><strong>Checkout code:</strong> Retrieves the latest version of the repository.</li><li><strong>Set up Python:</strong> Configures Python 3.9 in the environment to match the application’s requirements.</li><li><strong>Install dependencies:</strong> Installs the required Python packages as defined in requirements.txt.</li><li><strong>Run Flask application:</strong> Launches the Flask app briefly to ensure that it starts correctly. The app is terminated after a short period (sleep 5) to avoid keeping it running for the entire job. This serves as a quick check that everything is functioning as expected.</li></ol><h4>Test Job</h4><pre>test:<br>    runs-on: ubuntu-latest<br>    needs: build<br>    steps:<br>        - name: Checkout code<br>          uses: actions/checkout@v4<br>        - name: Set up Python<br>          uses: actions/setup-python@v5<br>          with:<br>            python-version: 3.9<br>        - name: Install dependencies<br>          run: |<br>            cd app<br>            pip install -r requirements.txt<br>        - name: Run tests<br>          run: |<br>            cd app<br>            python -m unittest discover -s .</pre><p>The <strong>test</strong> job is triggered after the build job is successful (needs: build). It performs these steps:</p><ol><li><strong>Checkout code:</strong> Fetches the latest version of the app again.</li><li><strong>Set up Python:</strong> Configures Python 3.9.</li><li><strong>Install dependencies:</strong> Installs the Python dependencies.</li><li><strong>Run tests:</strong> Executes the unit tests defined in the app using unittest. This ensures that the app passes all the tests correctly before proceeding to the next stage.</li></ol><h4>Dockerize Job</h4><pre>dockerize:<br>    runs-on: ubuntu-latest<br>    needs: test<br>    steps:<br>    - name: Checkout code<br>      uses: actions/checkout@v4<br>    - name: Log in to Docker Hub<br>      uses: docker/login-action@v3<br>      with:<br>        username: ${{ secrets.DOCKER_USERNAME }}<br>        password: ${{ secrets.DOCKER_PASSWORD }}<br>    - name: Build and push Docker image<br>      run: |<br>        cd app<br>        export sha_short=$(git rev-parse --short ${GITHUB_SHA})<br>        docker build -t ${{ secrets.DOCKER_USERNAME }}/demo-app:$sha_short .<br>        docker push ${{ secrets.DOCKER_USERNAME }}/demo-app:$sha_short</pre><p>The <strong>dockerize</strong> job runs after the test job passes (needs: test). It handles containerization and pushing the image to Docker Hub:</p><ol><li><strong>Checkout code:</strong> Retrieves the latest code version.</li><li><strong>Log in to Docker Hub:</strong> Uses the stored secrets for the Docker Hub credentials to log in.</li><li><strong>Build and push Docker image:</strong> Builds a Docker image of the app using the Dockerfile and tags it with a short commit hash. Then, it pushes the image to Docker Hub.</li></ol><blockquote>Note: You need to define your DockerHub Username and Password in Github secrets</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfYYBOlrJsLkZyG4-Kw5UA.png" /><figcaption>Adding repository secrets to our project</figcaption></figure><h4>Deploy Job</h4><pre>deploy:<br>    runs-on: ubuntu-latest<br>    needs: dockerize<br>    steps:<br>      - name: Install Helm<br>        uses: azure/setup-helm@v4.2.0<br>      - name: Clone Helm Repository<br>        uses: actions/checkout@v4<br>        with:<br>          repository: &#39;BoraKostem/demo-app-Helm&#39;<br>          path: ./helm<br>          token: ${{ secrets.PAT }}<br>      - name: Clone ArgoCD Repository    <br>        uses: actions/checkout@v4<br>        with:<br>          repository: &#39;BoraKostem/demo-app-ArgoCD&#39;<br>          path: ./argocd<br>          token: ${{ secrets.PAT }}<br>      - name: Generate Kubernetes Manifests with Helm<br>        env:<br>          NAMESPACE: demo-app<br>          IMAGE_REPO: borakostem/<br>          IMAGE_NAME: demo-app<br>        run: |<br>          cd helm<br>          export sha_short=$(git rev-parse --short ${GITHUB_SHA})<br>          helm template release demo-app --debug --set namespace=${NAMESPACE}, --set image.repository=${IMAGE_REPO}${IMAGE_NAME}, --set image.tag=$sha_short --output-dir ./..<br>      - name: Update ArgoCD Manifests<br>        run: |<br>          cd argocd<br>          export sha_short=$(git rev-parse --short ${GITHUB_SHA})<br>          cd ..<br>          mkdir -p argocd/manifests/apps/demo-app<br>          rm -rf argocd/manifests/apps/demo-app/*<br>          mv ./demo-app/templates/* argocd/manifests/apps/demo-app/<br>          git config --global user.email &quot;fenari.kostem@gmail.com&quot;<br>          git config --global user.name &quot;CI_CD Bot&quot;<br>          cd argocd<br>          git add .<br>          git commit -m &quot;Update demo-app commit ${sha_short}&quot;<br>          git remote set-url origin https://github.com/BoraKostem/demo-app-ArgoCD.git<br>          git push origin main</pre><p>The <strong>deploy</strong> job kicks off after the dockerize job (needs: dockerize). It performs the following tasks:</p><ol><li><strong>Install Helm:</strong> Installs the Helm CLI to generate Kubernetes manifests.</li><li><strong>Clone Helm Repository:</strong> Clones the Helm chart repository containing the Kubernetes configuration for the app into the ./helm directory.</li><li><strong>Clone ArgoCD Repository:</strong> Clones the repository containing the ArgoCD application YAML into the ./argocddirectory.</li><li><strong>Generate Kubernetes Manifests with Helm:</strong> Uses the Helm chart to generate Kubernetes manifests for the demo app. It sets the namespace, image repository, and image tag based on the commit hash and outputs the generated manifests.</li><li><strong>Update ArgoCD Manifests:</strong> Copies the generated Helm templates into the ArgoCD repository, commits the changes, and pushes them to the main branch. This triggers ArgoCD to update the Kubernetes resources accordingly.</li></ol><blockquote>Note: Like in the previous job you need to define your Github PAT (Personal Access Token) in Github secrets to clone and push to repository.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxB1_Gdn01nj2KG5qWQHgg.png" /><figcaption>Example Commit in ArgoCD Repository</figcaption></figure><h3>Conclusion</h3><p>As you can see, this CI/CD pipeline successfully triggers a new deployment in ArgoCD, ensuring that the application is deployed automatically and kept in sync with the latest changes. By integrating testing and containerization, the pipeline also verifies the app’s functionality and health before deployment. This approach streamlines the entire process, from code changes to production, ensuring a robust and reliable deployment strategy. Below are two screenshots that demonstrate the successful deployment and synchronization in ArgoCD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVsujKXZsEIV7PGSfELTgQ.png" /><figcaption>Our App in ArgoCD UI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIljLqhvMTmYQEmp3df7YQ.png" /><figcaption>Our App Deployment Is In Healthy and Synced State</figcaption></figure><p>Check out the repositories used in this article!</p><p><a href="https://github.com/BoraKostem/demo-app-app">Flask App Repo</a></p><p><a href="https://github.com/BoraKostem/demo-app-Helm">Helm Repo</a></p><p><a href="https://github.com/BoraKostem/demo-app-ArgoCD">ArgoCD Repo</a></p><h4>Acknowledgments</h4><p>Special thanks to <a href="https://medium.com/u/692abde0c1f6">Yağız Küçükkambak</a> for meticulously proofreading this document and providing valuable feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0817956b8878" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Secure EKS Cluster with Terraform and Vault: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@fenari.kostem/deploying-a-secure-eks-cluster-with-terraform-and-vault-a-step-by-step-guide-4924e8a7e321?source=rss-b00cda164c1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4924e8a7e321</guid>
            <category><![CDATA[hashicorp-vault]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Bora Köstem]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 15:21:15 GMT</pubDate>
            <atom:updated>2024-09-30T14:13:56.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thzy84p_3m2BVkUCiuBOvw.png" /></figure><p>In this project, I deployed a basic Amazon EKS (Elastic Kubernetes Service) cluster on AWS using Terraform, with the added security of managing AWS credentials via HashiCorp Vault. The objective was to streamline infrastructure deployment using automation while ensuring sensitive data, such as AWS credentials, is securely stored and retrieved.</p><p>By integrating HashiCorp Vault into the Terraform workflow, we ensure that AWS credentials are never hardcoded or exposed. Instead, Terraform fetches the necessary secrets securely from Vault, enhancing the overall security of the deployment process. In the following sections, I’ll go through the configuration of HashiCorp Vault and how it plays a vital role in securing credentials for Terraform.</p><p>You can start by installing HashiCorp Vault using the <a href="https://developer.hashicorp.com/vault/tutorials/getting-started/getting-started-install">official installation guide.</a></p><h3>Vault Configuration</h3><p>Once Vault is installed and you’ve initialized it by generating the root token, you can log in to Vault using the following command:</p><pre>vault login &lt;root_token&gt;</pre><p>After logging in, navigate to the <strong>Access</strong> section and create an AppRole authentication method via the Vault UI. This will allow Terraform to securely authenticate and retrieve AWS credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Amf1qfOaNxfiamM0ifWAuw.png" /></figure><h4>Adding a Key-Value (KV) Secret Engine via Vault UI</h4><p>To manage AWS credentials and other secrets, you need to enable the KV secret engine in Vault. You can do this via the UI by following these steps:</p><ol><li>Log into the Vault UI.</li><li>In the <strong>Secrets Engines</strong> section, click <strong>Enable New Engine</strong>.</li><li>Select <strong>KV</strong> from the list of engines.</li><li>Choose a path (e.g., kv/) and click <strong>Enable</strong>.</li></ol><p>This will allow you to store key-value pairs securely and make them accessible to Terraform as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rksFbHC4DKzCINFSPzky8Q.png" /></figure><h4>Adding AWS Credentials to Vault as KV Secrets</h4><p>Once the KV secret engine is enabled, you can store your AWS credentials in Vault. This can be done either via the Vault UI.</p><p>In the Vault UI:</p><ol><li>Navigate to the <strong>Secrets</strong> section, and click on the <strong>KV engine</strong> you created (e.g., kv/).</li><li>Click <strong>Create secret</strong>.</li><li>Set the path as aws, and add two key-value pairs:</li></ol><ul><li>ACCESS_KEY: your AWS access key</li><li>SECRET_ACCESS_KEY: your AWS secret access key</li></ul><p>4. Save the secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7a9JmH-fn_NeonFNkqWSOQ.png" /><figcaption>Click create secret in this page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkdeWO_vb5akqudzgBVlGw.png" /><figcaption>Then you can add your aws credentials inside aws secret.</figcaption></figure><p>With this configuration, Terraform can securely retrieve your AWS credentials from Vault, ensuring they are never hardcoded or exposed during the deployment process.</p><h4>Creating a Vault Policy for Terraform</h4><pre>vault policy write terraform - &lt;&lt;EOF<br>path &quot;*&quot; {<br>  capabilities = [&quot;list&quot;, &quot;read&quot;]<br>}<br>path &quot;secrets/data/*&quot; {<br>  capabilities = [&quot;list&quot;, &quot;read&quot;]<br>}<br>path &quot;kv/data/*&quot; {<br>  capabilities = [&quot;list&quot;, &quot;read&quot;]<br>}<br>path &quot;secret/data/*&quot; {<br>  capabilities = [&quot;list&quot;, &quot;read&quot;]<br>}<br>path &quot;auth/token/create&quot; {<br>  capabilities = [&quot;create&quot;, &quot;read&quot;, &quot;update&quot;, &quot;list&quot;]<br>}<br>EOF</pre><ul><li><strong>vault policy write terraform</strong>: This command creates a new policy named terraform. Policies in Vault define what actions are allowed for certain paths.</li><li><strong>path “*”</strong>: The wildcard * grants permissions for all paths. The capabilities list and read allow Terraform to list and read secrets from any location.</li><li><strong>path “secrets/data/*”</strong>: This specific path provides access to the secrets stored in Vault. It allows Terraform to read and list secrets under the secrets/data path, essential for managing AWS credentials.</li><li><strong>path “kv/data/*”</strong>: Similarly, this gives Terraform permissions to interact with key-value (KV) data under this path. KV is one of Vault’s secrets engines, often used to store configuration details and sensitive data.</li><li><strong>path “secret/data/*”</strong>: This grants access to the legacy secret path, which was previously used for the KV secrets engine before version 2.</li><li><strong>path “auth/token/create”</strong>: This allows Terraform to create and manage tokens for accessing Vault resources, making sure it can authenticate and securely interact with Vault’s API.</li></ul><h4>Configuring an AppRole for Terraform</h4><pre>vault write auth/approle/role/terraform \<br>  secret_id_ttl=10m \<br>  token_num_uses=10 \<br>  token_ttl=20m \<br>  token_max_ttl=30m \<br>  secret_id_num_uses=40 \<br>  token_policies=terraform</pre><ul><li><strong>vault write auth/approle/role/terraform</strong>: This command creates an AppRole named terraform. AppRole is an authentication method designed for machine-to-machine (or service-to-service) interaction.</li><li><strong>secret_id_ttl=10m</strong>: The secret ID will expire after 10 minutes, limiting the duration in which Terraform can request authentication.</li><li><strong>token_num_uses=10</strong>: The token can only be used 10 times before it expires. This prevents excessive or unauthorized usage.</li><li><strong>token_ttl=20m</strong>: The token will be valid for 20 minutes before it needs to be refreshed.</li><li><strong>token_max_ttl=30m</strong>: The maximum lifespan of the token is set to 30 minutes, meaning even with renewals, the token will not last beyond this time.</li><li><strong>secret_id_num_uses=40</strong>: The secret ID can be used 40 times before it expires.</li><li><strong>token_policies=terraform</strong>: This binds the previously created terraform policy to the AppRole, ensuring that Terraform will only have the capabilities outlined in that policy.</li></ul><h4>Retrieving Role ID and Secret ID</h4><pre>vault read auth/approle/role/terraform/role-id<br>vault write -f auth/approle/role/terraform/secret-id</pre><ul><li><strong>vault read auth/approle/role/terraform/role-id</strong>: This retrieves the unique role ID for the AppRole, which Terraform will need to authenticate.</li><li><strong>vault write -f auth/approle/role/terraform/secret-id</strong>: This generates a secret ID for the AppRole. Terraform will use this secret ID in conjunction with the role ID to authenticate and retrieve the necessary credentials.</li></ul><h4>Setting Environment Variables for Terraform</h4><pre>export TF_VAR_vault_role_id= &lt;vault-role-id&gt;<br>export TF_VAR_vault_secret_id= &lt;vault-secret-id&gt;</pre><p>These environment variables store the role ID and secret ID retrieved from Vault. Terraform can then access these variables to authenticate securely with Vault during the deployment process.</p><p>In the next section, we will explore how Terraform is configured to deploy the EKS cluster and securely retrieve the necessary AWS credentials from Vault.</p><h3>Setting Up AWS EKS Cluster with Terraform</h3><p>In this section, we’ll walk through how to configure and deploy an EKS cluster on AWS using Terraform. The setup is designed to securely fetch AWS credentials from HashiCorp Vault, deploy the necessary infrastructure, and configure the EKS cluster with proper IAM roles, security groups, and networking components.</p><p>General structure of the project:</p><pre>terraform/<br>├── main.tf                   # Main Terraform configuration (Vault, EKS module)<br>├── variable.tf               # Variables for Vault and AWS configuration<br>├── outputs.tf                # Output values like EKS cluster endpoint, security group ID<br>├── aws/<br>│   └── eks/<br>│       ├── iam.tf            # IAM roles and policies for EKS<br>│       ├── provider.tf       # AWS provider configuration<br>│       ├── security.tf       # Security group definitions<br>│       ├── vpc.tf            # VPC and subnet definitions<br>│       └── eks.tf            # EKS cluster configuration<br>└── configs/<br>    └── kubeconfig_&lt;cluster_name&gt;  # Generated kubeconfig for EKS</pre><h4>1. Main Terraform Configuration (main.tf)</h4><p>The primary Terraform configuration integrates with HashiCorp Vault and defines the EKS module to provision the AWS resources:</p><pre>provider &quot;vault&quot; {<br>    address           = &quot;http://localhost:8200&quot; //This is your vault servers ip<br>    skip_child_token  = true<br>    auth_login {<br>        path = &quot;auth/approle/login&quot;<br>        parameters = {<br>            role_id   = var.vault_role_id<br>            secret_id = var.vault_secret_id<br>        }<br>    }<br>}<br>data &quot;vault_kv_secret_v2&quot; &quot;aws_iam&quot; {<br>    mount = &quot;kv&quot;<br>    name  = &quot;aws&quot;<br>}<br>module &quot;eks&quot; {<br>    source = &quot;./aws/eks&quot;<br>    aws_region    = var.aws_region<br>    aws_access_key = data.vault_kv_secret_v2.aws_iam.data[&quot;ACCESS_KEY&quot;]<br>    aws_secret_key = data.vault_kv_secret_v2.aws_iam.data[&quot;SECRET_ACCESS_KEY&quot;]<br>}</pre><ul><li><strong>Vault Provider</strong>: The provider is configured to authenticate with Vault using the role_id and secret_id, which are securely fetched from environment variables.</li><li><strong>Vault Data</strong>: The AWS credentials are retrieved from the Vault key-value store (aws), ensuring they are not hardcoded in the configuration.</li><li><strong>EKS Module</strong>: This module is sourced from the ./aws/eks folder and includes the AWS region, access key, and secret key for deploying the EKS cluster.</li></ul><h4>Variables (variable.tf)</h4><p>Define the variables to store the Vault role ID, secret ID, and AWS region:</p><pre>variable &quot;vault_role_id&quot; {<br>    description = &quot;Vault role ID&quot;<br>    type        = string<br>}<br><br>variable &quot;vault_secret_id&quot; {<br>    description = &quot;Vault secret ID&quot;<br>    type        = string<br>}<br><br>variable &quot;aws_region&quot; {<br>    description = &quot;AWS region&quot;<br>    default     = &quot;us-west-2&quot;<br>}</pre><p>These variables will be populated using the export command, which sets the role ID and secret ID for Vault authentication.</p><h4>2. EKS Module (./aws/eks)</h4><h4>Provider Configuration (provider.tf)</h4><p>This file sets up the AWS provider with the credentials securely fetched from Vault:</p><pre>terraform {<br>    required_providers {<br>        aws = {<br>            source  = &quot;hashicorp/aws&quot;<br>            version = &quot;5.65.0&quot;<br>        }<br>    }<br>}<br>provider &quot;aws&quot; {<br>    access_key = var.aws_access_key<br>    secret_key = var.aws_secret_key<br>    region     = var.aws_region<br>}</pre><h4>IAM Role for EKS (iam.tf)</h4><p>In this file, we create IAM roles and policies necessary for the EKS cluster to function:</p><pre>data &quot;aws_iam_policy_document&quot; &quot;assume_role&quot; {<br>    statement {<br>        effect = &quot;Allow&quot;<br>        principals {<br>            type        = &quot;Service&quot;<br>            identifiers = [&quot;eks.amazonaws.com&quot;]<br>        }<br>        actions = [&quot;sts:AssumeRole&quot;]<br>    }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;eks-role&quot; {<br>    name               = &quot;eks-role&quot;<br>    assume_role_policy = data.aws_iam_policy_document.assume_role.json<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;eks-AmazonEKSClusterPolicy&quot; {<br>    policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEKSClusterPolicy&quot;<br>    role       = aws_iam_role.eks-role.name<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;eks-AmazonEKSVPCResourceController&quot; {<br>    policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEKSVPCResourceController&quot;<br>    role       = aws_iam_role.eks-role.name<br>}</pre><p>This file defines:</p><ul><li><strong>EKS IAM Role</strong>: The role that the EKS control plane assumes.</li><li><strong>Policy Attachments</strong>: Attach Amazon-managed policies to the role to allow the EKS cluster to interact with other AWS services.</li></ul><h4>Security Group (security.tf)</h4><p>Define a security group for the EKS cluster:</p><pre>resource &quot;aws_security_group&quot; &quot;cluster-group&quot; {<br>    name        = &quot;eks-security-group&quot;<br>    description = &quot;Security group for EKS cluster&quot;<br>    vpc_id      = module.vpc.vpc_id<br>    ingress {<br>        description = &quot;Allow all inbound traffic&quot;<br>        from_port   = 0<br>        to_port     = 0<br>        protocol    = &quot;-1&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>    egress {<br>        description = &quot;Allow all outbound traffic&quot;<br>        from_port   = 0<br>        to_port     = 0<br>        protocol    = &quot;-1&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    }<br>    tags = {<br>        Name = &quot;eks-security-group&quot;<br>    }<br>}</pre><blockquote><strong>Note</strong>: Allowing all traffic is for demonstration purposes only. In a production environment, restrict ingress to specific ports (e.g., HTTP, HTTPS).</blockquote><h4>VPC Setup (vpc.tf)</h4><p>Define the VPC and subnets:</p><pre>data &quot;aws_availability_zones&quot; &quot;available&quot; {} //This fetches the availability zones<br><br>module &quot;vpc&quot; {<br>    source  = &quot;terraform-aws-modules/vpc/aws&quot;<br>    version = &quot;5.13.0&quot;<br>    name              = &quot;eks-vpc&quot;<br>    cidr              = &quot;10.0.0.0/16&quot;<br>    azs               = slice(data.aws_availability_zones.available.names, 0, 3)<br>    private_subnets   = [&quot;10.0.1.0/24&quot;, &quot;10.0.2.0/24&quot;, &quot;10.0.3.0/24&quot;]<br>    public_subnets    = [&quot;10.0.4.0/24&quot;, &quot;10.0.5.0/24&quot;, &quot;10.0.6.0/24&quot;]<br>    enable_nat_gateway = true<br>}</pre><ul><li><strong>data “aws_availability_zones”</strong>: This data source fetches the available AWS availability zones for the region where the cluster will be deployed. This ensures that the EKS cluster can be deployed across multiple availability zones for high availability and fault tolerance.</li><li><strong>azs</strong>: This line slices the first three availability zones from the fetched availability zone data. EKS requires <strong>at least two</strong> availability zones for high availability, and in this example, we are configuring the VPC to use three availability zones.</li><li><strong>private_subnets &amp; public_subnets</strong>: The private subnets are used for the EKS worker nodes, while the public subnets are reserved for resources like load balancers. Each subnet is mapped to one of the availability zones for redundancy.</li><li><strong>enable_nat_gateway</strong>: This enables a NAT gateway, allowing instances in private subnets to access the internet without being directly exposed.</li></ul><p>This configuration ensures that the EKS cluster is deployed across multiple availability zones, providing high availability and resilience. Subnets are defined for both public and private access, and the VPC is configured to meet the networking needs of the cluster.</p><h4>EKS Cluster Definition (main.tf)</h4><p>Define the EKS cluster using the official EKS module:</p><p>Here’s the complete code for the EKS module, followed by a detailed explanation of each section:</p><pre>module &quot;eks&quot; {<br>  source  = &quot;terraform-aws-modules/eks/aws&quot;<br>  version = &quot;~&gt; 20.0&quot;<br>  create_iam_role   = false<br>  iam_role_arn = aws_iam_role.eks-role.arn<br>  cluster_security_group_id = aws_security_group.cluster-group.id<br><br>  authentication_mode = &quot;API_AND_CONFIG_MAP&quot;<br><br>  cluster_enabled_log_types = []<br>  create_cloudwatch_log_group = false<br><br>  cluster_name    = &quot;eks-cluster&quot;<br>  cluster_version = &quot;1.30&quot;<br><br>  cluster_endpoint_public_access  = true<br><br>  cluster_addons = {<br>    coredns = {<br>      resolve_conflicts = &quot;OVERWRITE&quot;<br>    }<br>    eks-pod-identity-agent = {}<br>    kube-proxy             = {}<br>    vpc-cni = {<br>      resolve_conflicts = &quot;OVERWRITE&quot;<br>    }<br>  }<br><br>  vpc_id = module.vpc.vpc_id<br>  subnet_ids = module.vpc.private_subnets<br><br>  eks_managed_node_group_defaults = {<br>    instance_types = [&quot;t2.micro&quot;]<br>  }<br><br>  eks_managed_node_groups = {<br>    node1 = {<br>      # Starting on 1.30, AL2023 is the default AMI type for EKS managed node groups<br>      ami_type       = &quot;AL2023_x86_64_STANDARD&quot;<br>      instance_types = [&quot;t2.micro&quot;]<br><br>      min_size     = 2<br>      max_size     = 3<br>      desired_size = 2<br>    }<br>  }<br><br>  tags = {<br>    Environment = &quot;dev&quot;<br>    Terraform   = &quot;true&quot;<br>  }<br><br>  depends_on = [<br>    aws_iam_role_policy_attachment.eks-AmazonEKSClusterPolicy,<br>    aws_iam_role_policy_attachment.eks-AmazonEKSVPCResourceController,<br>  ]<br>}</pre><h4>- EKS Module Definitions</h4><pre>source  = &quot;terraform-aws-modules/eks/aws&quot;<br>version = &quot;~&gt; 20.0&quot;</pre><ul><li><strong>source</strong>: This specifies that we are using the official Terraform AWS EKS module, which abstracts the necessary resources required to deploy an EKS cluster.</li><li><strong>version</strong>: We are locking the module version to any version compatible with ~&gt; 20.0, ensuring stability in future updates without breaking changes.</li></ul><pre>create_iam_role   = false<br>iam_role_arn = aws_iam_role.eks-role.arn</pre><ul><li><strong>create_iam_role</strong>: We set this to false because we have manually created the required IAM role in a separate configuration (iam.tf). This avoids duplicating resources.</li><li><strong>iam_role_arn</strong>: This points to the ARN of the manually created IAM role (eks-role), which grants EKS the permissions it needs to manage resources in the AWS account.</li></ul><pre>cluster_security_group_id = aws_security_group.cluster-group.id</pre><ul><li><strong>cluster_security_group_id</strong>: This connects the EKS control plane to the security group cluster-group, ensuring the correct network security configuration is applied to the cluster.</li></ul><pre>authentication_mode = &quot;API_AND_CONFIG_MAP&quot;</pre><ul><li><strong>authentication_mode</strong>: This defines how access to the Kubernetes API is managed. API_AND_CONFIG_MAP allows both IAM-based authentication (via the API) and role-based access control (RBAC) via Kubernetes ConfigMap.</li></ul><pre>cluster_enabled_log_types = []<br>create_cloudwatch_log_group = false</pre><ul><li><strong>cluster_enabled_log_types</strong>: In this setting, no logs are enabled. Typically, you could enable logs like api, audit, authenticator, etc.</li><li><strong>create_cloudwatch_log_group</strong>: We disable the automatic creation of CloudWatch log groups.</li></ul><pre>cluster_name    = &quot;eks-cluster&quot;<br>cluster_version = &quot;1.30&quot;</pre><ul><li><strong>cluster_name</strong>: The name of the EKS cluster being created, set to &quot;eks-cluster&quot;.</li><li><strong>cluster_version</strong>: Specifies the version of Kubernetes to be installed on the cluster, which in this case is 1.30.</li></ul><pre>cluster_endpoint_public_access  = true</pre><ul><li><strong>cluster_endpoint_public_access</strong>: When set to true, this allows public access to the EKS cluster API endpoint. This is useful for external management but should be secured with appropriate security groups and IAM roles.</li></ul><pre>cluster_addons = {<br>  coredns = {<br>    resolve_conflicts = &quot;OVERWRITE&quot;<br>  }<br>  eks-pod-identity-agent = {}<br>  kube-proxy             = {}<br>  vpc-cni = {<br>    resolve_conflicts = &quot;OVERWRITE&quot;<br>  }<br>}</pre><ul><li><strong>coredns</strong>: CoreDNS is a DNS server that provides service discovery in Kubernetes. The conflict resolution is set to OVERWRITE, ensuring it overrides any previous configuration.</li></ul><blockquote><strong>Important Note:</strong></blockquote><blockquote>The CoreDNS add-on requires <strong>a minimum of 2 nodes</strong> in your EKS cluster to function properly. If fewer than 2 nodes are available, the CoreDNS pods will remain in a Pending or Creating state, as they rely on node availability to deploy across the cluster. Ensure that your EKS cluster is provisioned with at least 2 nodes to avoid issues.</blockquote><ul><li><strong>eks-pod-identity-agent</strong>: This add-on is used to enable IAM roles for service accounts, which helps assign AWS IAM roles directly to pods.</li><li><strong>kube-proxy</strong>: Manages Kubernetes networking for the cluster nodes.</li><li><strong>vpc-cni</strong>: The VPC CNI plugin handles pod networking within AWS VPC.</li></ul><pre>vpc_id = module.vpc.vpc_id<br>subnet_ids = module.vpc.private_subnets</pre><ul><li><strong>vpc_id</strong>: The VPC where the EKS cluster is deployed, retrieved from the VPC module.</li><li><strong>subnet_ids</strong>: Specifies the private subnets where EKS worker nodes will be deployed. Private subnets ensure that the nodes are not directly accessible from the internet.</li></ul><pre>eks_managed_node_group_defaults = {<br>  instance_types = [&quot;t2.micro&quot;]<br>}<br><br>eks_managed_node_groups = {<br>  node1 = {<br>    ami_type       = &quot;AL2023_x86_64_STANDARD&quot;<br>    instance_types = [&quot;t2.micro&quot;]<br><br>    min_size     = 2<br>    max_size     = 3<br>    desired_size = 2<br>  }<br>}</pre><ul><li><strong>eks_managed_node_group_defaults</strong>: Defines default settings for managed node groups. Here, the default instance type is t2.micro, suitable for small workloads and testing environments.</li><li><strong>eks_managed_node_groups</strong>: Defines a managed node group with the name node1. This node group will:</li><li>Use Amazon Linux 2023 (AL2023_x86_64_STANDARD) as the AMI type.</li><li>Use t2.micro instances.</li><li>Have a minimum of 2 nodes, a maximum of 3 nodes, and a desired count of 2 nodes for the cluster.</li></ul><pre>enable_cluster_creator_admin_permissions = true</pre><ul><li><strong>enable_cluster_creator_admin_permissions</strong>: Ensures that the user who creates the cluster has full administrative access.</li></ul><pre>tags = {<br>  Environment = &quot;dev&quot;<br>  Terraform   = &quot;true&quot;<br>}</pre><ul><li><strong>tags</strong>: Tags help with resource management and tracking. Here, two tags are added:</li><li><strong>Environment</strong>: Set to dev, indicating that this is a development environment.</li><li><strong>Terraform</strong>: Marks the resources as being created by Terraform.</li></ul><pre>depends_on = [<br>  aws_iam_role_policy_attachment.eks-AmazonEKSClusterPolicy,<br>  aws_iam_role_policy_attachment.eks-AmazonEKSVPCResourceController,<br>]</pre><ul><li><strong>depends_on</strong>: This ensures that the EKS cluster creation depends on the successful attachment of IAM policies (eks-AmazonEKSClusterPolicy and eks-AmazonEKSVPCResourceController) to the IAM role. This prevents Terraform from attempting to create the EKS cluster before the IAM role is properly set up.</li></ul><h4>Outputs (outputs.tf)</h4><p>Retrieve the important outputs after cluster creation:</p><pre>output &quot;cluster_endpoint&quot; {<br>    description = &quot;Endpoint for EKS control plane&quot;<br>    value       = module.eks.cluster_endpoint<br>}<br><br>output &quot;cluster_name&quot; {<br>    description = &quot;Kubernetes Cluster Name&quot;<br>    value       = module.eks.cluster_name<br>}<br>resource &quot;null_resource&quot; &quot;generate_kubeconfig&quot; {<br>    provisioner &quot;local-exec&quot; {<br>        command = &lt;&lt;EOT<br>          aws eks update-kubeconfig \<br>            --region ${var.aws_region} \<br>            --name ${module.eks.cluster_name} \<br>            --kubeconfig ./configs/kubeconfig_${module.eks.cluster_name}<br>        EOT<br>    }<br>}</pre><p>The null_resource generates the kubeconfig file for accessing the EKS cluster with kubectl.</p><blockquote>Note: You need to have AWS CLI to generate kubeconfig.</blockquote><p>With this setup, Terraform will deploy the entire EKS infrastructure, configure IAM roles, VPC, security groups, and generate a kubeconfig for cluster management.</p><p><em>“To explore the full project and codebase, you can find the repository at </em><a href="https://github.com/BoraKostem/terraform-eks"><em>https://github.com/BoraKostem/terraform-eks</em></a><em>&quot;</em></p><h3>Acknowledgments</h3><p>I would like to give a special thanks to my mentor, <a href="https://medium.com/u/692abde0c1f6">Yağız Küçükkambak</a>, for his invaluable guidance and support throughout this project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4924e8a7e321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Code to Kubernetes: Building a Full GitOps Pipeline with GitLab CI and FluxCD]]></title>
            <link>https://medium.com/@fenari.kostem/from-code-to-kubernetes-building-a-full-gitops-pipeline-with-gitlab-ci-and-fluxcd-aa6188ca517f?source=rss-b00cda164c1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa6188ca517f</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[flux-cd]]></category>
            <dc:creator><![CDATA[Bora Köstem]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 14:11:28 GMT</pubDate>
            <atom:updated>2024-09-30T14:14:41.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is GitOps and Why Do We Need It?</h3><p>GitOps is a modern approach to continuous deployment that leverages Git as the single source of truth for both application and infrastructure code. It enables teams to manage and automate their Kubernetes deployments by using Git repositories to track and version control all changes. With GitOps, any change made to the Git repository automatically triggers an update to the live environment, ensuring that the state of the system is always consistent with what’s defined in Git. It’s particularly beneficial in Kubernetes environments where managing infrastructure and application updates can become complex and error-prone without a robust version control system.</p><p>In this article, I will guide you through the fundamentals of GitOps and demonstrate how to configure a complete end-to-end GitOps pipeline using GitLab CI and FluxCD. We’ll explore how these tools integrate seamlessly to automate your Kubernetes deployments, ensuring that your infrastructure and applications are always in sync with the desired state defined in your Git repositories. Whether you’re new to GitOps or looking to enhance your CI/CD pipeline, this step-by-step guide will provide you with the knowledge and code snippets needed to build a robust and efficient GitOps workflow.</p><h4>Requirements:</h4><ul><li>GitLab repository</li><li>Running Kubernetes cluster</li><li>Kubectl and Flux CLI installed</li><li>GitLab Runner configured</li><li>Helm</li><li>FluxCD installed on Kubernetes</li><li>Access to a container registry (e.g., Docker Hub, GitLab Container Registry, Harbor)</li></ul><h4>General Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*lNrF1UpPy0dCFSytH1Tc_A.png" /></figure><p>In this GitOps pipeline, we’ll be setting up a series of stages that ensure our application is built, tested, and deployed to our Kubernetes cluster in a secure and automated manner. The pipeline is designed to handle a typical CI/CD workflow, which integrates static analysis, containerization, security testing, and deployment. Here’s how the stages are structured:</p><p><strong>Build Stage</strong>:</p><ul><li>This initial stage compiles the application and packages it.</li><li>The output of this stage is a build artifact that will be used in subsequent stages.</li></ul><p><strong>Test Stage</strong>:</p><ul><li>In this stage, the application is tested using unit and integration tests to ensure code quality and functionality.</li><li>After the tests pass, this stage splits into two parallel paths: (SAST and Docker build)</li></ul><p><strong>SAST (Static Application Security Testing)</strong>:</p><ul><li>This stage performs static code analysis to detect security vulnerabilities in your application’s source code.</li></ul><p><strong>Build and Push Docker Image</strong>:</p><ul><li>Simultaneously, the tested application is packaged into a Docker image and pushed to a container registry.</li></ul><p><strong>DAST (Dynamic Application Security Testing)</strong>:</p><ul><li>Once the Docker image is available, this stage runs dynamic security tests on the running application to find vulnerabilities in a live environment.</li><li>This stage ensures that the application is secure before moving to deployment.</li></ul><p><strong>Deploy Stage</strong>:</p><ul><li>If both SAST and DAST stages are successful, the pipeline proceeds to deployment.</li><li>In this stage, Kubernetes YAML files are generated from Helm charts (they will be in their own repository), which define how the application will be deployed in the Kubernetes cluster.</li><li>These YAML files are then pushed to a dedicated Git repository monitored by FluxCD.</li><li>FluxCD automatically detects these changes and updates the application in the Kubernetes cluster.</li></ul><p>For this tutorial, I will be using a general Spring Boot application as an example to demonstrate each of these stages, ensuring that the app is securely tested and deployed using GitOps principles.</p><h4>Getting Started</h4><p>To begin setting up our GitOps pipeline, we’ll need to install kubectl and FluxCD on our development machine. kubectl is the command-line tool for interacting with the Kubernetes cluster, allowing to manage and deploy applications. FluxCD is the GitOps operator that will monitor the Git repository for changes and ensure that our Kubernetes cluster is always in sync with the desired state defined in your repository.</p><p><strong>Install </strong><strong>kubectl</strong>: Follow the official Kubernetes documentation to download and install kubectl for your operating system. Once installed, configure it to connect to your Kubernetes cluster.</p><ul><li>Windows: <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl-windows">https://kubernetes.io/docs/tasks/tools/install-kubectl-windows</a></li><li>Linux: <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl-linux">https://kubernetes.io/docs/tasks/tools/install-kubectl-linux</a></li><li>MacOS: <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl-macos">https://kubernetes.io/docs/tasks/tools/install-kubectl-macos</a></li></ul><p><strong>Install FluxCD</strong>: Next, install the FluxCD CLI by following the instructions on the official FluxCD documentation. This tool will help you bootstrap FluxCD into your Kubernetes cluster and manage your GitOps deployments.</p><ul><li>Homebrew install for MacOS and Linux:</li></ul><pre>brew install fluxcd/tap/flux</pre><ul><li>Chocolately install for Windows:</li></ul><pre>choco install flux</pre><h4>Setting Up</h4><p>To set up our GitOps pipeline, we’ll need to create three separate repositories, each serving a specific purpose in our workflow:</p><p><strong>Spring App Repository</strong>: This repository will contain our Spring Boot application’s source code and the .gitlab-ci.yml file that defines our CI/CD pipeline. This is where we will manage the application’s development and continuous integration processes.</p><p><strong>Helm Charts Repository</strong>: This repository will store our Helm charts, which define the Kubernetes resources needed to deploy our application. These charts will be used in the deploy stage of our pipeline to generate Kubernetes manifests.</p><p><strong>FluxCD Repository</strong>: This repository will be monitored by FluxCD and will contain the Kubernetes manifest files generated from our Helm charts. Any changes pushed to this repository will trigger FluxCD to update our application in the Kubernetes cluster, ensuring that our deployments stay in sync with the desired state defined in our Git repositories.</p><h4>Installing FluxCD to Kubernetes</h4><p>With the necessary repositories in place, the next step is to install FluxCD on our Kubernetes cluster. FluxCD will act as the GitOps operator, continuously monitoring the FluxCD repository for changes and applying those changes to our cluster. To install FluxCD, we’ll use the Flux CLI, which simplifies the setup process.</p><p>To install FluxCD on Kubernetes, run the following command using the Flux CLI:</p><pre>flux bootstrap gitlab \<br>  --hostname= &lt;your gitlab host&gt; \<br>  --owner= &lt;repo location group&gt; \<br>  --repository= &lt;repository name&gt; \<br>  --branch= main\<br>  --path= &lt;Flux install location&gt; \<br>  --namespace= &lt;Kubernetes namespace to install&gt; \<br>--token-auth</pre><p>When setting up FluxCD with GitLab, we use the flux bootstrap gitlab command to connect our GitLab repository to FluxCD. Each flag in this command has a specific purpose:</p><ul><li>--hostname=&lt;your gitlab host&gt;: Specifies the hostname of our GitLab instance. If we&#39;re using a self-hosted GitLab, this will be our custom domain. For GitLab.com, it would be gitlab.com or you could remove the flag.</li><li>--owner=&lt;repo location group&gt;: Defines the group or user that owns the repository in GitLab. This is the top-level namespace where our repository is located.</li><li>--repository=&lt;repository name&gt;: Indicates the name of the GitLab repository that FluxCD will monitor for changes. This is where our Kubernetes manifest files will be stored.</li><li>--branch=main: Specifies the branch of the repository that FluxCD should track. The main branch is commonly used, but we can specify another branch if needed.</li><li>--path=&lt;Flux install location&gt;: Determines the directory path within the repository where FluxCD will install its manifests.</li><li>--namespace=&lt;Kubernetes namespace to install&gt;: Indicates the Kubernetes namespace where FluxCD will be installed. This helps in isolating FluxCD&#39;s resources from other applications in the cluster.</li><li>--token-auth: Enables token-based authentication to connect to our GitLab repository. This flag ensures that FluxCD can securely access our GitLab repository using a personal access token.</li></ul><h4>Creating The Pipeline</h4><p>In this section, we will set up our GitLab CI pipeline to automate the build, testing, Dockerization, and deployment of our Spring Boot application. Below is the .gitlab-ci.yml configuration, which defines the stages and jobs necessary for our pipeline. We&#39;ll break down each stage and explain its purpose.</p><h4>Pipeline Stages Overview</h4><pre>stages:<br>  - build<br>  - test<br>  - dockerize<br>  - deploy</pre><p>Our pipeline is organized into four stages:</p><ol><li><strong>Build</strong>: Compiles the application and packages it as a JAR file.</li><li><strong>Test</strong>: Runs unit and integration tests to ensure code quality.</li><li><strong>Dockerize</strong>: Packages the application into a Docker image and pushes it to a container registry.</li><li><strong>Deploy</strong>: Generates Kubernetes manifest files from Helm charts and pushes them to the FluxCD repository.</li></ol><h4>Build Stage</h4><pre>build:<br>  stage: build<br>  image: maven:3-jdk-8-alpine<br>  script:<br>    - mvn clean package -DskipTests<br>  artifacts:<br>    paths:<br>      - target/*.jar</pre><p>In the <strong>Build</strong> stage, we use a Maven Docker image to compile our Spring Boot application. The mvn clean package -DskipTests command packages the application into a JAR file while skipping the tests (which will be handled in the next stage). The compiled JAR file is stored as an artifact, which will be used in subsequent stages.</p><h4>Test Stage</h4><pre>test:<br>  stage: test<br>  image: maven:3-jdk-8-alpine<br>  script:<br>    - mvn test<br>  allow_failure: true</pre><p>The <strong>Test</strong> stage runs the unit and integration tests using Maven. This stage is marked with allow_failure: true, meaning the pipeline will continue even if the tests fail. This is useful when you want to ensure that the build and deployment proceed while still capturing test results for later review.</p><h4>Dockerize Stage</h4><pre>dockerize:<br>  stage: dockerize<br>  image: docker:24.0.5<br>  services:<br>    - docker:24.0.5-dind<br>  before_script:<br>    - docker login -u $REGISTRY_USER -p $REGISTRY_PASSWORD $IMAGE_REPO<br>  script:<br>    - cp target/*.jar .<br>    - docker build -t ${IMAGE_REPO}${IMAGE_NAME}:${CI_COMMIT_SHORT_SHA} .<br>    - docker push ${IMAGE_REPO}${IMAGE_NAME}:${CI_COMMIT_SHORT_SHA}<br>  artifacts:<br>    paths:<br>      - target/*.jar<br>  dependencies:<br>    - build<br>  needs:<br>    - job: build<br>      artifacts: true</pre><p>In the <strong>Dockerize</strong> stage, we build a Docker image from the JAR file generated in the build stage. The Docker image is then pushed to our specified container registry. The docker:24.0.5-dind service is used to run Docker in Docker, allowing us to build and push images within the CI environment. The image is tagged with the commit hash for versioning.</p><h3>Configuring Helm</h3><p>Before we proceed with the <strong>Manifest</strong> stage, we need to configure Helm by creating a Helm chart that will define the Kubernetes resources for our Spring Boot application. Helm allows us to manage these resources as reusable and configurable templates, making it easier to deploy our application across different environments.</p><h4>Step 1: Create a Helm Chart</h4><p>First, let’s create a new Helm chart named spring-app. This chart will contain the templates for our Kubernetes resources. You can create the Helm chart using the following command:</p><pre>helm create spring-app</pre><p>This command will generate a basic directory structure for the spring-app Helm chart, including default templates and a values.yaml file where we can define the default values for our templates.</p><h4>Step 2: Add Templates for Deployment, Service, Namespace, and HPA</h4><p>Next, we’ll add four specific templates to the spring-app chart to manage our application’s deployment, service, namespace, and horizontal pod autoscaler (HPA). Here’s how to structure each template:</p><p><strong>Deployment Template</strong></p><p>The Deployment template defines how our Spring Boot application will be deployed and managed within the Kubernetes cluster. It specifies the number of replicas, the container image to use, and the ports the application will expose.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: {{ include &quot;spring-app.fullname&quot; . }}<br>  namespace: {{ include &quot;spring-app.namespace&quot; . | default &quot;default-namespace&quot; }}<br>  labels:<br>    app: {{ include &quot;spring-app.name&quot; . }}</pre><ul><li><strong>apiVersion</strong>: Specifies the API version of the resource. Here, we use apps/v1 for the Deployment resource.</li><li><strong>kind</strong>: Defines the type of Kubernetes resource, which in this case is a Deployment.</li><li><strong>metadata</strong>: Contains information about the deployment, including the name, namespace, and labels. The name is generated using the fullname template helper, and the namespace is either provided or defaults to default-namespace.</li></ul><pre>spec:<br>  replicas: {{ include &quot;spring-app.replicas&quot; . | default 1 }}<br>  selector:<br>    matchLabels:<br>      app: {{ include &quot;spring-app.name&quot; . }}<br>  template:<br>    metadata:<br>      labels:<br>        app: {{ include &quot;spring-app.name&quot; . }}<br>    spec:<br>      containers:<br>      - name: {{ include &quot;spring-app.name&quot; . }}<br>        image: {{ include &quot;spring-app.image.repository&quot; . }}:{{ include &quot;spring-app.image.tag&quot; . | default &quot;latest&quot; }}<br>        ports:<br>        - containerPort: {{ include &quot;spring-app.containerPort&quot; . | default 8080 }}</pre><ul><li><strong>replicas</strong>: Specifies the desired number of pod replicas for the deployment. It defaults to 1 if not provided.</li><li><strong>selector</strong>: Ensures that the deployment matches pods with the specified labels, tying the deployment to the correct pods.</li><li><strong>template</strong>: Defines the pod template that the deployment will use to create pods. It includes metadata (labels) and the specification for the container(s).</li><li><strong>containers</strong>: Specifies the container configuration, including the name, image, and the port on which the application will listen.</li></ul><p><strong>HPA (Horizontal Pod Autoscaler) Template</strong></p><p>The HPA template configures an autoscaler for our deployment, which automatically adjusts the number of pod replicas based on CPU utilization or other metrics.</p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: {{ include &quot;spring-app.fullname&quot; . }}-hpa<br>  namespace: {{ include &quot;spring-app.namespace&quot; . | default &quot;default-namespace&quot; }}</pre><ul><li><strong>apiVersion</strong>: Specifies the API version, here it’s autoscaling/v2.</li><li><strong>kind</strong>: Indicates that this resource is a HorizontalPodAutoscaler.</li><li><strong>metadata</strong>: Contains the name and namespace of the HPA, similar to the deployment resource.</li></ul><pre>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: {{ include &quot;spring-app.fullname&quot; . }}<br>  minReplicas: {{ include &quot;spring-app.hpa.minReplicas&quot; . | default 1 }}<br>  maxReplicas: {{ include &quot;spring-app.hpa.maxReplicas&quot; . | default 5 }}<br>  metrics:<br>  - type: Resource<br>    resource:<br>      name: cpu<br>      target:<br>        type: Utilization<br>        averageUtilization: {{ include &quot;spring-app.hpa.targetCPUUtilizationPercentage&quot; . | default 70 }}</pre><ul><li><strong>scaleTargetRef</strong>: Defines the target resource that the HPA will manage, which in this case is the deployment we created earlier.</li><li><strong>minReplicas</strong> and <strong>maxReplicas</strong>: Define the minimum and maximum number of replicas that the HPA can scale to.</li><li><strong>metrics</strong>: Specifies the metric used to trigger scaling. Here, we are using CPU utilization, and scaling will occur if the CPU usage exceeds 70% on average.</li></ul><p><strong>Service Template</strong></p><p>The Service template defines how our application will be exposed to other services or the outside world. It maps an internal port (the container port) to an external port.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: {{ include &quot;spring-app.fullname&quot; . }}-service<br>  namespace: {{ include &quot;spring-app.namespace&quot; . | default &quot;default-namespace&quot; }}</pre><ul><li><strong>apiVersion</strong>: Specifies the API version, here it’s v1 for the Service resource.</li><li><strong>kind</strong>: Indicates that this resource is a Service.</li><li><strong>metadata</strong>: Contains the name and namespace of the service.</li></ul><pre>spec:<br>  selector:<br>    app: {{ include &quot;spring-app.name&quot; . }}<br>  ports:<br>    - protocol: TCP<br>      port: {{ include &quot;spring-app.containerPort&quot; . | default 8080 }}<br>      targetPort: {{ include &quot;spring-app.containerPort&quot; . | default 8080 }}<br>      nodePort: {{ include &quot;spring-app.service.nodePort&quot; . | default 30001 }}<br>  type: NodePort</pre><ul><li><strong>selector</strong>: Links the service to the pods with the specified label.</li><li><strong>ports</strong>: Defines the port mappings. The port is the external port, and the targetPort is the port the container listens on.</li><li><strong>type</strong>: Specifies the type of service. NodePort exposes the service on each node’s IP at a static port.</li></ul><p><strong>Namespace Template</strong></p><p>The Namespace template ensures that our application’s namespace is created.</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: {{ include &quot;spring-app.namespace&quot; . | default &quot;default-namespace&quot; }}<br>  labels:<br>    name: {{ include &quot;spring-app.namespace&quot; . | default &quot;default-namespace&quot; }}</pre><ul><li><strong>apiVersion</strong>: Specifies the API version, here it’s v1.</li><li><strong>kind</strong>: Indicates that this resource is a Namespace.</li><li><strong>metadata</strong>: Contains the name and labels for the namespace. Labels are optional but useful for organizing and selecting resources within the namespace.</li></ul><h4>Step 3: Update values.yaml</h4><p>In the values.yaml file, define the default values for our templates. Here&#39;s an example:</p><pre>replicaCount: 1<br>image:<br>  repository: &quot;your-repository/spring-app&quot;<br>  tag: &quot;latest&quot;<br>namespace: &quot;default-namespace&quot;<br>containerPort: 8080<br>hpa:<br>  minReplicas: 1<br>  maxReplicas: 5<br>  targetCPUUtilizationPercentage: 70<br>service:<br>  nodePort: 30001</pre><p>This configuration sets the default values for the deployment, such as the number of replicas, the Docker image to use, the active namespace, the container port, and the HPA settings. These values can be overridden when deploying the Helm chart to different environments.</p><p>With these templates in place, our Helm chart is now configured to generate the necessary Kubernetes manifests for deploying our Spring Boot application. These templates will be utilized in the Manifest stage to create YAML files that will be pushed to the FluxCD repository for deployment.</p><h3>Deploy Stage</h3><p>The <strong>Deploy</strong> stage is a crucial part of our GitLab CI pipeline where we generate Kubernetes manifests from Helm charts and push them to the FluxCD repository. This ensures that any changes to our application’s configuration are automatically deployed to the Kubernetes cluster by FluxCD. Here’s how this stage is structured and what each part of the script does.</p><h4>Deploy Stage Overview</h4><pre>deploy:<br>  stage: deploy<br>  image: <br>    name: alpine/helm<br>    entrypoint: [&quot;&quot;]<br>  variables:<br>    NAMESPACE: spring-app-namespace<br>  before_script:<br>    - git clone --depth 1 https://gitlab-ci-token:${CI_JOB_TOKEN}@&lt;helm-repo-url&gt;.git<br>    - git clone --depth 1 https://gitlab-ci-token:${CI_JOB_TOKEN}@&lt;flux-repo-url&gt;.git<br>  script:<br>    - helm template release helm/spring-app --set namespace=${NAMESPACE}, --set image.repository=${IMAGE_REPO}${IMAGE_NAME}, --set image.tag=${CI_COMMIT_SHORT_SHA}, --set fullnameOverride=${CI_PROJECT_NAME} --output-dir ./<br>    - rm -rf flux-cd/apps/spring-app/*<br>    - mv ./spring-app/templates/* flux-cd/apps/spring-app/<br>    - cd flux-cd<br>    - git config --global user.email &quot;ci_cd@example.com&quot;<br>    - git config --global user.name &quot;CI/CD Bot&quot;<br>    - git add .<br>    - git commit -m &quot;Update spring-app commit ${CI_COMMIT_SHORT_SHA}&quot;<br>    - git remote set-url origin https://gitlab-ci-token:${ACCESS_TOKEN}@&lt;flux-repo-url&gt;.git<br>    - git push origin main</pre><ol><li><strong>Image and Variables</strong></li></ol><pre>image: <br>  name: alpine/helm<br>  entrypoint: [&quot;&quot;]<br>variables:<br>  NAMESPACE: spring-app-namespace</pre><ul><li><strong>image</strong>: We use an Alpine-based Helm image to execute Helm commands in this stage.</li><li><strong>NAMESPACE</strong>: This variable defines the Kubernetes namespace where the application will be deployed. It can be customized as needed.</li></ul><p><strong>Before Script</strong></p><pre>before_script:<br>  - git clone --depth 1 https://gitlab-ci-token:${CI_JOB_TOKEN}@&lt;helm-repo-url&gt;.git<br>  - git clone --depth 1 https://gitlab-ci-token:${CI_JOB_TOKEN}@&lt;flux-repo-url&gt;.git</pre><ul><li><strong>git clone</strong>: These commands clone the Helm and FluxCD repositories into the CI environment. We use the GitLab CI token for authentication, ensuring secure access to these repositories.</li></ul><p><strong>Script</strong></p><pre>script:<br>  - helm template release helm/spring-app --set namespace=${NAMESPACE}, --set image.repository=${IMAGE_REPO}${IMAGE_NAME}, --set image.tag=${CI_COMMIT_SHORT_SHA}, --set fullnameOverride=${CI_PROJECT_NAME} --output-dir ./<br>  - rm -rf flux-cd/apps/spring-app/*</pre><ul><li><strong>helm template</strong>: This command generates Kubernetes manifests from the Helm chart using the provided variables. The output is directed to the current directory.</li><li><strong>rm -rf flux-cd/apps/spring-app/</strong>: This command clears the old manifest files in the FluxCD repository to avoid conflicts with the new deployment.</li></ul><p><strong>Moving Files and Committing Changes</strong></p><pre>- mv ./spring-app/templates/* flux-cd/apps/spring-app/<br>- cd flux-cd<br>- git config --global user.email &quot;ci_cd@example.com&quot;<br>- git config --global user.name &quot;CI/CD Bot&quot;<br>- git add .<br>- git commit -m &quot;Update spring-app commit ${CI_COMMIT_SHORT_SHA}&quot;<br>- git remote set-url origin https://gitlab-ci-token:${ACCESS_TOKEN}@&lt;flux-repo-url&gt;.git<br>- git push origin main</pre><ul><li><strong>mv</strong>: Moves the generated YAML files into the appropriate directory in the FluxCD repository.</li><li><strong>git config</strong>: Sets the Git user email and name for committing changes.</li><li><strong>git add</strong> and <strong>git commit</strong>: Stages and commits the new manifest files.</li><li><strong>git push</strong>: Pushes the changes to the main branch of the FluxCD repository. FluxCD will automatically detect this push and apply the new manifests to the Kubernetes cluster.</li></ul><p>This stage automates the generation and deployment of Kubernetes manifests using Helm, ensuring that any code changes are consistently and automatically reflected in the cluster via FluxCD.</p><p>After the deploy job definition runs, the line for the image definition in the deployment.yaml file should be updated in the repository where the Kubernetes manifest files of the application are located. This ensures that the application is deployed with the correct Docker image version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nyq0pp9Baljd2jspHV5Ow.png" /><figcaption>FluxCD Repository Update</figcaption></figure><h4>Configuring FluxCD with Kustomization File</h4><p>In the final stage of our GitOps pipeline, we will set up a FluxCD Kustomization file to point to the Kubernetes manifest files generated and pushed in the previous stages. This file will be used by FluxCD to manage the deployment of our Spring Boot application. Since we’ve already configured the Git repository using the flux bootstrap command, we only need to create and configure the Kustomization file to direct FluxCD to the correct location of our Kubernetes manifests.</p><p>The Kustomization files should be located inside the directory specified by the --path=&lt;Flux install location&gt; parameter that we defined in the flux bootstrap command. This ensures that FluxCD knows exactly where to find and apply the Kubernetes manifests for our application.</p><h4>Creating the Kustomization File</h4><p>The Kustomization file informs FluxCD where to find the Kubernetes manifest files in our Git repository and how often it should check for updates. Here’s what the file looks like:</p><pre>apiVersion: kustomize.toolkit.fluxcd.io/v1<br>kind: Kustomization<br>metadata:<br>  name: spring-app<br>  namespace: flux-system<br>spec:<br>  interval: 5m0s<br>  path: apps/spring-app<br>  prune: true<br>  sourceRef:<br>    kind: GitRepository<br>    name: flux-system<br>  targetNamespace: spring-app-namespace</pre><h4>Explanation of the Kustomization File</h4><p><strong>apiVersion</strong>: Specifies the API version used by FluxCD for Kustomization resources. Here, it’s kustomize.toolkit.fluxcd.io/v1.</p><p><strong>kind</strong>: Indicates that this resource is a Kustomization. This tells FluxCD that it will manage a set of Kubernetes resources based on this configuration.</p><p><strong>metadata</strong>: Contains the metadata for the Kustomization resource.</p><ul><li><strong>name</strong>: The name of this Kustomization resource, which is spring-app in this example.</li><li><strong>namespace</strong>: The namespace where the FluxCD components are installed, typically defined during the Flux bootstrap process. Here, it’s flux-system.</li></ul><p><strong>spec</strong>: Defines the behavior and scope of the Kustomization.</p><ul><li><strong>interval</strong>: Sets the frequency at which FluxCD checks the Git repository for updates. In this case, it checks every 5 minutes (5m0s).</li><li><strong>path</strong>: Specifies the path within the Git repository where the Kubernetes manifest files are located. For this setup, it’s apps/spring-app.</li><li><strong>prune</strong>: When set to true, FluxCD will automatically remove Kubernetes resources that are no longer defined in the manifest files, ensuring that the cluster state is always aligned with the Git repository.</li><li><strong>sourceRef</strong>: Defines the source Git repository that FluxCD will monitor.</li><li><strong>kind</strong>: Specifies that the source is a GitRepository.</li><li><strong>name</strong>: The name of the GitRepository resource as configured during the Flux bootstrap. In this case, it’s flux-system.</li><li><strong>targetNamespace</strong>: Specifies the Kubernetes namespace where the application will be deployed. For this setup, the application is deployed into the spring-app-namespace.</li></ul><p>By configuring this final stage, we ensure that FluxCD continuously monitors and synchronizes the state of our Kubernetes cluster with the manifests defined in our Git repository. With this Kustomization file in place, any changes pushed to the repository will automatically trigger an update in the cluster, ensuring that the application remains in sync with the desired state. This completes the end-to-end GitOps pipeline, automating the deployment process from code changes to live updates in Kubernetes.</p><blockquote>Special thanks to <a href="https://medium.com/u/692abde0c1f6">Yağız Küçükkambak</a> for being my mentor and support throughout this journey. Your mentorship has made all the difference.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa6188ca517f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>