<?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 Ankit Mittal on Medium]]></title>
        <description><![CDATA[Stories by Ankit Mittal on Medium]]></description>
        <link>https://medium.com/@ankit630?source=rss-950bae0c7d3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-3gGtfGFOtVJ8d2pfNVe5Q.jpeg</url>
            <title>Stories by Ankit Mittal on Medium</title>
            <link>https://medium.com/@ankit630?source=rss-950bae0c7d3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:16:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankit630/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[From DevOps Engineer to Building an AI-Powered Autonomous Trading Platform]]></title>
            <link>https://medium.com/@ankit630/from-devops-engineer-to-building-an-ai-powered-autonomous-trading-platform-8bba25774611?source=rss-950bae0c7d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bba25774611</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ankit Mittal]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 04:30:21 GMT</pubDate>
            <atom:updated>2026-08-03T04:30:21.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8i7XVAwuiPkZcZEo1SpKaw.png" /></figure><p>What happens when a DevOps engineer steps outside his familiar domain and tries to build a system that can understand information, make decisions and act independently?</p><p>A year ago, I began working on an ambitious personal project.</p><p>The goal was not to create another trading script connected to a single broker. I wanted to engineer a production-grade, broker-independent platform capable of processing real-time information, making autonomous decisions and managing execution across multiple accounts and brokers — without manual trade-by-trade intervention.</p><p>Today, the platform has completed approximately one year of live operation.</p><p>It brings together several complex capabilities:</p><ul><li>Real-time market data ingestion and processing</li><li>AI-powered financial news analysis</li><li>Autonomous decision and risk evaluation</li><li>Multi-account and multi-broker execution</li><li>Automated order and position reconciliation</li><li>Monitoring, audit trails and failure recovery</li><li>Deterministic risk controls and circuit breakers</li></ul><p>AI has played an important role throughout this journey.</p><p>It helped accelerate architecture exploration, development, testing, debugging and failure analysis. More importantly, AI is deeply integrated into the production platform itself — not added merely as a label.</p><p>Through an OpenRouter-based intelligence layer, the platform can work with multiple AI models to analyze unstructured financial news and convert it into structured, meaningful and actionable information.</p><p>Instead of treating news as simply positive or negative, the system attempts to understand:</p><ul><li>Which companies, sectors or financial instruments may be affected</li><li>What type of event has occurred</li><li>Its possible significance and direction</li><li>Whether its impact may be immediate or longer-term</li><li>How relevant it is under current market conditions</li><li>The confidence and risk associated with acting on it</li></ul><p>These AI-generated insights are evaluated alongside real-time market data, portfolio exposure, existing positions and predefined risk rules.</p><p>This allows the system to transform raw information into controlled action — not merely produce summaries or sentiment scores.</p><p>AI is integrated at multiple levels, but it does not bypass the platform’s safety mechanisms. Every potential action remains subject to deterministic safeguards, including position limits, exposure controls, execution rules and circuit breakers.</p><p>One of the most challenging parts was building the multi-broker architecture.</p><p>Every broker has different APIs, authentication mechanisms, order formats, rate limits and failure behaviours. The platform handles these differences through modular broker adapters behind a common interface.</p><p>The decision engine remains independent of the execution provider. This makes it possible to onboard additional brokers without redesigning the core system, operate across multiple accounts and avoid relying on any single broker.</p><p>The same principle applies to AI. The model layer can work with different models through OpenRouter rather than being permanently tied to a single provider.</p><p>My DevOps background became the foundation of the platform.</p><p>Observability, idempotency, fault tolerance, deployment safety, automated recovery, reconciliation and auditability were treated as fundamental product capabilities — not afterthoughts.</p><p>The biggest lesson from this journey is that autonomy is not only about making intelligent decisions.</p><p>A truly autonomous system must continue behaving safely and predictably when data is delayed, APIs fail, connections drop, models return uncertain outputs or the external state no longer matches the system’s internal state.</p><p>The attached image represents an operational milestone from the past year. It is shared as part of my engineering journey — not as investment advice, a performance guarantee or an invitation to replicate the strategy.</p><p>This project has pushed me deeper into AI engineering, autonomous systems, real-time processing, multi-model integration, distributed architecture and financial technology.</p><p>More importantly, it reminded me how much we can learn when we step beyond the boundaries of our primary role.</p><p>I began this journey with a simple question:</p><p><strong>“Can I actually build this?”</strong></p><p>One year later, the question has changed:</p><p><strong>“How much further can I take it?”</strong></p><p>There is still a great deal to explore, improve and learn — particularly around making AI-powered systems safer, more reliable and more effective under real-world conditions.</p><p>Sometimes growth begins when we stop waiting to feel completely ready, start building and allow difficult problems to teach us what to learn next.</p><p>#AIEngineering #GenerativeAI #AutonomousSystems #DevOps #PlatformEngineering #OpenRouter #MLOps #FinTech #AlgorithmicTrading #RealTimeSystems #SoftwareArchitecture #ContinuousLearning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bba25774611" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to Policy Control in Kubernetes: Enhancing Security, Compliance, and Operational Efficiency]]></title>
            <link>https://medium.com/@ankit630/guide-to-policy-control-in-kubernetes-enhancing-security-compliance-and-operational-efficiency-e67c14f03b09?source=rss-950bae0c7d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e67c14f03b09</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <category><![CDATA[cloud-native-security]]></category>
            <category><![CDATA[policy-as-code]]></category>
            <dc:creator><![CDATA[Ankit Mittal]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 13:42:16 GMT</pubDate>
            <atom:updated>2024-09-11T13:42:16.287Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the rapidly evolving landscape of cloud-native technologies, Kubernetes has emerged as the de facto standard for container orchestration. As organizations increasingly adopt Kubernetes for deploying and managing their applications, the need for robust policy control mechanisms has become paramount. This article delves deep into the world of policy control in Kubernetes, exploring its importance, comparing popular tools, and providing detailed insights into production-ready policies.</p><h3>Why Implement Policy Control in Kubernetes?</h3><p>Kubernetes’ flexibility and power come with increased complexity and potential security risks. Policy control in Kubernetes addresses these challenges by providing a framework to enforce security, compliance, and operational best practices across your cluster. Here are the key reasons why implementing policy control is crucial:</p><ol><li><strong>Enhanced Security</strong>: Policy control allows you to enforce security best practices, such as running containers as non-root users, limiting privileges, and ensuring proper network segmentation.</li><li><strong>Compliance Adherence</strong>: For organizations in regulated industries, policy control helps ensure that all deployments meet necessary compliance requirements (e.g., HIPAA, PCI-DSS, GDPR).</li><li><strong>Operational Consistency</strong>: Policies can enforce standardization across your organization, ensuring all teams follow best practices for resource management, naming conventions, and more.</li><li><strong>Cost Optimization</strong>: By enforcing resource quotas and limits, policy control helps prevent resource overutilization and optimizes cloud spending.</li><li><strong>Risk Mitigation</strong>: Automated policy enforcement reduces the risk of human error and ensures that security and compliance standards are consistently met.</li><li><strong>Auditing and Governance</strong>: Policy control provides a clear audit trail of what is allowed or denied in your cluster, facilitating governance and troubleshooting.</li></ol><h3>Popular Policy Control Tools for Kubernetes</h3><p>Several tools have emerged to address the need for policy control in Kubernetes. Let’s explore the most prominent ones:</p><h3>1. Open Policy Agent (OPA)</h3><p>OPA is a general-purpose policy engine that can be used with Kubernetes through its Gatekeeper project.</p><p><strong>Key Features</strong>:</p><ul><li>Declarative policy language (Rego)</li><li>Extensive integration capabilities</li><li>Supports complex policy logic</li><li>Can be used beyond Kubernetes</li></ul><p><strong>Pros</strong>:</p><ul><li>Highly flexible and powerful</li><li>Large community and ecosystem</li><li>Can handle complex, stateful policies</li></ul><p><strong>Cons</strong>:</p><ul><li>Steeper learning curve</li><li>Requires separate installation and management</li></ul><h3>2. Kyverno</h3><p>Kyverno is a policy engine designed specifically for Kubernetes.</p><p><strong>Key Features</strong>:</p><ul><li>Kubernetes-native (uses familiar YAML syntax)</li><li>No new language to learn</li><li>Built-in policy reporting</li><li>Supports generating and mutating resources</li></ul><p><strong>Pros</strong>:</p><ul><li>Easy to learn and use</li><li>Integrates seamlessly with Kubernetes</li><li>Lightweight and doesn’t require external components</li></ul><p><strong>Cons</strong>:</p><ul><li>Less flexible for complex, stateful policies</li><li>Limited use outside of Kubernetes</li></ul><h3>3. Kubewarden</h3><p>Kubewarden is an emerging policy engine that uses WebAssembly for policy execution.</p><p><strong>Key Features</strong>:</p><ul><li>Language-agnostic policy authoring</li><li>High performance due to WebAssembly</li><li>Supports both admission control and audit mode</li></ul><p><strong>Pros</strong>:</p><ul><li>Flexibility in policy language choice</li><li>Potential for high performance</li><li>Isolation of policy execution</li></ul><p><strong>Cons</strong>:</p><ul><li>Relatively new, with a smaller ecosystem</li><li>Requires understanding of WebAssembly concepts</li></ul><h3>4. Falco</h3><p>While primarily known as a runtime security tool, Falco can also be used for policy enforcement in Kubernetes.</p><p><strong>Key Features</strong>:</p><ul><li>Real-time threat detection</li><li>Extensible rules engine</li><li>Kernel-level visibility</li></ul><p><strong>Pros</strong>:</p><ul><li>Deep insights into runtime behavior</li><li>Can detect and prevent real-time threats</li><li>Extensive set of pre-defined rules</li></ul><p><strong>Cons</strong>:</p><ul><li>More focused on runtime security than general policy enforcement</li><li>Can have performance overhead</li></ul><h3>Comparison of Policy Control Tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Vj3FE9rLPAvHUMtEyFI0Q.png" /></figure><h3>Essential Policies for Production Environments</h3><p>When implementing policy control in a production Kubernetes environment, certain policies are crucial for maintaining security, compliance, and operational efficiency. Let’s explore these essential policies in detail:</p><h3>1. Image Source Control</h3><p><strong>Policy</strong>: Ensure containers are only pulled from approved registries.</p><p><strong>Implementation (Kyverno)</strong>:</p><pre>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: allowed-registries<br>spec:<br>  validationFailureAction: enforce<br>  rules:<br>  - name: validate-registries<br>    match:<br>      resources:<br>        kinds:<br>        - Pod<br>    validate:<br>      message: &quot;Image must be from an approved registry&quot;<br>      pattern:<br>        spec:<br>          containers:<br>          - image: &quot;approved-registry.com/*&quot;</pre><p><strong>Use Case</strong>: Prevent the use of potentially malicious or untrusted container images.</p><p><strong>Advantage</strong>: Reduces the risk of supply chain attacks and ensures all deployed containers come from verified sources.</p><h3>2. Resource Quotas and Limits</h3><p><strong>Policy</strong>: Enforce CPU and memory limits on all containers.</p><p><strong>Implementation (OPA)</strong>:</p><pre>package kubernetes.admission<br><br>deny[msg] {<br>  input.request.kind.kind == &quot;Pod&quot;<br>  container := input.request.object.spec.containers[_]<br>  not container.resources.limits.cpu<br>  msg := sprintf(&quot;Container &#39;%v&#39; does not have CPU limit defined&quot;, [container.name])<br>}<br>deny[msg] {<br>  input.request.kind.kind == &quot;Pod&quot;<br>  container := input.request.object.spec.containers[_]<br>  not container.resources.limits.memory<br>  msg := sprintf(&quot;Container &#39;%v&#39; does not have memory limit defined&quot;, [container.name])<br>}</pre><p><strong>Use Case</strong>: Prevent resource exhaustion and ensure fair resource allocation.</p><p><strong>Advantage</strong>: Improves cluster stability, prevents noisy neighbor issues, and helps in cost optimization.</p><h3>3. Pod Security Standards</h3><p><strong>Policy</strong>: Enforce the Kubernetes Pod Security Standards at the restricted level.</p><p><strong>Implementation (Kyverno)</strong>:</p><pre>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: pod-security-restricted<br>spec:<br>  validationFailureAction: enforce<br>  rules:<br>  - name: restricted-volumes<br>    match:<br>      resources:<br>        kinds:<br>        - Pod<br>    validate:<br>      message: &quot;Use of hostPath volumes is not allowed&quot;<br>      pattern:<br>        spec:<br>          =(volumes):<br>            - X(hostPath): &quot;null&quot;<br>  - name: restrict-privilege-escalation<br>    match:<br>      resources:<br>        kinds:<br>        - Pod<br>    validate:<br>      message: &quot;Privilege escalation is not allowed&quot;<br>      pattern:<br>        spec:<br>          containers:<br>          - securityContext:<br>              allowPrivilegeEscalation: false</pre><p><strong>Use Case</strong>: Enforce a baseline of security best practices across all pods.</p><p><strong>Advantage</strong>: Significantly reduces the attack surface and potential for privilege escalation attacks.</p><h3>4. Network Policies</h3><p><strong>Policy</strong>: Enforce default deny for ingress and egress traffic, requiring explicit allowance.</p><p><strong>Implementation (OPA)</strong>:</p><pre>package kubernetes.admission<br><br>deny[msg] {<br>  input.request.kind.kind == &quot;NetworkPolicy&quot;<br>  not input.request.object.spec.policyTypes<br>  msg := &quot;NetworkPolicy must specify policyTypes&quot;<br>}<br>deny[msg] {<br>  input.request.kind.kind == &quot;NetworkPolicy&quot;<br>  not array_contains(input.request.object.spec.policyTypes, &quot;Ingress&quot;)<br>  not array_contains(input.request.object.spec.policyTypes, &quot;Egress&quot;)<br>  msg := &quot;NetworkPolicy must include both Ingress and Egress types&quot;<br>}<br>array_contains(array, element) {<br>  array[_] == element<br>}</pre><p><strong>Use Case</strong>: Ensure all network traffic is explicitly defined and controlled.</p><p><strong>Advantage</strong>: Improves security posture by implementing the principle of least privilege for network communication.</p><h3>5. Secret Management</h3><p><strong>Policy</strong>: Prevent secrets from being defined directly in Pod specifications.</p><p><strong>Implementation (Kyverno)</strong>:</p><pre>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: no-secrets-in-env<br>spec:<br>  validationFailureAction: enforce<br>  rules:<br>  - name: check-for-secrets-in-env<br>    match:<br>      resources:<br>        kinds:<br>        - Pod<br>    validate:<br>      message: &quot;Secrets should not be defined directly in Pod spec&quot;<br>      pattern:<br>        spec:<br>          containers:<br>          - =(env):<br>            - X(valueFrom):<br>                X(secretKeyRef): &quot;null&quot;</pre><p><strong>Use Case</strong>: Enforce the use of proper secret management tools and prevent exposure of sensitive information.</p><p><strong>Advantage</strong>: Reduces the risk of secret exposure and encourages the use of more secure secret management practices.</p><h3>6. Mandatory Labels and Annotations</h3><p><strong>Policy</strong>: Enforce required labels for all resources.</p><p><strong>Implementation (OPA)</strong>:</p><pre>package kubernetes.admission<br><br>required_labels = [&quot;app&quot;, &quot;environment&quot;, &quot;team&quot;]<br>deny[msg] {<br>  input.request.kind.kind == &quot;Deployment&quot;<br>  provided_labels := {label | input.request.object.metadata.labels[label]}<br>  missing := required_labels - provided_labels<br>  count(missing) &gt; 0<br>  msg := sprintf(&quot;Deployment is missing required labels: %v&quot;, [missing])<br>}</pre><p><strong>Use Case</strong>: Ensure all resources are properly tagged for management, cost allocation, and operational purposes.</p><p><strong>Advantage</strong>: Improves resource management, enables better cost tracking, and facilitates easier troubleshooting and auditing.</p><h3>7. Ingress TLS Enforcement</h3><p><strong>Policy</strong>: Ensure all Ingress resources use TLS.</p><p><strong>Implementation (Kyverno)</strong>:</p><pre>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: require-tls-ingress<br>spec:<br>  validationFailureAction: enforce<br>  rules:<br>  - name: check-tls<br>    match:<br>      resources:<br>        kinds:<br>        - Ingress<br>    validate:<br>      message: &quot;Ingress resources must specify TLS&quot;<br>      pattern:<br>        spec:<br>          tls:<br>            - hosts:<br>              - &quot;?*&quot;<br>              secretName: &quot;?*&quot;</pre><p><strong>Use Case</strong>: Enforce HTTPS for all incoming traffic to improve security.</p><p><strong>Advantage</strong>: Ensures data in transit is encrypted, protecting against man-in-the-middle attacks and data interception.</p><h3>8. Container Vulnerability Scanning</h3><p><strong>Policy</strong>: Reject deployments with critical vulnerabilities.</p><p><strong>Implementation (OPA)</strong>:</p><pre>package kubernetes.admission<br><br>deny[msg] {<br>  input.request.kind.kind == &quot;Deployment&quot;<br>  container := input.request.object.spec.template.spec.containers[_]<br>  annotation := input.request.object.metadata.annotations[&quot;security-scan-result&quot;]<br>  annotation == &quot;critical&quot;<br>  msg := sprintf(&quot;Deployment blocked due to critical vulnerability in container: %v&quot;, [container.name])<br>}</pre><p><strong>Use Case</strong>: Prevent the deployment of containers with known critical vulnerabilities.</p><p><strong>Advantage</strong>: Reduces the risk of exploits and ensures a baseline level of security for all deployed containers.</p><h3>9. Multi-tenancy Isolation</h3><p><strong>Policy</strong>: Enforce namespace isolation and prevent cross-namespace resource access.</p><p><strong>Implementation (Kyverno)</strong>:</p><pre>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: namespace-isolation<br>spec:<br>  validationFailureAction: enforce<br>  rules:<br>  - name: check-namespace-references<br>    match:<br>      resources:<br>        kinds:<br>        - NetworkPolicy<br>        - RoleBinding<br>    validate:<br>      message: &quot;Resources must not reference other namespaces&quot;<br>      pattern:<br>        metadata:<br>          namespace: &quot;?*&quot;<br>        spec:<br>          =(ingress):<br>            - from:<br>              - namespaceSelector: &quot;null&quot;<br>          =(roleRef):<br>            namespace: &quot;null&quot;</pre><p><strong>Use Case</strong>: Ensure proper isolation between different teams or applications sharing the same cluster.</p><p><strong>Advantage</strong>: Improves security by preventing unauthorized access across namespace boundaries and enforcing the principle of least privilege.</p><h3>Implementing Policy Control: Best Practices</h3><ol><li><strong>Start with Audit Mode</strong>: Begin by implementing policies in audit mode to understand their impact before enforcing them.</li><li><strong>Gradual Enforcement</strong>: Incrementally enforce policies, starting with non-critical ones and gradually moving to stricter controls.</li><li><strong>Regular Policy Reviews</strong>: Continuously review and update policies to adapt to new threats and changing organizational requirements.</li><li><strong>Education and Training</strong>: Ensure all team members understand the policies and their rationale to promote compliance.</li><li><strong>Integrate with CI/CD</strong>: Incorporate policy checks into your CI/CD pipeline to catch violations early in the development process.</li><li><strong>Monitor and Alert</strong>: Set up monitoring and alerting for policy violations to quickly identify and address issues.</li><li><strong>Version Control Policies</strong>: Manage your policies as code, storing them in version control systems for transparency and auditability.</li><li><strong>Performance Considerations</strong>: Be mindful of the performance impact of your policies, especially in large clusters.</li></ol><h3>Conclusion</h3><p>Policy control in Kubernetes is not just a security measure; it’s a fundamental aspect of maintaining a robust, compliant, and efficient container orchestration environment. By implementing comprehensive policies using tools like OPA, Kyverno, or others, organizations can significantly enhance their Kubernetes security posture, ensure compliance with industry standards, and streamline operations.</p><p>As Kubernetes continues to evolve, policy control will play an increasingly critical role in managing the complexities of cloud-native environments. By adopting a proactive approach to policy implementation and management, organizations can stay ahead of potential security threats, maintain operational excellence, and fully leverage the power of Kubernetes.</p><p>Remember, the journey to effective policy control is ongoing. Start small, learn from your experiences, and continuously refine your approach. With diligence and the right tools, you can create a Kubernetes environment that is not only powerful and flexible but also secure and compliant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e67c14f03b09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Maven Application Containerisation and Security Scanning with GitLab CI/CD]]></title>
            <link>https://medium.com/@ankit630/advanced-maven-application-containerisation-and-security-scanning-with-gitlab-ci-cd-d170a8342788?source=rss-950bae0c7d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d170a8342788</guid>
            <category><![CDATA[kaniko]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[container-security]]></category>
            <category><![CDATA[gitlab-cicd]]></category>
            <category><![CDATA[docker-in-docker]]></category>
            <dc:creator><![CDATA[Ankit Mittal]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 15:02:14 GMT</pubDate>
            <atom:updated>2024-09-10T15:02:14.043Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous post we discussed about importance of implementing the Codequality, SAST, Secret Scanning, Unit tests and Dependency Scanning across our Gitlab pipelines. So if you not covered that yet, would suggest to cover the previous posts so you can continue ahead in this post.</p><p><a href="https://medium.com/@ankit630/elevating-software-quality-a-comprehensive-gitlab-ci-cd-pipeline-for-java-projects-8b91d098b4b4">Elevating Software Quality: A Comprehensive GitLab CI/CD Pipeline for Java Projects</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5JFtlfFBkvh59O52wckRg.png" /></figure><h3>Containerizing Maven Applications in GitLab CI/CD</h3><p>Containerization has become a crucial part of modern software development and deployment. For Java applications built with Maven, containerizing the application ensures consistency across different environments and simplifies deployment processes. In this section, we’ll explore two popular approaches to building container images within a GitLab CI/CD pipeline: Docker-in-Docker (DinD) and Kaniko.</p><h3>Docker-in-Docker (DinD) Approach</h3><p>Docker-in-Docker allows you to run Docker commands inside a Docker container. Here’s an example of how to implement DinD in your GitLab CI/CD pipeline:</p><pre>package:dind:<br>  stage: package<br>  image: docker:20.10.16<br>  services:<br>    - name: docker:20.10.16-dind<br>      command: [&quot;--tls=false&quot;]<br>  variables:<br>    DOCKER_HOST: tcp://docker:2375<br>    DOCKER_TLS_CERTDIR: &quot;&quot;<br>    DOCKER_DRIVER: overlay2<br>  before_script:<br>    - until docker info; do sleep 1; done<br>    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY<br>  script:<br>    - cd $PROJECT_PATH<br>    - docker build -t $DOCKER_IMAGE:dind .<br>    # We don&#39;t push this image, it&#39;s just for demonstration<br>  rules:<br>    - if: $CI_COMMIT_BRANCH</pre><h3>Advantages of DinD:</h3><ol><li><strong>Familiar Docker CLI commands</strong>: Developers can use the same Docker commands they use locally. Example: docker build, docker push, etc.</li><li><strong>Full Docker functionality</strong>: Supports advanced features like multi-stage builds. Example of a multi-stage Dockerfile:</li></ol><pre># Build stage<br>FROM maven:3.8.1-openjdk-11-slim AS build<br>WORKDIR /app<br>COPY pom.xml .<br>COPY src ./src<br>RUN mvn clean package -DskipTests<br><br># Run stage<br>FROM openjdk:11-jre-slim<br>COPY --from=build /app/target/myapp.jar /app.jar<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;/app.jar&quot;]3. Ability to use Docker Compose: Useful for complex setups involving multiple services. Example: You could use Docker Compose to spin up a database alongside your application for integration tests.</pre><p>3. <strong>Ability to use Docker Compose</strong>: Useful for complex setups involving multiple services. Example: You could use Docker Compose to spin up a database alongside your application for integration tests.</p><p><strong>Limitations of DinD:</strong></p><ul><li><strong>Security concerns</strong>: Requires running a privileged container, which can be a security risk.</li><li><strong>Performance overhead</strong>: Running Docker inside Docker adds an extra layer of virtualization.</li><li><strong>Filesystem issues</strong>: Can encounter problems with volume mounts and file permissions.</li></ul><p>Kaniko is a tool to build container images from a Dockerfile, inside a container or Kubernetes cluster, without depending on a Docker daemon. Here’s how to use Kaniko in your GitLab CI/CD pipeline:</p><pre>package:kaniko:<br>  stage: package<br>  image:<br>    name: gcr.io/kaniko-project/executor:debug<br>    entrypoint: [&quot;&quot;]<br>  script:<br>    - echo &quot;{\&quot;auths\&quot;:{\&quot;$CI_REGISTRY\&quot;:{\&quot;username\&quot;:\&quot;$CI_REGISTRY_USER\&quot;,\&quot;password\&quot;:\&quot;$CI_REGISTRY_PASSWORD\&quot;}}}&quot; &gt; /kaniko/.docker/config.json<br>    - /kaniko/executor <br>      --context $CI_PROJECT_DIR/$PROJECT_PATH<br>      --dockerfile $CI_PROJECT_DIR/$PROJECT_PATH/Dockerfile<br>      --destination $DOCKER_IMAGE:$CI_COMMIT_SHA<br>      --destination $DOCKER_IMAGE:latest<br>  rules:<br>    - if: $CI_COMMIT_BRANCH</pre><h3>Advantages of Kaniko:</h3><ol><li>Doesn’t require privileged access to run</li><li>Built specifically for running in containerized environments</li><li>Can be easily integrated into Kubernetes environments</li></ol><h3>How Kaniko Overcomes DinD Limitations:</h3><ol><li>Improved security by not requiring a Docker daemon</li><li>Better performance as it doesn’t need to run a full Docker environment</li><li>Avoids filesystem issues associated with DinD</li></ol><h3>Container Security Scanning</h3><p>After building our container image, it’s crucial to scan it for vulnerabilities. GitLab provides built-in container scanning capabilities. Here’s how to implement it:</p><pre>container_scanning:<br>  stage: scan<br>  variables:<br>    CS_IMAGE: $DOCKER_IMAGE:$CI_COMMIT_SHA<br>  rules:<br>    - if: $CI_COMMIT_BRANCH</pre><h3>The Importance of Container Scanning</h3><p>Container scanning is essential for reducing the attack surface and improving the overall security posture of your application. It helps identify:</p><ol><li>Vulnerable packages and libraries</li><li>Outdated base images</li><li>Misconfigurations in the container setup</li></ol><h3>Example Vulnerabilities</h3><p>Let’s look at some examples of vulnerabilities that our scanner might detect:</p><ol><li><strong>CVE-2022–37434 (Critical):</strong> A heap-based buffer overflow in zlib, which could lead to remote code execution.</li><li><strong>CVE-2023–0286 (High):</strong> A type confusion vulnerability in OpenSSL, potentially allowing arbitrary code execution.</li><li><strong>CVE-2022–1304 (High):</strong> An out-of-bounds read/write vulnerability in e2fsprogs, which could lead to arbitrary code execution.</li></ol><p>These vulnerabilities highlight the importance of regular scanning and updating of our container images. In a future post, we’ll explore how to remediate these issues and implement automated fix processes.</p><h3>Pushing for DevSecOps Practices</h3><p>Implementing container scanning in our CI/CD pipeline is a significant step towards adopting DevSecOps practices. It helps:</p><ol><li>Shift security left in the development lifecycle</li><li>Provide early feedback to developers about potential vulnerabilities</li><li>Ensure that only secure images are deployed to production</li></ol><h3>Conclusion</h3><p>In this post, we’ve explored advanced techniques for containerizing Maven applications using GitLab CI/CD. We’ve compared Docker-in-Docker and Kaniko approaches, highlighting their strengths and limitations. Additionally, we’ve introduced container scanning as a crucial step in our pipeline to enhance the security of our deployments.</p><p>By adopting these practices, we’re not only improving our containerization workflow but also taking significant steps towards a more secure and robust CI/CD pipeline. In our next post, we’ll delve deeper into vulnerability remediation strategies and explore how to automate the process of fixing and rescanning our container images.</p><p>Stay tuned for more insights on building efficient, secure, and scalable CI/CD pipelines for Java applications!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d170a8342788" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elevating Software Quality: A Comprehensive GitLab CI/CD Pipeline for Java Projects]]></title>
            <link>https://medium.com/@ankit630/elevating-software-quality-a-comprehensive-gitlab-ci-cd-pipeline-for-java-projects-8b91d098b4b4?source=rss-950bae0c7d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b91d098b4b4</guid>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[security-testing-services]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[ci-pipeline]]></category>
            <dc:creator><![CDATA[Ankit Mittal]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 07:31:13 GMT</pubDate>
            <atom:updated>2024-09-09T07:31:13.504Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1XfYGCLw0uCJeW2sIRcDg.png" /></figure><p>In today’s fast-paced software development landscape, maintaining high code quality while ensuring rapid delivery is crucial. This article delves into a robust GitLab CI/CD pipeline designed for Java projects, incorporating essential quality assurance and security checks. We’ll explore how this pipeline integrates code coverage, code quality analysis, dependency scanning, static application security testing (SAST), and unit testing to create a comprehensive quality control system.</p><p>This article is in continuation to our previous article and use the same project to implement comprehensive testing before building the project, so if you have not covered it yet, I would highly recommend to go through it first to cover the project and pipeline details which we enhancing in this post.<br><a href="https://medium.com/@ankit630/optimizing-gitlab-ci-cd-pipelines-with-amazon-efs-a-comprehensive-guide-to-maven-dependency-364babaa96ac">https://medium.com/@ankit630/optimizing-gitlab-ci-cd-pipelines-with-amazon-efs-a-comprehensive-guide-to-maven-dependency-364babaa96ac</a></p><h3>The Power of Comprehensive CI/CD</h3><p>Continuous Integration and Continuous Deployment (CI/CD) have become indispensable in modern software development. A well-structured CI/CD pipeline not only automates the build and deployment process but also integrates various quality checks, ensuring that only high-quality, secure code makes it to production. Let’s dive into the components of our advanced GitLab CI/CD pipeline.</p><h3>Pipeline Overview</h3><p>Our pipeline consists of five key stages:</p><ol><li><strong>Unit Tests</strong></li><li><strong>Code Coverage</strong></li><li><strong>Code Quality Analysis</strong></li><li><strong>Dependency Scanning</strong></li><li><strong>Static Application Security Testing (SAST)</strong></li></ol><p>Each stage plays a crucial role in maintaining code quality and security. Let’s examine each component in detail.</p><h3>1. Unit Tests</h3><p>Unit testing is the foundation of any robust testing strategy. Our pipeline uses JUnit 5 for unit testing, complemented by Mockito for mocking.yam</p><pre>.unit_tests:<br>  stage: test<br>  image: maven:3.8.1-openjdk-11-slim<br>  variables:<br>    MAVEN_OPTS: &quot;-Dmaven.repo.local=/gitlab/m2/repository&quot;<br>  script:<br>    - cd ${PROJECT_PATH}<br>    - mvn clean test jacoco:report<br>  artifacts:<br>    paths:<br>      - ${PROJECT_PATH}/target/site/jacoco/<br>      - ${PROJECT_PATH}/target/surefire-reports/<br>    reports:<br>      junit: ${PROJECT_PATH}/target/surefire-reports/TEST-*.xml<br>  cache:<br>    paths:<br>      - /gitlab/m2/repository</pre><p>This job runs all unit tests and generates a JaCoCo coverage report. The use of Maven’s local repository caching speeds up subsequent builds.</p><h3>2. Code Coverage</h3><p>Code coverage is a critical metric that helps identify untested parts of your codebase.</p><pre>.code_coverage:<br>  stage: test<br>  needs:<br>    - job: unit_tests<br>      artifacts: true<br>  image: maven:3.8.1-openjdk-11-slim<br>  script:<br>    - cd ${PROJECT_PATH}<br>    - if [ -f target/site/jacoco/jacoco.csv ]; then<br>        awk -F&quot;,&quot; &#39;{ instructions += $4 + $5; covered += $5 } END { print covered, &quot;/&quot;, instructions, &quot; instructions covered&quot;; print 100*covered/instructions, &quot;% covered&quot; }&#39; target/site/jacoco/jacoco.csv;<br>      else<br>        echo &quot;No coverage data found. Ensure unit tests job completed successfully.&quot;;<br>        exit 1;<br>      fi<br>  coverage: &#39;/([0-9]{1,3}.[0-9]*).covered/&#39;<br>  artifacts:<br>    reports:<br>      coverage_report:<br>        coverage_format: cobertura<br>        path: ${PROJECT_PATH}/target/site/jacoco/jacoco.xml</pre><p>This job processes the JaCoCo report, calculating the overall coverage percentage. It also generates a Cobertura-format report for GitLab’s built-in coverage visualization.</p><h3>3. Code Quality Analysis</h3><p>Code quality analysis helps maintain consistent coding standards and identify potential issues.</p><pre>.code_quality:<br>  stage: test<br>  image: docker:20.10.12<br>  allow_failure: true<br>  services:<br>    - name: &#39;docker:20.10.12-dind&#39;<br>      command: [&#39;--tls=false&#39;, &#39;--host=tcp://0.0.0.0:2375&#39;]<br>  variables:<br>    DOCKER_DRIVER: overlay2<br>    CODE_QUALITY_IMAGE: &quot;$CI_TEMPLATE_REGISTRY_HOST/gitlab-org/ci-cd/codequality:$CODE_QUALITY_IMAGE_TAG&quot;<br>  script:<br>    - export SOURCE_CODE=${SOURCE_CODE:-$PWD}<br>    - docker pull --quiet &quot;$CODE_QUALITY_IMAGE&quot;<br>    - docker run --rm <br>        --volume &quot;$PWD&quot;:/code <br>        --volume &quot;$DOCKER_SOCKET_PATH&quot;:/var/run/docker.sock <br>        &quot;$CODE_QUALITY_IMAGE&quot; /code<br>  artifacts:<br>    reports:<br>      codequality: gl-code-quality-report.json<br>    expire_in: 1 week</pre><p>This job uses GitLab’s Code Quality image to analyze the codebase and generate a detailed report. It helps identify code smells, complexity issues, and potential bugs.</p><h3>4. Dependency Scanning</h3><p>Dependency scanning is crucial for identifying vulnerabilities in third-party libraries.</p><pre>.dependency_scan:<br>  stage: test<br>  image: maven:3.8.1-openjdk-11-slim<br>  variables:<br>    MAVEN_OPTS: &quot;-Dmaven.repo.local=/gitlab/m2/repository&quot;<br>    NVD_API_KEY: ${NVD_API_KEY}<br>  script:<br>    - cd ${PROJECT_PATH}<br>    - mvn org.owasp:dependency-check-maven:check<br>  artifacts:<br>    paths:<br>      - ${PROJECT_PATH}/target/dependency-check-report.html<br>    reports:<br>      junit: ${PROJECT_PATH}/target/dependency-check-report.xml<br>  allow_failure: true<br>  cache:<br>    paths:<br>      - /gitlab/m2/repository<br>      - ${PROJECT_PATH}/.dependency-check-cache</pre><p>This job uses OWASP Dependency-Check to scan project dependencies for known vulnerabilities. It generates both HTML and XML reports for easy review.</p><h3>5. Static Application Security Testing (SAST)</h3><p>SAST helps identify potential security vulnerabilities in the source code.</p><pre>.sast:<br>  stage: test<br>  image: maven:3.8.1-openjdk-11-slim<br>  variables:<br>    MAVEN_OPTS: &quot;-Dmaven.repo.local=/gitlab/m2/repository&quot;<br>    NVD_API_KEY: ${NVD_API_KEY}<br>  script:<br>    - cd ${PROJECT_PATH}<br>    - mvn com.github.spotbugs:spotbugs-maven-plugin:check<br>  artifacts:<br>    paths:<br>      - ${PROJECT_PATH}/target/spotbugsXml.xml<br>  cache:<br>    paths:<br>      - /gitlab/m2/repository</pre><p>This job uses SpotBugs to perform static analysis, identifying potential bugs and security issues in the Java code.</p><h3>Integrating with pom.xml</h3><p>To support these CI/CD processes, we need to configure our pom.xml file appropriately. Here are the key additions:</p><pre>&lt;dependencies&gt;<br>  &lt;!-- JUnit 5 dependencies --&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>    &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;<br>    &lt;version&gt;${junit.version}&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>    &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;<br>    &lt;version&gt;${junit.version}&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;!-- Mockito for mocking --&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.mockito&lt;/groupId&gt;<br>    &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;<br>    &lt;version&gt;${mockito.version}&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.mockito&lt;/groupId&gt;<br>    &lt;artifactId&gt;mockito-junit-jupiter&lt;/artifactId&gt;<br>    &lt;version&gt;${mockito.version}&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><pre>&lt;build&gt;<br>  &lt;plugins&gt;<br>    &lt;plugin&gt;<br>      &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>      &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>      &lt;version&gt;2.22.2&lt;/version&gt;<br>    &lt;/plugin&gt;<br>    &lt;!-- JaCoCo Plugin for code coverage --&gt;<br>    &lt;plugin&gt;<br>      &lt;groupId&gt;org.jacoco&lt;/groupId&gt;<br>      &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;<br>      &lt;version&gt;0.8.7&lt;/version&gt;<br>      &lt;executions&gt;<br>        &lt;execution&gt;<br>          &lt;goals&gt;<br>            &lt;goal&gt;prepare-agent&lt;/goal&gt;<br>          &lt;/goals&gt;<br>        &lt;/execution&gt;<br>        &lt;execution&gt;<br>          &lt;id&gt;report&lt;/id&gt;<br>          &lt;phase&gt;test&lt;/phase&gt;<br>          &lt;goals&gt;<br>            &lt;goal&gt;report&lt;/goal&gt;<br>          &lt;/goals&gt;<br>        &lt;/execution&gt;<br>      &lt;/executions&gt;<br>    &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p>These configurations ensure that JUnit 5, Mockito, and JaCoCo are properly set up for our testing and code coverage needs.</p><h3>Advantages of This Approach</h3><ol><li><strong>Comprehensive Quality Assurance</strong>: By integrating multiple types of tests and analyses, we ensure a thorough evaluation of code quality and security.</li><li><strong>Early Detection of Issues</strong>: Running these checks in the CI/CD pipeline allows for early detection of bugs, vulnerabilities, and quality issues.</li><li><strong>Consistent Code Standards</strong>: Automated code quality checks ensure that all code meets predefined standards, regardless of who wrote it.</li><li><strong>Enhanced Security</strong>: Regular dependency scanning and SAST help identify and mitigate security vulnerabilities promptly.</li><li><strong>Improved Developer Productivity</strong>: Automated testing and quality checks free developers from manual review tasks, allowing them to focus on writing code.</li><li><strong>Continuous Improvement</strong>: Regular feedback from these tools helps developers learn and improve their coding practices over time.</li><li><strong>Streamlined Review Process</strong>: With automated checks in place, code reviews can focus on higher-level concerns rather than catching basic issues.</li><li><strong>Confidence in Releases</strong>: A comprehensive suite of tests and checks provides confidence that the code is ready for deployment.</li><li><strong>Compliance Support</strong>: For projects requiring compliance with specific standards, these automated checks can help ensure and demonstrate adherence.</li></ol><h3>Conclusion</h3><p>Implementing a robust CI/CD pipeline with integrated quality and security checks is a powerful way to enhance software development practices. This approach not only improves code quality and security but also streamlines the development process, leading to faster, more reliable releases.</p><p>By leveraging GitLab’s CI/CD capabilities and integrating tools like JUnit, JaCoCo, OWASP Dependency-Check, and SpotBugs, we’ve created a comprehensive quality assurance system. This pipeline serves as a guardian, ensuring that only high-quality, secure code progresses through the development lifecycle.</p><p>As software development continues to evolve, adopting such comprehensive CI/CD practices will become increasingly crucial for teams aiming to deliver high-quality software efficiently and securely.</p><p><a href="https://gitlab.com/ankit630/unixcloudfusion-devops-solutions.git">You can find the complete code for this pipeline in our GitLab repository</a>:</p><p><a href="https://gitlab.com/ankit630/unixcloudfusion-devops-solutions.git">https://gitlab.com/ankit630/unixcloudfusion-devops-solutions.git</a><br><a href="https://github.com/ankit630/unixcloudfusion-devops-solutions.git">https://github.com/ankit630/unixcloudfusion-devops-solutions.git</a></p><p><strong>Example Pipeline</strong></p><p><a href="https://gitlab.com/ankit630/unixcloudfusion-devops-solutions/-/pipelines/1445315404">https://gitlab.com/ankit630/unixcloudfusion-devops-solutions/-/pipelines/1445315404</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b91d098b4b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing GitLab CI/CD Pipelines with Amazon EFS: A Comprehensive Guide to Maven Dependency…]]></title>
            <link>https://medium.com/@ankit630/optimizing-gitlab-ci-cd-pipelines-with-amazon-efs-a-comprehensive-guide-to-maven-dependency-364babaa96ac?source=rss-950bae0c7d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/364babaa96ac</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitlab-runner]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Ankit Mittal]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 07:59:13 GMT</pubDate>
            <atom:updated>2024-09-08T07:59:13.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing GitLab CI/CD Pipelines with Amazon EFS: A Comprehensive Guide to Maven Dependency Caching</h3><h3>Introduction</h3><p>In the fast-paced world of software development, the efficiency of your Continuous Integration and Continuous Deployment (CI/CD) pipeline can make or break your team’s productivity. One of the most common bottlenecks in Java-based projects is the time spent downloading Maven dependencies during each build. This article presents a comprehensive solution to this problem by leveraging Amazon Elastic File System (EFS) to create a persistent cache for Maven dependencies in GitLab CI/CD pipelines.</p><p>For all the relevant code for this implementation <br><a href="https://gitlab.com/ankit630/unixcloudfusion-devops-solutions.git">https://gitlab.com/ankit630/unixcloudfusion-devops-solutions.git</a><br><a href="https://github.com/ankit630/unixcloudfusion-devops-solutions.git">https://github.com/ankit630/unixcloudfusion-devops-solutions.git</a></p><h3>The Challenge: The Hidden Cost of Dependency Downloads</h3><p>Every Java developer is familiar with the scenario: you push a commit, trigger a build, and then wait… and wait… as Maven downloads dependencies from remote repositories. This process, while necessary, can significantly slow down your CI/CD pipeline, especially for projects with numerous dependencies or in environments with slower internet connections.</p><p>To illustrate this point, let’s look at a real-world example from one of our projects:</p><p><a href="https://gitlab.com/ankit630/unixcloudfusion-devops-solutions/-/jobs/7770893214">Build Job Without Caching</a></p><p>In this job, the total build time was a substantial 53.178 seconds. A significant portion of this time was spent downloading dependencies that had likely been downloaded in previous builds. This redundancy not only slows down individual builds but can also lead to increased costs and reduced overall team productivity.</p><h3>The Solution: Persistent Caching with Amazon EFS</h3><p>To address this issue, we implemented a solution using Amazon Elastic File System (EFS). EFS provides scalable, elastic file storage for use with Amazon EC2 instances. By mounting an EFS volume to our GitLab Runner and configuring Maven to use this volume as its local repository, we can preserve dependencies between builds, significantly reducing download times in subsequent runs.</p><p>Here’s a high-level overview of our solution:</p><ol><li>Create an Amazon EFS file system</li><li>Configure the GitLab Runner to mount the EFS volume</li><li>Update the Maven settings to use the EFS mount point as its local repository</li></ol><p>After implementing this solution, the results were dramatic. The same job that previously took over 53 seconds now completed in just 11.791 seconds:</p><p><a href="https://gitlab.com/ankit630/unixcloudfusion-devops-solutions/-/jobs/7770895153">Build Job With EFS Caching</a></p><p>As you can see in the job logs, dependencies were not downloaded again, resulting in a significant time saving of over 75%.</p><h3>Detailed Implementation Guide</h3><p>Let’s walk through the key steps to set up this optimization in your own environment.</p><h3>Step 1: Create an Amazon EFS File System</h3><p>First, you’ll need to create an EFS file system in your AWS account. While you can do this manually through the AWS Console, we recommend using Infrastructure as Code tools like Terraform for better reproducibility and version control.</p><p>Here’s a sample Terraform configuration for creating an EFS file system:</p><pre>resource &quot;aws_efs_file_system&quot; &quot;gitlab_runner_cache&quot; {<br>  creation_token = &quot;gitlab-runner-cache&quot;<br>  encrypted      = true<br><br>  tags = {<br>    Name = &quot;GitLab Runner Cache&quot;<br>  }<br>}<br><br>resource &quot;aws_efs_mount_target&quot; &quot;gitlab_runner_cache&quot; {<br>  count           = length(var.subnet_ids)<br>  file_system_id  = aws_efs_file_system.gitlab_runner_cache.id<br>  subnet_id       = var.subnet_ids[count.index]<br>  security_groups = [aws_security_group.efs.id]<br>}</pre><h3>Step 2: Configure GitLab Runner</h3><p>Next, you’ll need to update your GitLab Runner configuration to mount the EFS volume. This is typically done in the values.yaml file if you&#39;re using the GitLab Runner Helm chart.</p><p>Here’s an example configuration:</p><pre>runners:<br>  config: |<br>    [[runners]]<br>      [runners.kubernetes]<br>        [runners.kubernetes.volumes]<br>          [[runners.kubernetes.volumes.pvc]]<br>            name = &quot;gitlab-runner-efs-pvc&quot;<br>            mount_path = &quot;/gitlab&quot;</pre><p>You’ll also need to create a PersistentVolume and PersistentVolumeClaim for the EFS volume. Here’s an example:</p><pre>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: gitlab-runner-efs-pv<br>spec:<br>  capacity:<br>    storage: 5Gi<br>  volumeMode: Filesystem<br>  accessModes:<br>    - ReadWriteMany<br>  persistentVolumeReclaimPolicy: Retain<br>  storageClassName: efs-sc<br>  csi:<br>    driver: efs.csi.aws.com<br>    volumeHandle: fs-xxxxxxxx # Replace with your EFS ID<br><br>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: gitlab-runner-efs-pvc<br>  namespace: gitlab-runner<br>spec:<br>  accessModes:<br>    - ReadWriteMany<br>  storageClassName: efs-sc<br>  resources:<br>    requests:<br>      storage: 5Gi</pre><h3>Step 3: Update Maven Settings</h3><p>Create a settings.xml file in your project repository to tell Maven to use the EFS mount point as its local repository:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;settings xmlns=&quot;http://maven.apache.org/SETTINGS/1.0.0&quot;&gt;<br>    &lt;localRepository&gt;/gitlab/m2/repository&lt;/localRepository&gt;<br>&lt;/settings&gt;</pre><h3>Step 4: Update GitLab CI Configuration</h3><p>Modify your .gitlab-ci.yml file to use the custom Maven settings:</p><pre>build:<br>  stage: build<br>  image: maven:3.8.1-openjdk-11-slim<br>  script:<br>    - mvn clean package -s settings.xml<br>  artifacts:<br>    paths:<br>      - target/*.war</pre><h3>Automating the Setup</h3><p>To streamline the setup process, we’ve created a shell script that automates much of the configuration. This script creates the necessary AWS resources (S3 bucket for Terraform state and DynamoDB table for state locking) and generates a Terraform backend configuration file.</p><p>You can find this script in our repository:</p><p>Here’s how to use it:</p><ol><li>Clone the repository:</li></ol><pre>git clone https://gitlab.com/ankit630/unixcloudfusion-devops-solutions.git<br>git clone https://github.com/ankit630/unixcloudfusion-devops-solutions.git</pre><p>2. Follow the steps below to build everything in automated way</p><pre>PRE STEPS:-<br># You can entire setup from the Cloudshell in a new account in few mins<br># Open cloudshell and setup access key and secret key to speed up setting <br># process<br># Alternatively you can setup on local machine or ec2 using role or access<br># key<br># Fork the Gitlab repository as it will alow you to modify account id and efs id<br># according to your setup<br><br># Setup a EKS Cluster if you dont have already<br>cd unixcloudfusion-devops-solutions/aws/EKS/install-eks<br>bash create-eks-cluster.sh      # Creates EKS Cluster<br><br># Setup Argocd to implement gitops<br>cd unixcloudfusion-devops-solutions/argocd<br>bash install-argocd.sh   #Argocd login password is available in file argocd-admin-password.txt<br><br># Setup Secretsmanager which will hold the token for Gitlab<br>cd unixcloudfusion-devops-solutions/argocd<br>bash install-gitlab-secretsmanager.sh  # Install External Secrets operator<br><br># Install Terraform and state setup for creating EFS <br>cd unixcloudfusion-devops-solutions/setup_terraform/scripts<br>bash setup_terraform_backend.sh       # Setup Terraform backend<br><br># Create the EFS Volume for maven application todoapp which we will build<br>cd unixcloudfusion-devops-solutions/aws/efs/todoapp<br>bash setup_efs.sh<br><br># Note the EFS_ID output from the terraform run<br># update EFS_ID in both places<br>unixcloudfusion-devops-solutions/gitlab-runner/resources/efs-provisioner.yaml<br># update the account-id of your aws account in roel of gitlab runner in<br>unixcloudfusion-devops-solutions/gitlab-runner/values.yaml<br><br># Next go to Gitlab account<br># Select group runner or project runner<br># Create a token for the runner this would be needed when you execute script<br><br># Create the Gitlab runner<br>unixcloudfusion-devops-solutions/gitlab-runner/setup-gitlab-runner.sh<br># Script will ask for token as input, enter the token which will copy it to<br>secrets manager and replicated in eks using secrets operator so runner can use<br>token for authorization<br><br># once completed can login to Argocd to check health of gitlab runner<br># Go to runner and verify if the runner is healthy<br><br># Now you can trigger the build and verify<br><br># First time you trigger EFS Volume wont have packages so more time is needed<br># also packagaes will be downloaded as well<br>https://gitlab.com/ankit630/unixcloudfusion-devops-solutions/-/jobs/7770893214<br><br># Next time the build time will reduce significantly more than 70% and packages<br># wont be downloaded again<br>https://gitlab.com/ankit630/unixcloudfusion-devops-solutions/-/jobs/7770895153<br><br># this way you can optimize your Gitlab pipeline and use EFS Volume as cache.<br><br><br><br><br></pre><h3>Understanding the Performance Improvement</h3><p>Let’s take a closer look at why this solution provides such a significant performance boost.</p><p>In a traditional setup, every time a build runs, Maven needs to download all the project dependencies from remote repositories. This process is time-consuming and network-intensive, especially for large projects with many dependencies.</p><p>With our EFS-based solution, here’s what happens:</p><ol><li>On the first run, Maven downloads the dependencies as usual and stores them in the local repository on the EFS volume.</li><li>On subsequent runs, Maven checks the local repository first. Since the dependencies are already there (persisted on the EFS volume), it doesn’t need to download them again.</li><li>This not only saves time but also reduces network usage and potential points of failure due to network issues.</li></ol><p>The time savings can be substantial. In our example, we saw a reduction from 53.178 seconds to 11.791 seconds — a 77.8% improvement!</p><h3>Best Practices and Considerations</h3><p>While this solution can significantly improve your build times, there are a few best practices and considerations to keep in mind:</p><ol><li><strong>Security</strong>: Ensure that your EFS volume is properly secured. Use encryption at rest and in transit, and configure your security groups to allow access only from your GitLab runners.</li><li><strong>Monitoring</strong>: Keep an eye on your EFS usage. Set up CloudWatch alerts to notify you if you’re approaching storage limits.</li><li><strong>Cleanup</strong>: Implement a cleanup strategy to occasionally purge old or unused dependencies from your EFS volume. This can prevent your storage costs from growing unnecessarily over time.</li><li><strong>Consistency</strong>: Make sure all your runners are configured to use the EFS volume. Inconsistent configurations can lead to unpredictable build behavior.</li><li><strong>Backup</strong>: Regularly backup your EFS volume to protect against data loss.</li></ol><h3>Conclusion</h3><p>By implementing this EFS-based caching solution for Maven dependencies, we were able to dramatically reduce our GitLab CI/CD pipeline execution times. This improvement translates to faster feedback for developers, quicker releases, and overall improved efficiency in our development process.</p><p>While we’ve focused on Maven dependencies in this article, the same principle can be applied to other package managers and build tools. The key is to identify repetitive, time-consuming tasks in your pipeline and find ways to persist necessary data between runs.</p><p>Remember, every second saved in your CI/CD pipeline is a second gained in your development process. By optimizing your pipeline, you’re not just saving time — you’re enhancing your entire development workflow, allowing your team to iterate faster and deliver value to your users more quickly.</p><p>We encourage you to try this setup in your own environment. The complete code and configuration files are available in our <a href="https://github.com/ankit630/unixcloudfusion-devops-solutions">GitHub repository</a>. Don’t hesitate to reach out if you have any questions or run into any issues during implementation.</p><p>Have you implemented similar optimizations in your CI/CD pipelines? We’d love to hear about your experiences and any other tips you might have for speeding up build processes. Share your thoughts in the comments below!</p><p>Happy optimizing, and may your builds be ever faster!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=364babaa96ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security Best Practices in AWS: A Comprehensive Guide]]></title>
            <link>https://medium.com/@ankit630/security-best-practices-in-aws-a-comprehensive-guide-a4baa3bd58f0?source=rss-950bae0c7d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4baa3bd58f0</guid>
            <dc:creator><![CDATA[Ankit Mittal]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 12:17:28 GMT</pubDate>
            <atom:updated>2024-08-27T12:17:28.149Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li><a href="#introduction">Introduction</a></li><li><a href="#aws-shared-responsibility-model">AWS Shared Responsibility Model</a></li><li><a href="#identity-and-access-management-iam">Identity and Access Management (IAM)</a></li><li><a href="#network-security">Network Security</a></li><li><a href="#data-protection">Data Protection</a></li><li><a href="#logging-and-monitoring">Logging and Monitoring</a></li><li><a href="#compliance-and-auditing">Compliance and Auditing</a></li><li><a href="#incident-response-and-recovery">Incident Response and Recovery</a></li><li><a href="#devsecops-in-aws">DevSecOps in AWS</a></li><li><a href="#conclusion">Conclusion</a></li></ol><h3>1. Introduction</h3><p>As organizations continue to migrate their infrastructure and applications to the cloud, ensuring robust security measures becomes increasingly critical. Amazon Web Services (AWS) provides a wide array of security tools and features, but it’s essential to understand and implement best practices to safeguard your assets effectively. This article delves into key security considerations and best practices for AWS environments.</p><h3>2. AWS Shared Responsibility Model</h3><p>Before diving into specific practices, it’s crucial to understand the AWS Shared Responsibility Model. This model delineates the security responsibilities between AWS and the customer.</p><pre>+----------------------------------+<br>|        Customer Data             |<br>+----------------------------------+<br>|  Platform, Applications, IAM     |<br>+----------------------------------+<br>|   Operating System, Network &amp;    |<br>|   Firewall Configuration         |<br>+----------------------------------+<br>|   Client-side Data Encryption    |<br>|   Server-side Encryption         |<br>|   Network Traffic Protection     |<br>+==================================+<br>|     Compute    |    Storage      |<br>+----------------------------------+<br>|     Database   |   Networking    |<br>+----------------------------------+<br>|        AWS Global Infrastructure |<br>+----------------------------------+<br><br>Customer Responsibility ^<br>                        |<br>                        |<br>                        v<br>AWS Responsibility</pre><p>AWS is responsible for the security “of” the cloud, while customers are responsible for security “in” the cloud.</p><h3>3. Identity and Access Management (IAM)</h3><p>IAM is the cornerstone of AWS security. Follow these best practices:</p><ol><li><strong>Use the principle of least privilege</strong>: Grant only the permissions necessary to perform a task.</li><li><strong>Implement strong password policies</strong>: Enforce complex passwords and regular rotation.</li><li><strong>Enable Multi-Factor Authentication (MFA)</strong>: Require MFA for all users, especially those with elevated privileges.</li><li><strong>Use IAM roles for EC2 instances</strong>: Avoid storing AWS credentials on instances.</li><li><strong>Regularly audit IAM users and permissions</strong>: Use AWS IAM Access Analyzer to identify unintended access.</li></ol><p>Example IAM policy following the principle of least privilege:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:PutObject&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::my-bucket/*&quot;<br>        }<br>    ]<br>}</pre><h3>4. Network Security</h3><p>Securing your AWS network is crucial. Key practices include:</p><ol><li><strong>Use Virtual Private Clouds (VPCs)</strong>: Isolate your resources in a private network.</li><li><strong>Implement Security Groups and Network ACLs</strong>: Control inbound and outbound traffic.</li><li><strong>Use VPN or AWS Direct Connect for secure communication</strong>: Encrypt data in transit between your on-premises infrastructure and AWS.</li><li><strong>Implement AWS WAF</strong>: Protect your web applications from common web exploits.</li></ol><p>Example Security Group configuration:</p><pre>SecurityGroup:<br>  Type: AWS::EC2::SecurityGroup<br>  Properties:<br>    GroupDescription: Allow HTTP and SSH access<br>    SecurityGroupIngress:<br>      - IpProtocol: tcp<br>        FromPort: 80<br>        ToPort: 80<br>        CidrIp: 0.0.0.0/0<br>      - IpProtocol: tcp<br>        FromPort: 22<br>        ToPort: 22<br>        CidrIp: YOUR_IP_ADDRESS/32</pre><h3>5. Data Protection</h3><p>Protecting data at rest and in transit is paramount. Best practices include:</p><ol><li><strong>Encrypt data at rest</strong>: Use AWS KMS for managing encryption keys.</li><li><strong>Encrypt data in transit</strong>: Use SSL/TLS for all communications.</li><li><strong>Implement S3 bucket policies</strong>: Ensure proper access controls on S3 buckets.</li><li><strong>Use AWS Macie</strong>: Discover, classify, and protect sensitive data.</li></ol><p>Example S3 bucket policy to enforce encryption:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;DenyIncorrectEncryptionHeader&quot;,<br>            &quot;Effect&quot;: &quot;Deny&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:PutObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::my-bucket/*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringNotEquals&quot;: {<br>                    &quot;s3:x-amz-server-side-encryption&quot;: &quot;AES256&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><h3>6. Logging and Monitoring</h3><p>Comprehensive logging and monitoring are essential for maintaining security. Key practices include:</p><ol><li><strong>Enable AWS CloudTrail</strong>: Log API calls across your AWS infrastructure.</li><li><strong>Use Amazon CloudWatch</strong>: Monitor resources and applications.</li><li><strong>Implement AWS Config</strong>: Assess, audit, and evaluate configurations of your AWS resources.</li><li><strong>Set up alerts</strong>: Configure notifications for suspicious activities or policy violations.</li></ol><p>Example CloudWatch alarm configuration:</p><pre>CloudWatchAlarm:<br>  Type: AWS::CloudWatch::Alarm<br>  Properties:<br>    AlarmDescription: Alarm if CPU exceeds 70% for 5 minutes<br>    Namespace: AWS/EC2<br>    MetricName: CPUUtilization<br>    Statistic: Average<br>    Period: 300<br>    EvaluationPeriods: 1<br>    Threshold: 70<br>    AlarmActions:<br>      - !Ref SNSTopic<br>    ComparisonOperator: GreaterThanThreshold</pre><h3>7. Compliance and Auditing</h3><p>Maintaining compliance is crucial for many organizations. AWS provides several tools to help:</p><ol><li><strong>Use AWS Artifact</strong>: Access compliance reports.</li><li><strong>Implement AWS Security Hub</strong>: Comprehensive view of your security alerts and posture.</li><li><strong>Regular security assessments</strong>: Conduct penetration testing (with AWS approval).</li><li><strong>Use AWS Audit Manager</strong>: Continuously audit your AWS usage to simplify risk and compliance assessment.</li></ol><h3>8. Incident Response and Recovery</h3><p>Having a robust incident response plan is crucial. Key considerations include:</p><ol><li><strong>Develop an Incident Response Plan</strong>: Define roles, responsibilities, and procedures.</li><li><strong>Use AWS GuardDuty</strong>: Detect threats and unauthorized behavior.</li><li><strong>Implement AWS Backup</strong>: Ensure you can recover your data in case of an incident.</li><li><strong>Practice your response</strong>: Regularly conduct drills to test your incident response procedures.</li></ol><h3>9. DevSecOps in AWS</h3><p>Integrating security into your DevOps practices is essential:</p><ol><li><strong>Use Infrastructure as Code (IaC)</strong>: Implement AWS CloudFormation or Terraform to version control your infrastructure.</li><li><strong>Implement automated security testing</strong>: Use tools like AWS CodePipeline and AWS CodeBuild to automate security checks.</li><li><strong>Scan container images</strong>: Use Amazon ECR image scanning to detect vulnerabilities.</li><li><strong>Implement least privilege in CI/CD</strong>: Use separate IAM roles for different stages of your pipeline.</li></ol><p>Example AWS CodeBuild configuration for security scanning:</p><pre>CodeBuildProject:<br>    Type: AWS::CodeBuild::Project<br>    Properties:<br>      Name: SecurityScanningProject<br>      ServiceRole: !Ref CodeBuildServiceRole<br>      Artifacts:<br>        Type: NO_ARTIFACTS<br>      Environment:<br>        Type: LINUX_CONTAINER<br>        ComputeType: BUILD_GENERAL1_SMALL<br>        Image: aws/codebuild/amazonlinux2-x86_64-standard:3.0<br>      Source:<br>        Type: GITHUB<br>        Location: https://github.com/your-repo/your-project.git<br>      Triggers:<br>        Webhook: true<br>        FilterGroups:<br>          - - Type: EVENT<br>              Pattern: PUSH<br>      BuildSpec: |<br>        version: 0.2<br>        phases:<br>          build:<br>            commands:<br>              - npm install<br>              - npm run security-scan</pre><h3>10. Conclusion</h3><p>Securing your AWS environment is an ongoing process that requires vigilance, regular auditing, and staying up-to-date with the latest security features and best practices. By implementing the strategies outlined in this article, you can significantly enhance your security posture in AWS.</p><p>Remember, security in the cloud is a shared responsibility. While AWS provides a secure infrastructure and many tools to help you protect your assets, it’s ultimately up to you to use these tools effectively and maintain secure configurations and practices.</p><p>Stay informed about the latest security updates from AWS, regularly review and update your security measures, and foster a culture of security awareness within your organization. With these practices in place, you can confidently leverage the power of AWS while maintaining a robust security posture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4baa3bd58f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Tuning for EKS Clusters: A Comprehensive Guide]]></title>
            <link>https://medium.com/@ankit630/performance-tuning-for-eks-clusters-a-comprehensive-guide-2182294812ce?source=rss-950bae0c7d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2182294812ce</guid>
            <dc:creator><![CDATA[Ankit Mittal]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 12:13:15 GMT</pubDate>
            <atom:updated>2024-08-27T12:13:15.687Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li><a href="#introduction">Introduction</a></li><li><a href="#understanding-eks-architecture">Understanding EKS Architecture</a></li><li><a href="#key-performance-metrics">Key Performance Metrics</a></li><li><a href="#cluster-level-optimizations">Cluster-Level Optimizations</a></li><li><a href="#node-level-optimizations">Node-Level Optimizations</a></li><li><a href="#application-level-optimizations">Application-Level Optimizations</a></li><li><a href="#monitoring-and-observability">Monitoring and Observability</a></li><li><a href="#best-practices-and-common-pitfalls">Best Practices and Common Pitfalls</a></li><li><a href="#conclusion">Conclusion</a></li></ol><h3>1. Introduction</h3><p>Amazon Elastic Kubernetes Service (EKS) has become a go-to solution for organizations looking to run containerized workloads at scale. However, as with any distributed system, performance tuning is crucial to ensure optimal resource utilization and cost-effectiveness. This article delves into the intricacies of performance tuning for EKS clusters, providing actionable insights and best practices for DevOps engineers and SREs.</p><h3>2. Understanding EKS Architecture</h3><p>Before we dive into performance tuning, it’s essential to understand the architecture of an EKS cluster. Here’s a high-level diagram</p><pre>+---------------------+<br>|    EKS Control Plane |<br>|  +----------------+  |<br>|  | API Server     |  |<br>|  | Scheduler      |  |<br>|  | etcd           |  |<br>|  +----------------+  |<br>+---------------------+<br>          |<br>          | VPC Peering<br>          |<br>+---------------------+<br>|   Worker Nodes      |<br>| +------------------+|<br>| | kubelet          ||<br>| | container runtime||<br>| | kube-proxy       ||<br>| +------------------+|<br>| +------------------+|<br>| | Pods             ||<br>| |  +------------+  ||<br>| |  |Containers  |  ||<br>| |  +------------+  ||<br>| +------------------+|<br>+---------------------+</pre><p>This architecture highlights the separation between the EKS-managed control plane and the worker nodes running in your VPC. Understanding this separation is crucial for effective performance tuning.</p><h3>3. Key Performance Metrics</h3><p>When tuning EKS clusters, focus on these key metrics:</p><ol><li>CPU Utilization</li><li>Memory Usage</li><li>Network Throughput</li><li>Disk I/O</li><li>API Server Latency</li><li>etcd Performance</li><li>Pod Startup Time</li></ol><p>These metrics provide a holistic view of your cluster’s health and performance.</p><h3>4. Cluster-Level Optimizations</h3><h3>4.1 Right-sizing the Cluster</h3><p>One of the most impactful optimizations is ensuring your cluster is properly sized. Use tools like the Kubernetes Vertical Pod Autoscaler (VPA) to right-size your pods, and the Horizontal Pod Autoscaler (HPA) to adjust the number of pod replicas based on demand.</p><p>Example HPA configuration:</p><pre>apiVersion: autoscaling/v2beta1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: my-app-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: my-app<br>  minReplicas: 2<br>  maxReplicas: 10<br>  metrics:<br>  - type: Resource<br>    resource:<br>      name: cpu<br>      targetAverageUtilization: 50</pre><h3>4.2 Optimizing etcd Performance</h3><p>etcd is the backbone of Kubernetes, storing all cluster data. To optimize etcd:</p><ol><li>Use SSDs for etcd storage</li><li>Implement proper backup and restore procedures</li><li>Monitor and tune etcd metrics</li></ol><h3>5. Node-Level Optimizations</h3><h3>5.1 Instance Type Selection</h3><p>Choose the right EC2 instance type for your workloads. Consider using:</p><ul><li>C5 instances for compute-intensive workloads</li><li>R5 instances for memory-intensive applications</li><li>M5 instances for balanced workloads</li></ul><h3>5.2 Kernel Tuning</h3><p>Optimize the Linux kernel parameters for container workloads:</p><pre># Add to /etc/sysctl.conf<br>net.ipv4.ip_forward = 1<br>net.bridge.bridge-nf-call-iptables = 1<br>fs.inotify.max_user_watches = 1048576<br>vm.max_map_count = 262144</pre><h3>6. Application-Level Optimizations</h3><h3>6.1 Resource Requests and Limits</h3><p>Set appropriate resource requests and limits for your pods:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: frontend<br>spec:<br>  containers:<br>  - name: app<br>    image: images.my-company.example/app:v4<br>    resources:<br>      requests:<br>        memory: &quot;64Mi&quot;<br>        cpu: &quot;250m&quot;<br>      limits:<br>        memory: &quot;128Mi&quot;<br>        cpu: &quot;500m&quot;</pre><h3>6.2 Liveness and Readiness Probes</h3><p>Implement proper liveness and readiness probes to ensure efficient scheduling and fast recovery from failures:</p><pre>livenessProbe:<br>  httpGet:<br>    path: /healthz<br>    port: 8080<br>  initialDelaySeconds: 3<br>  periodSeconds: 3<br>readinessProbe:<br>  httpGet:<br>    path: /ready<br>    port: 8181<br>  periodSeconds: 5</pre><h3>7. Monitoring and Observability</h3><p>Implement a robust monitoring solution using tools like Prometheus and Grafana. Here’s a sample Prometheus configuration for scraping Kubernetes metrics:</p><pre>global:<br>  scrape_interval: 15s</pre><pre>scrape_configs:<br>  - job_name: &#39;kubernetes-apiservers&#39;<br>    kubernetes_sd_configs:<br>    - role: endpoints<br>    scheme: https<br>    tls_config:<br>      ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt<br>    bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token<br>    relabel_configs:<br>    - source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]<br>      action: keep<br>      regex: default;kubernetes;https</pre><h3>8. Best Practices and Common Pitfalls</h3><ul><li>Regularly update EKS and node versions</li><li>Use managed node groups for easier management</li><li>Implement proper network policies</li><li>Avoid over-provisioning resources</li><li>Be cautious with custom kernels or runtime</li></ul><h3>9. Conclusion</h3><p>Performance tuning EKS clusters is an ongoing process that requires a deep understanding of both Kubernetes and AWS infrastructure. By following the strategies outlined in this article, you can significantly improve the performance, reliability, and cost-effectiveness of your EKS deployments.</p><p>Remember, the key to successful performance tuning is continuous monitoring, iterative improvements, and staying up-to-date with the latest best practices in the rapidly evolving Kubernetes ecosystem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2182294812ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>