<?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 Aniruddha Jawanjal on Medium]]></title>
        <description><![CDATA[Stories by Aniruddha Jawanjal on Medium]]></description>
        <link>https://medium.com/@iamaniruddhaj?source=rss-b26e9700ec72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Egg8wWDUxQXhUDw6C7QhKg.png</url>
            <title>Stories by Aniruddha Jawanjal on Medium</title>
            <link>https://medium.com/@iamaniruddhaj?source=rss-b26e9700ec72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:30:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamaniruddhaj/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[Fixing Critical Java CVEs in New Relic’s Infrastructure Bundle: A Practical Guide]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@iamaniruddhaj/fixing-critical-java-cves-in-new-relics-infrastructure-bundle-a-practical-guide-934119193079?source=rss-b26e9700ec72------2"><img src="https://cdn-images-1.medium.com/max/1412/1*gaol7Auoyxh1UfE3l51mew.png" width="1412"></a></p><p class="medium-feed-snippet">TL;DR</p><p class="medium-feed-link"><a href="https://medium.com/@iamaniruddhaj/fixing-critical-java-cves-in-new-relics-infrastructure-bundle-a-practical-guide-934119193079?source=rss-b26e9700ec72------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@iamaniruddhaj/fixing-critical-java-cves-in-new-relics-infrastructure-bundle-a-practical-guide-934119193079?source=rss-b26e9700ec72------2</link>
            <guid isPermaLink="false">https://medium.com/p/934119193079</guid>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[new-relic]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cve]]></category>
            <dc:creator><![CDATA[Aniruddha Jawanjal]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 07:24:21 GMT</pubDate>
            <atom:updated>2026-01-29T07:32:40.762Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building Infrapause]]></title>
            <link>https://medium.com/@iamaniruddhaj/building-infrapause-72a79448d6fc?source=rss-b26e9700ec72------2</link>
            <guid isPermaLink="false">https://medium.com/p/72a79448d6fc</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[infrapause]]></category>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <dc:creator><![CDATA[Aniruddha Jawanjal]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 18:37:47 GMT</pubDate>
            <atom:updated>2025-12-28T18:37:47.061Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://infrapause.io/">Pause idle cloud infrastructure automatically and save real money | Infrapause</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqS2faHPUd7IhsxhP8Bl0g.png" /></figure><h3>Why I’m Building Infrapause: Lessons From a Decade in DevOps</h3><p>After more than a decade in DevOps, you start noticing patterns. Not the glamorous ones we talk about at conferences; but the quiet, expensive, deeply inefficient ones that everyone just accepts as “how things are.”</p><p><a href="https://infrapause.io/">Infrapause</a> was born out of one such pattern.</p><h3>The Problem Nobody Owns</h3><p>Over the years, I’ve worked with startups, scale-ups, and enterprises. Different sizes, different industries; but one thing was always consistent:</p><p><strong>Cloud infrastructure runs far longer than it needs to.</strong></p><ul><li>Non-production environments running all night</li><li>QA stacks alive over weekends</li><li>Forgotten EC2s, RDS snapshots, idle NAT gateways</li><li>Teams “meaning to clean up” but never quite getting to it</li></ul><p>Everyone <em>knows</em> this happens. No one feels responsible enough to fix it properly.</p><p>Finance teams see the bill but don’t understand the infrastructure.<br>Engineering teams understand the infrastructure but aren’t incentivized to reduce spend.<br>Founders are busy shipping product and raising the next round.</p><p>The result?<br>Thousands of dollars burned every month. silently. <br>The cost is real, but it’s abstract.</p><h3>“Just Use Scripts” (And Why That Doesn’t Work)</h3><p>The common advice is:</p><blockquote><em>“Just write a Lambda.”<br>“Use cron.”<br>“Add lifecycle rules.”</em></blockquote><p>I’ve done all of that. Many times.</p><p>Here’s what actually happens in the real world:</p><ul><li>Scripts break when infra changes</li><li>Cron jobs run twice when containers scale</li><li>One-off Lambdas have no UI, no visibility, no ownership</li><li>Nobody knows <em>what</em> is paused, <em>why</em>, or <em>by whom</em></li></ul><p>Six months later, the original engineer has left the company and everyone is afraid to touch the automation.</p><p>So infra stays on. Bills keep coming.</p><h3>The Moment It Clicked</h3><p>At some point I realized:<br><strong>This is not a scripting problem. It’s a product problem.</strong></p><p>Teams don’t need more YAML.<br>They need:</p><ul><li>Visibility</li><li>Guardrails</li><li>Confidence</li><li>An audit trail</li><li>And something they can trust to “just work”</li></ul><p>That’s when the idea for <a href="https://infrapause.io/"><strong>Infrapause</strong></a> started taking shape.</p><h3>What Infrapause Is (And Isn’t)</h3><p><a href="https://infrapause.io/">Infrapause</a> is not a cost-optimization dashboard.<br>It’s not another FinOps tool that tells you <em>after the fact</em> that you spent too much.</p><p><a href="https://infrapause.io/">Infrapause</a> is simple by design:</p><blockquote><strong><em>Automatically pause cloud infrastructure when it’s not needed — and resume it when it is.</em></strong></blockquote><ul><li>Nights</li><li>Weekends</li><li>Holidays</li><li>On-demand</li></ul><p>With clear visibility into:</p><ul><li>What’s running</li><li>What’s paused</li><li>How much you’ve saved because of it</li></ul><p>No Kubernetes complexity.<br>No invasive agents.<br>No fragile cron hacks.</p><h3>Why I’m Building This Now</h3><p>A few personal reasons made this the right time:</p><ol><li><strong>I’ve seen this problem enough times</strong><br>Across companies, teams, and scales — the pain is universal.</li><li><strong>The cloud has matured</strong><br>AWS now has the primitives needed to do this safely and reliably.</li><li><strong>Founders are finally cost-conscious</strong><br>The “growth at all costs” era is over. Efficiency matters again.</li><li><strong>I wanted to build something opinionated</strong><br>Not a generic platform — but a tool that reflects real DevOps experience.</li></ol><h3>The Bigger Vision</h3><p>Long-term, Infrapause isn’t just about saving money.</p><p>It’s about:</p><ul><li>Making cost-awareness part of engineering culture</li><li>Giving teams confidence to automate infra decisions</li><li>Turning “cloud hygiene” into a default, not a chore</li></ul><p>If your infrastructure doesn’t need to run, it shouldn’t.<br>And you shouldn’t need a senior DevOps engineer babysitting it. If your QA wants to start the infrastructure, they should be able to do it: on a click of button or slack message.</p><h3>Still Early, Still Learning</h3><p><a href="https://infrapause.io/">Infrapause</a> is still in beta.<br>I’m actively learning from users, breaking assumptions, and iterating fast.</p><p>But one thing I’m sure of:<br>This problem is real.<br>And it’s worth solving properly.</p><p>If you’ve ever looked at a cloud bill and thought:</p><blockquote><em>“Why is this still running?”</em></blockquote><p>Then <a href="https://infrapause.io/">Infrapause</a> is for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a79448d6fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up Timescale DB extension on Postgres 17]]></title>
            <link>https://medium.com/@iamaniruddhaj/setting-up-timescale-db-extension-on-postgres-17-98ad1605693d?source=rss-b26e9700ec72------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ad1605693d</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[timescaledb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Aniruddha Jawanjal]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 11:15:03 GMT</pubDate>
            <atom:updated>2025-06-09T11:18:08.804Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we will list the commands that we used to setup &amp; enable timescale DB postgres extention on Ubuntu 24.04. We are using t3.medium type instance in Ubuntu. These instructions are taken from Timescale DB documentation and should be referred for non-prod setup.</p><p><a href="https://docs.timescale.com/self-hosted/latest/install/installation-linux/#install-and-configure-timescaledb-on-postgresql">Timescale Documentation | Install TimescaleDB on Linux</a></p><h4>Install Timescale DB extension with Postgres17</h4><p>Install the latest PostgreSQL packages</p><pre>$ sudo apt install gnupg postgresql-common apt-transport-https lsb-release wgetbash</pre><p>Run the PostgreSQL package setup script</p><pre>sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh (Press &quot;Enter&quot;)<br>sudo apt install postgresql-server-dev-17</pre><p>Install the TimescaleDB package</p><pre>$ echo &quot;deb https://packagecloud.io/timescale/timescaledb/ubuntu/ $(lsb_release -c -s) main&quot; | sudo tee /etc/apt/sources.list.d/timescaledb.list<br>$ wget --quiet -O - https://packagecloud.io/timescale/timescaledb/gpgkey | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/timescaledb.gpg<br>$ sudo apt update<br>$ sudo apt install timescaledb-2-postgresql-17 postgresql-client-17</pre><p>Tune the Timescale DB configuration</p><pre>$ sudo timescaledb-tune </pre><p>You can find more details about Timescale tuning prameters here <a href="https://docs.timescale.com/self-hosted/latest/configuration/">https://docs.timescale.com/self-hosted/latest/configuration/</a></p><p>Once completed, tuning parameters will be updated in Postgres config file. In our case <strong>/etc/postgresql/17/main/postgresql.conf </strong>under<strong> </strong>CUSTOMIZED OPTIONS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WmkGlLY8UqubxqnXJl4uA.png" /></figure><p>Restart postgresql &amp; add timescale db extension to Postgres. Check that TimescaleDB is installed</p><pre>$ sudo systemctl restart postgresql<br>$ sudo -u postgres psql              #Login to postgres<br>$ \password postgres                 #Set postgres password<br>$ CREATE EXTENSION IF NOT EXISTS timescaledb; #Add TimescaleDB to the database <br>$ \dx                               # Check that TimescaleDB is installed</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYYZv_vAr_JLs0CiQYQ_nA.png" /></figure><p>Cheers!</p><p>If you need detailed setup for TimescaleDB or any Devops related work, you can reach out to us on <strong><em>aniruddha[at]yantraflow.com</em></strong> or <strong><em>jawanjal.shiva[at]gmail.com</em></strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ad1605693d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Windows server & process monitoring using Prometheus + Grafana]]></title>
            <link>https://medium.com/@iamaniruddhaj/windows-server-process-monitoring-using-prometheus-grafana-19256abbb274?source=rss-b26e9700ec72------2</link>
            <guid isPermaLink="false">https://medium.com/p/19256abbb274</guid>
            <category><![CDATA[prometheus-monitoring]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Aniruddha Jawanjal]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 11:33:42 GMT</pubDate>
            <atom:updated>2025-04-06T11:33:42.877Z</atom:updated>
            <content:encoded><![CDATA[<p>Our client has an existing windows server with different processes running on the system. We needed to set up time series dashboards for these windows processes that can show uptime and disruptions in these services.</p><p>Default windows exporter would give us configuration to monitor most of the hardware and system configurations, but we also need to monitor specific critical processes on the server</p><p><strong>Solution:</strong></p><p>First, We configured the windows exporter to send process uptime data along with timestamps for monitoring. Then we analyzed the uptime data using PromQL queries to create required Grafana visualizations.</p><ul><li>Update Windows exporter configuration to send process data</li></ul><pre>.\windows_exporter.exe --collectors.enabled &quot;[defaults],process&quot;</pre><ul><li>Verify data in Prometheus and design PromQL queries for analysis</li><li>Create Grafana dashboards based on uptime data for specific services</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oq5w4TRePPHDrx2UX4Begg.png" /></figure><p>In above configuration, we are monitoring status of critical process(Stopped/Running). But we can modify this to denote other process status for windows server as well.</p><p>Apart from above service monitoring dashboard, we can also monitor specific processes in the Windows server. For eg., checking if Chrome application is running or not! Windows treats services(Background tasks, like Windows update service) and processes(User specific process, like Chrome).</p><p>Below are some of the sample dashboards we created for monitoring</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHCYiDwcuz-oqWje47L7pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDdiQ6DQ9jzxKVGK1SoD5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxVgPyadiKXQFT6yRtoMDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vX9PRhxRYZapkKMZ_hC08Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z--slvKrWt-QCZjKAAqSQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aj5wMCuWRgiLoTr-C9s49Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19256abbb274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating CloudWatch Log Exports to S3 with AWS Batch: A Serverless Approach]]></title>
            <link>https://medium.com/@iamaniruddhaj/automating-cloudwatch-log-exports-to-s3-with-aws-batch-a-serverless-approach-d3e63a2b21da?source=rss-b26e9700ec72------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3e63a2b21da</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[batch]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloudwatch-logs]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Aniruddha Jawanjal]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 14:05:21 GMT</pubDate>
            <atom:updated>2024-10-21T14:32:37.984Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of cloud computing, log management is a critical aspect of maintaining and troubleshooting applications. Amazon CloudWatch Logs is a popular service for collecting and storing log data, but what if you want to archive these logs in Amazon S3 for long-term storage or analysis? In this post, we’ll explore how to automate the process of exporting CloudWatch logs to S3 using AWS Batch, creating a serverless and scalable solution.</p><p><strong>Note:</strong> This solution helps to upload all log files including the ones with large size. I have tested it with hundreds of logs files with most of them over 20 GB &amp; few over 100 GB. This solution should work for files larger than that as well. I triggered the job manually first time, which ran over two days to upload logs files to S3 — as we were uploading all files from the start for the first time. After that this batch job was triggered daily using Eventbridge Event+Lambda. For optimisation, you can look at parallel processing of this implementation if rate limiting is not a concern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzZKBy0eGI8eanrP2SkXZw.png" /></figure><h3>The Challenge</h3><p>While CloudWatch Logs is great for real-time monitoring and analysis, there are several reasons why you might want to export logs to S3:</p><ol><li>Long-term storage and compliance</li><li>Cost optimization (S3 is generally cheaper for long-term storage)</li><li>Advanced analytics using services like Athena or EMR</li></ol><p>Manually exporting logs is time-consuming and error-prone. We need an automated, scalable solution that can handle large volumes of log data across multiple log groups.</p><h3>Why Lambda Didn’t Work</h3><p>Initially, we attempted to use AWS Lambda for this task. However, we encountered several limitations that made Lambda unsuitable for our use case:</p><ol><li><strong>Execution Time Limit</strong>: Lambda functions have a maximum execution time of 15 minutes. For large log groups or multiple log groups, this often wasn’t enough time to complete the export process.</li><li><strong>Memory Constraints</strong>: Lambda functions are limited to 10GB of memory. For very large log exports, this could be insufficient.</li><li><strong>Concurrent Executions</strong>: Lambda has a default limit on concurrent executions, which could be problematic when trying to export many log groups simultaneously. I tried to execute <strong><em>Lambda with Step functions</em></strong>, but given the sheer number of log groups, troubleshooting this with step functions was a big headache. Though doable, this is simple task which shouldn’t be this complicated to implement.</li><li><strong>Statelessness</strong>: Lambda functions are stateless, making it challenging to track progress across multiple invocations for long-running export tasks. Though, we used SSM to solve this issue.</li></ol><p>These limitations led us to explore alternative solutions, ultimately leading us to AWS Batch.</p><h3>The Solution: AWS Batch</h3><p>AWS Batch is a fully managed batch computing service that allows you to run jobs on a schedule or in response to events. It’s perfect for our use case because:</p><ol><li>It’s serverless, so we don’t need to manage any infrastructure</li><li>It’s scalable, capable of processing large volumes of data</li><li>It integrates well with other AWS services</li><li>It doesn’t have the same time and memory constraints as Lambda</li></ol><pre>LogExportBatchJobRole:<br>    Condition: DevProdOnly<br>    Type: AWS::IAM::Role<br>    Properties:<br>      RoleName: &quot;LogExportBatchJobRole&quot;<br>      AssumeRolePolicyDocument:<br>        Version: &#39;2012-10-17&#39;<br>        Statement:<br>          - Effect: Allow<br>            Principal:<br>              Service: &quot;ecs-tasks.amazonaws.com&quot;<br>            Action: sts:AssumeRole<br>      ManagedPolicyArns:<br>        - arn:aws:iam::aws:policy/service-role/AWSBatchServiceRole<br>        - arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy  # Required for Fargate job execution<br>        - arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess<br>        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore <br>      Policies:<br>        - PolicyName: !Sub ${EnvironmentName}-S3Access<br>          PolicyDocument:<br>            Version: &#39;2012-10-17&#39;<br>            Statement:<br>              - Effect: Allow<br>                Action:<br>                  - s3:GetObject<br>                  - s3:PutObject<br>                  - logs:*<br>                  - ssm:*<br>                Resource: <br>                  - &#39;*&#39;<br><br>LogExportJobDefinition:<br>    Type: AWS::Batch::JobDefinition<br>    Properties:<br>      JobDefinitionName: &quot;LogExportJobDefinition&quot;<br>      Type: &quot;container&quot;<br>      ContainerProperties:<br>        ExecutionRoleArn: !GetAtt LogExportBatchJobRole.Arn<br>        JobRoleArn: !GetAtt LogExportBatchJobRole.Arn<br>        Image: amazonlinux:2<br>        ResourceRequirements:<br>          - Type: VCPU<br>            Value: &quot;2&quot;<br>          - Type: MEMORY<br>            Value: &quot;4096&quot;<br>        Environment:  <br>          - Name: DESTINATION_BUCKET<br>            Value: &lt;s3-bucket-to-store-logs&gt;<br>          - Name: SCRIPT_BUCKET<br>            Value: &lt;s3-bucket-to-store-python-script-with-log-export-logic&gt;<br>          - Name: SCRIPT_KEY<br>            Value: scripts/export_logs.py<br>          - Name: RETENTION_DAYS<br>            Value: &quot;365&quot;<br>        Command:<br>          - /bin/bash<br>          - -c<br>          - |<br>            yum install -y awscli<br>            yum install -y python3 pip<br>            pip3 install boto3<br>            aws s3 cp s3://${SCRIPT_BUCKET}/${SCRIPT_KEY} .<br>            python3 export_logs.py<br>        LogConfiguration:<br>          LogDriver: awslogs<br>          Options:<br>            awslogs-group: !Sub &quot;/aws/batch/logs/LogExportJobDefinition&quot;<br>            awslogs-region: !Ref &quot;AWS::Region&quot;<br>            awslogs-stream-prefix: &quot;fargate&quot;<br>      PlatformCapabilities:<br>        - FARGATE<br>      RetryStrategy:<br>        Attempts: 3</pre><h3>The Export Script</h3><p>The heart of our solution is the Python script that actually performs the log export. Here’s an overview of its key functionalities:</p><ol><li><strong>Log Group Discovery</strong>: The script uses the CloudWatch Logs API to discover all log groups in the account.</li><li><strong>Retention Policy Setting</strong>: For each log group, it sets the retention policy according to the specified RETENTION_DAYS environment variable.</li><li><strong>Export Task Creation</strong>: It creates an export task for each log group, exporting logs to the specified S3 bucket.</li><li><strong>Progress Tracking</strong>: The script uses SSM Parameters to track the last export time for each log group, ensuring we only export new logs in subsequent runs.</li><li><strong>Error Handling and Retries</strong>: The script includes robust error handling and retry logic to deal with API limits and transient failures.</li></ol><p>Create a job definition to run the script:</p><p>I could have used an image and push it to ECR but I wanted to avoid the additional dependency</p><p>Here’s a snippet of the core export logic <strong><em>export_logs.py</em></strong></p><pre>import boto3<br>import time<br>import os<br>from botocore.config import Config<br>import logging<br><br>config = Config(<br>   retries = {<br>      &#39;max_attempts&#39;: 10,<br>      &#39;mode&#39;: &#39;standard&#39;<br>   }<br>)<br><br># Set up logging<br>logging.basicConfig(level=logging.INFO, format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br>logger = logging.getLogger()<br><br><br>def set_log_retention(log_client, log_group_name, retention_days):<br>    try:<br>        log_client.put_retention_policy(<br>            logGroupName=log_group_name,<br>            retentionInDays=retention_days<br>        )<br>        logger.info(f&quot;Set retention policy of {retention_days} days for {log_group_name}&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;Error setting retention policy for {log_group_name}: {e}&quot;)<br><br>def export_logs(S3_BUCKET, REGION, RETENTION_DAYS):<br>    # Initialize AWS clients<br>    session = boto3.Session()<br>    log_client = session.client(&#39;logs&#39;, region_name=REGION, config=config)<br>    ssm_client = session.client(&#39;ssm&#39;, region_name=REGION, config=config)<br><br>    log_group_names = []<br>    paginator = log_client.get_paginator(&#39;describe_log_groups&#39;)<br><br>    for page in paginator.paginate(limit=50):<br>        for log_group in page[&#39;logGroups&#39;]:<br>            log_group_names.append(log_group[&#39;logGroupName&#39;])<br><br>    for log_group_name in log_group_names:<br>        # Set retention policy<br>        retention_days = int(os.environ.get(&#39;RETENTION_DAYS&#39;))<br>        set_log_retention(log_client, log_group_name, retention_days)<br>        <br>        ssm_parameter_name = (&quot;/log-exporter-last-export/%s&quot; % log_group_name).replace(&quot;//&quot;, &quot;/&quot;)<br>        try:<br>            ssm_response = ssm_client.get_parameter(Name=ssm_parameter_name)<br>            ssm_value = ssm_response[&#39;Parameter&#39;][&#39;Value&#39;]<br>        except ssm_client.exceptions.ParameterNotFound:<br>            ssm_value = &quot;0&quot;<br><br>        export_to_time = int(round(time.time() * 1000))<br><br>        logger.info(f&quot;Exporting {log_group_name} to {S3_BUCKET}&quot;)<br><br>        if export_to_time - int(ssm_value) &lt; (24 * 60 * 60 * 1000):<br>            logger.info(&quot;Skipped until 24hrs from last export is completed&quot;)<br>            continue<br><br>        retries = 0<br>        max_retries = 5<br>        backoff_time = 20<br><br>        while retries &lt; max_retries:<br>            try:<br>                response = log_client.create_export_task(<br>                    logGroupName=log_group_name,<br>                    fromTime=int(ssm_value),<br>                    to=export_to_time,<br>                    destination=S3_BUCKET,<br>                    destinationPrefix=log_group_name.strip(&quot;/&quot;)<br>                )<br>                logger.info(f&quot;Task created: {response[&#39;taskId&#39;]}&quot;)<br><br>                while True:<br>                    status_response = log_client.describe_export_tasks(<br>                        taskId=response[&#39;taskId&#39;]<br>                    )<br>                    export_task = status_response[&#39;exportTasks&#39;][0]<br>                    status_code = export_task[&#39;status&#39;][&#39;code&#39;]<br>                    logger.info(f&quot;Task status: {status_code} for Task {response[&#39;taskId&#39;]}&quot;)<br><br>                    if status_code == &#39;COMPLETED&#39;:<br>                        logger.info(f&quot;Task {response[&#39;taskId&#39;]} completed successfully.&quot;)<br>                        break<br>                    elif status_code in [&#39;FAILED&#39;, &#39;CANCELLED&#39;]:<br>                        raise Exception(f&quot;Export task failed with status: {status_code}&quot;)<br><br>                    time.sleep(10)<br><br>                if status_code == &#39;COMPLETED&#39;:<br>                    break<br><br>            except log_client.exceptions.LimitExceededException:<br>                logger.warning(&quot;Need to wait until all tasks are finished (LimitExceededException). Retrying...&quot;)<br>                time.sleep(backoff_time)<br>                retries += 1<br>                backoff_time = min(backoff_time * 2, 60)<br>            except Exception as e:<br>                logger.error(f&quot;Error exporting {log_group_name}: {e}&quot;)<br>                break<br><br>        if retries == max_retries:<br>            logger.warning(f&quot;Max retries reached for {log_group_name}, skipping...&quot;)<br>            continue<br><br>        ssm_response = ssm_client.put_parameter(<br>            Name=ssm_parameter_name,<br>            Type=&quot;String&quot;,<br>            Value=str(export_to_time),<br>            Overwrite=True<br>        )<br>        logger.info(f&quot;Updated SSM parameter {ssm_parameter_name} with time: {export_to_time}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    # Get configuration from environment variables<br>    S3_BUCKET = os.environ.get(&#39;DESTINATION_BUCKET&#39;)<br>    REGION = os.environ.get(&#39;AWS_REGION&#39;, &#39;us-east-1&#39;)<br>    RETENTION_DAYS = os.environ.get(&#39;RETENTION_DAYS&#39;, &#39;365&#39;)<br><br>    if not S3_BUCKET:<br>        logger.error(&quot;DESTINATION_BUCKET environment variable is not set&quot;)<br>        exit(1)<br><br>    logger.info(f&quot;Starting log export process for all log groups&quot;)<br>    logger.info(f&quot;Destination S3 bucket: {S3_BUCKET}&quot;)<br>    logger.info(f&quot;AWS Region: {REGION}&quot;)<br><br>    export_logs(S3_BUCKET, REGION, RETENTION_DAYS)<br><br>    logger.info(&quot;Log export process completed&quot;)</pre><p>This script runs within our AWS Batch job, allowing it to process large volumes of log data without time or memory constraints.</p><h3>The Workflow</h3><p>Here’s how it all comes together:</p><ol><li>Every day, the EventBridge rule triggers the Lambda function.</li><li>The Lambda function submits a new Batch job.</li><li>AWS Batch runs the job in the Fargate compute environment.</li><li>The job runs our Python script, which:</li></ol><ul><li>Discovers all log groups</li><li>Sets retention policies</li><li>Creates export tasks for each log group</li><li>Monitors the export tasks until completion</li><li>Updates SSM parameters to track progress</li></ul><h3>Conclusion</h3><p>By leveraging AWS Batch, we’ve created a serverless, scalable solution for automatically exporting CloudWatch logs to S3. This approach offers several benefits:</p><ul><li><strong>Cost-effective</strong>: We only pay for the compute resources used during the export process.</li><li><strong>Scalable</strong>: AWS Batch can handle large volumes of log data across multiple log groups.</li><li><strong>Maintainable</strong>: The solution is entirely serverless, reducing operational overhead.</li><li><strong>Flexible</strong>: We can easily modify the export script or schedule without changing the overall architecture.</li><li><strong>Robust</strong>: Unlike a Lambda-based solution, our Batch job can run for extended periods, handling large export tasks without timing out.</li></ul><p>Remember to consider your specific requirements, such as retention periods, access controls, and compliance needs, when implementing this solution in your environment. Happy logging!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3e63a2b21da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building lightweight multistage docker images]]></title>
            <link>https://medium.com/@iamaniruddhaj/building-lightweight-multistage-docker-images-f40f643b9fe7?source=rss-b26e9700ec72------2</link>
            <guid isPermaLink="false">https://medium.com/p/f40f643b9fe7</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[bitbucket-pipelines]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Aniruddha Jawanjal]]></dc:creator>
            <pubDate>Fri, 17 May 2024 05:38:26 GMT</pubDate>
            <atom:updated>2024-05-17T06:14:28.871Z</atom:updated>
            <content:encoded><![CDATA[<p>Sample integration in Gitlab CI &amp; Bitbucket pipelines</p><p>In today’s worls building docker images for a project is prerequisite for most of the projects running on cloud. These build process sometimes result in bulky docker images with lot of tools and files which are not required at the runtime.</p><p>If build process is creating a bulky docker image, it has several disadvantages like security issues, more attack surface, slower startup times, consuming more disk space etc.</p><p>Building lightweight docker images helps you to avoid these issues. Also, it helps to reduce storage cost, faster build-deployment and startup times &amp; efficient resource utilization.</p><p>Below are some examples of building lightweight docker images:</p><p><strong>Building a lightweight Docker image for openjdk + maven project</strong></p><pre># Stage 1: Build image <br>FROM maven:3.8.3-openjdk-17 as builder<br>WORKDIR /usr/src/app<br>COPY . .<br>RUN mvn clean package <br><br># Stage 2: jdk slim deploy image<br>FROM openjdk:17-jdk-slim<br>WORKDIR /usr/app<br>COPY --from=builder /usr/src/app/target/ /usr/app/<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;/usr/app/app-services-0.0.1-SNAPSHOT.jar&quot;]</pre><p><strong>Building a lightweight Docker image for NodeJS project</strong></p><pre># Stage 1: Build image<br>FROM node:18 AS build<br>WORKDIR /build<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>RUN npm run build --if-present<br><br># Stage 2: Alpine Deploy image<br>FROM node:18-alpine<br>WORKDIR /app<br>COPY --from=build /build/dist ./dist<br># Change directory to the &#39;dist&#39; folder<br>WORKDIR /app/dist<br>EXPOSE 3000<br># Command to run the application<br>CMD [ &quot;npm&quot;, &quot;start&quot; ]</pre><p>Once we have dockerfile in place for build process, we need to push these images to container registry. Thereafter, we can move ahead with deployment process for these on Kubernetes using helm or any other tool. I am mostly using helm for this.</p><p>PFB sample multistageGitlab CI pipeline. It follows the below process</p><p><strong><em>Build a lightwegith docker image → Push image to container registry → update the helm chart values.yaml file with updated image tag hosted in separate repo → commit to helmcharts repo with updated image tag</em></strong></p><p>As I was using ArgoCD, this would trigger auto-deployment for dev environments.</p><p>PFB Gitlab CI pipeline which performs the above steps. I haven’t explained Gitlab variables in details, I’ll do that in separate blog in future. But most of the steps are self-explainatory.</p><pre>stages:<br>  - build<br>  - deploy<br><br><br>variables:<br>  IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-$CI_COMMIT_SHORT_SHA<br><br><br>build:<br>  # Use the official docker image.<br>  image: docker:latest<br>  stage: build<br>  only:<br>    - develop <br>    - main<br>  services:<br>    - docker:dind<br>  script:<br>    - echo &quot;Building Docker image...&quot;<br>    - docker login -u &quot;$CI_REGISTRY_USER&quot; -p &quot;$CI_REGISTRY_PASSWORD&quot; $CI_REGISTRY<br>    - docker build --quiet -f Dockerfile.Build -t $IMAGE_TAG .<br>    - docker push $IMAGE_TAG<br>    - echo &quot;Pushed image $IMAGE_TAG to registry.&quot;<br><br>deploy:<br>  stage: deploy<br>  before_script:<br>    - &#39;which ssh-agent || ( apt-get update -qy &amp;&amp; apt-get install openssh-client -qqy )&#39;<br>    - eval `ssh-agent -s`<br>    - echo &quot;${SSH_PRIVATE_KEY_TOOLKIT}&quot; | tr -d &#39;\r&#39; | ssh-add -<br>    - mkdir -p ~/.ssh<br>    - chmod 700 ~/.ssh<br>    - echo &quot;$SSH_PUBLIC_KEY&quot; &gt;&gt; ~/.ssh/id_rsa.pub<br>    - &#39;[[ -f /.dockerenv ]] &amp;&amp; echo -e &quot;Host *\n\tStrictHostKeyChecking no\n\n&quot; &gt; ~/.ssh/config&#39;<br>  needs: [ &quot;build&quot; ]<br>  script:<br>    - &gt;-<br>      existing_tag=$(cat ./helm-charts/backend-app/values.dev.yaml | grep tag: | cut -d &quot;:&quot; -f2 )<br>      updated_tag=$CI_COMMIT_REF_SLUG-$CI_COMMIT_SHORT_SHA<br>    - echo -e &quot;exsting_tag is $existing_tag &amp; updated_tag will be $updated_tag&quot;<br>    - sed -i &quot;s/$existing_tag/ $updated_tag/&quot; ./helm-charts/backend-app/values.dev.yaml<br>    - git config --global user.email &quot;${GITLAB_USER_EMAIL}&quot; &amp;&amp; git config --global user.name &quot;${GITLAB_USER_NAME}&quot;<br>    - git add * <br>    - git commit -m &quot;Updated $CI_COMMIT_SHORT_SHA [skip ci]&quot; || echo &quot;No changes, nothing to commit!&quot;<br>    - git remote rm origin &amp;&amp; git remote add origin git@gitlab.com:$CI_PROJECT_PATH.git<br>    - git push origin HEAD:$CI_COMMIT_REF_NAME<br><br># Below steps can be skipped. It basically does the same thing if helm charts repo is separate.<br>    - git clone git@gitlab.com:gitops-demo.git<br>    - ls -lhtr <br>    - cd ./gitops-demo &amp;&amp; git checkout feature/ajawanjal/helm<br>    - &gt;- <br>      GITOPS_EXISTING_IMAGE_TAG=$(cat ./helm-charts/backend-app/values.dev.yaml | grep tag: | cut -d &quot;:&quot; -f2 )<br>      GITOPS_BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)<br>      GITOPS_COMMIT_ID=$(git rev-parse --short HEAD)<br>    #   GITOPS_UPDATED_IMAGE_TAG=$GITOPS_BRANCH_NAME-$GITOPS_COMMIT_ID<br>    - echo -e &quot;existing_tag is $existing_tag &amp; updated_tag will be $updated_tag. Branch Name  GITOPS_BRANCH_NAME &amp; commit id - GITOPS_COMMIT_ID&quot;<br>    - sed -i &quot;s|$GITOPS_EXISTING_IMAGE_TAG| $updated_tag|&quot; ./helm-charts/backend-app/values.dev.yaml<br>    - git config --global user.email &quot;${GITLAB_USER_EMAIL}&quot; &amp;&amp; git config --global user.name &quot;${GITLAB_USER_NAME}&quot;<br>    - git add * <br>    - git commit -m &quot;Updated $GITOPS_COMMIT_ID [skip ci]&quot; || echo &quot;No changes, nothing to commit!&quot;<br>    - git remote rm origin &amp;&amp; git remote add origin git@gitlab.com:gitops-demo.git<br>    - git push origin HEAD:$GITOPS_BRANCH_NAME</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f40f643b9fe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Looping in AWS Cloudformation with “Fn::ForEach” intrinsic function!]]></title>
            <link>https://medium.com/@iamaniruddhaj/looping-in-cloudformation-with-fn-foreach-intrinsic-function-197862e3ff9c?source=rss-b26e9700ec72------2</link>
            <guid isPermaLink="false">https://medium.com/p/197862e3ff9c</guid>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Aniruddha Jawanjal]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 05:50:15 GMT</pubDate>
            <atom:updated>2024-03-04T05:59:18.153Z</atom:updated>
            <content:encoded><![CDATA[<p>I had multiple DynamoDB tables with provisioned capacity in my Cloudformation stack. Most of the capacity was unused and I wanted to cost-optimise it. DynamoDB autoscaling looked like perfect solution for this.</p><p>Only issue is, I have around 80 tables &amp; to implement DDB autoscaling, I had to repeat autoscaling code block around 80 times. Doesn’t sound like an elegant solution. My autoscaling code would be more than actual DynamoDB table config code and it’ll make my CF templates bit unreadable/Hard to understand.</p><p>So, I looked around for solutions. As I am familiar with Terraform, I tried to look for <a href="https://aws.amazon.com/blogs/mt/introducing-aws-cloudformation-modules/">modules in Cloudformation</a>. Voila, they are available. Only problem is, unlike terraform, you can not just write a few .tf files, throw them in a folder and use it as modules — you have to do “cfn init” in separate folder, it will create some another set of json, Yaml and rpdk-config, you write your module code and then submit it to Cloudformation. Doable but unnecessary complicated IMO. I don’t want to add this to my working</p><p>Code is going to be repetitive, I could just loop through tables if there’s a way. And I found it — For loop in CF. <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-foreach.html">https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-foreach.html</a></p><p>Just a few notes to use this in your Cloudformation template.</p><ul><li>You have to specify “AWS::LanguageExtensions” in your CF template. By default Cloudformation does not allow you to use intrinsic functions.</li><li>I have used mapping to specify table names. Because “<em>Identifier” or “Collection” </em>in CF template only supports alphanumeric characters and my table name has “-” in the names. It also helped me to specify different values for each table.</li><li>You have to specify CAPABILITY_AUTO_EXPAND in Capabilities. We need this as Intrinsic function &amp; Macros perform custom processing on templates. <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html">https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html</a></li></ul><p>Please check sample code block below.</p><pre><br>AWSTemplateFormatVersion: 2010-09-09<br>Transform: AWS::LanguageExtensions<br><br>Description: &gt;-<br>  Create DynamoDB tables with ForEach<br><br>Parameters:<br>  Environment:<br>    Description: Environment<br>    Type: String<br><br>Mappings:<br>  ProvisionedDynamoDBtables:<br>    ExamStudentSemesters:<br>      DDBTableName: Exam-student-semesters<br>      MaxCapacity: 10<br>      MinCapacity: 2<br>      ScaleInCooldown: 15<br>      ScaleOutCooldown: 15<br>      TargetValue: 50<br>      SecondaryIndex: secondaryindex-loginStudentName-unit<br>    ExamSessionTime:<br>      DDBTableName: Exam-session-time<br>      MaxCapacity: 10<br>      MinCapacity: 2<br>      ScaleInCooldown: 15<br>      ScaleOutCooldown: 15<br>      TargetValue: 50<br>      <br>Resources:<br>  EventsUserSemestersDynamoDBTable:<br>    Type: AWS::DynamoDB::Table<br>    Properties:<br>      AttributeDefinitions:<br>        - AttributeName: studentName<br>          AttributeType: S<br>        - AttributeName: studentId<br>          AttributeType: S<br>        - AttributeName: examId<br>          AttributeType: S<br>      KeySchema:<br>        - AttributeName: examId<br>          KeyType: RANGE<br>        - AttributeName: studentId<br>          KeyType: HASH<br>      GlobalSecondaryIndexes:<br>        - IndexName: secondaryindex-loginStudentName-unit<br>          KeySchema:<br>            - AttributeName: examId<br>              KeyType: HASH<br>            - AttributeName: studentName<br>              KeyType: RANGE<br>          ProvisionedThroughput:<br>              ReadCapacityUnits: 5<br>              WriteCapacityUnits: 5<br>      ProvisionedThroughput:<br>          ReadCapacityUnits: 10<br>          WriteCapacityUnits: 10<br>      TableName: !Join [&quot;-&quot;, [!Ref &quot;Environment&quot;, &quot;exam-student-semesters&quot;]]<br>      Tags:<br>        - Key: Environment<br>          Value: !Ref &quot;Environment&quot;<br><br><br>  &#39;Fn::ForEach::DynamoDBtableProvisioned&#39;:<br>    - TableName<br>    - - ExamStudentSemesters<br>      - ExamSessionTime<br>    - &#39;DynamoDB${TableName}ReadCapacityScalableTarget&#39;:<br>        Type: &quot;AWS::ApplicationAutoScaling::ScalableTarget&quot;<br>        Properties:<br>          ResourceId: !Join<br>            - /<br>            - - table<br>              - !Join [&#39;-&#39;, [!Ref Environment, Fn::FindInMap: [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;DDBTableName&quot; ]] ] # !Ref TableName<br>          MaxCapacity: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;MaxCapacity&quot; ]<br>          MinCapacity: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;MinCapacity&quot; ]<br>          RoleARN: !GetAtt DynamodbDynamodbScalingRole.Arn<br>          ScalableDimension: dynamodb:table:ReadCapacityUnits<br>          ServiceNamespace: dynamodb<br><br>      &#39;DynamoDB${TableName}ReadScalingPolicy&#39;:<br>        Type: &quot;AWS::ApplicationAutoScaling::ScalingPolicy&quot;<br>        <br>        Properties:<br>          PolicyName: !Sub &quot;DynamoDBRead${TableName}AutoScalingPolicy&quot;<br>          PolicyType: TargetTrackingScaling<br>          ScalingTargetId: !Ref<br>            &#39;Fn::Sub&#39;: &#39;DynamoDB${TableName}ReadCapacityScalableTarget&#39;<br>          TargetTrackingScalingPolicyConfiguration:<br>            TargetValue: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;TargetValue&quot; ]<br>            ScaleInCooldown: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;ScaleInCooldown&quot; ]<br>            ScaleOutCooldown: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;ScaleOutCooldown&quot; ]<br>            PredefinedMetricSpecification:<br>              PredefinedMetricType: DynamoDBReadCapacityUtilization<br><br>      &#39;DynamoDB${TableName}WriteCapacityScalableTarget&#39;:<br>        Type: &quot;AWS::ApplicationAutoScaling::ScalableTarget&quot;<br>        <br>        Properties:<br>          ResourceId: !Join<br>            - /<br>            - - table<br>              - !Join [&#39;-&#39;, [!Ref Environment, Fn::FindInMap: [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;DDBTableName&quot; ]] ]<br>          MaxCapacity: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;MaxCapacity&quot; ]<br>          MinCapacity: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;MinCapacity&quot; ]<br>          RoleARN: !GetAtt DynamodbDynamodbScalingRole.Arn<br>          ScalableDimension: dynamodb:table:WriteCapacityUnits<br>          ServiceNamespace: dynamodb<br><br>      &#39;DynamoDB${TableName}WriteScalingPolicy&#39;:<br>        Type: &quot;AWS::ApplicationAutoScaling::ScalingPolicy&quot;<br>        Properties:<br>          PolicyName: !Sub &quot;DynamoDBWrite${TableName}AutoScalingPolicy&quot;<br>          PolicyType: TargetTrackingScaling<br>          ScalingTargetId: !Ref<br>            &#39;Fn::Sub&#39;: &#39;DynamoDB${TableName}WriteCapacityScalableTarget&#39;<br>          TargetTrackingScalingPolicyConfiguration:<br>            TargetValue: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;TargetValue&quot; ]<br>            ScaleInCooldown: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;ScaleInCooldown&quot; ]<br>            ScaleOutCooldown: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;ScaleOutCooldown&quot; ]<br>            PredefinedMetricSpecification:<br>              PredefinedMetricType: DynamoDBWriteCapacityUtilization<br><br>  &#39;Fn::ForEach::DynamoDBtableProvisionedSecondaryIndex&#39;:<br>    - TableName<br>    - - ExamStudentSemesters<br>      - ExamSessionTime<br>    - &#39;DynamoDB${TableName}SecondaryIndexReadCapacityScalableTarget&#39;:<br>        Type: &quot;AWS::ApplicationAutoScaling::ScalableTarget&quot; <br>        Properties:<br>          MaxCapacity: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;MaxCapacity&quot; ]<br>          MinCapacity: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;MinCapacity&quot; ]<br>          RoleARN: !GetAtt DynamodbDynamodbScalingRole.Arn<br>          ResourceId: !Join<br>            - /<br>            - - table<br>              - !Join [&#39;-&#39;, [!Ref Environment, Fn::FindInMap: [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;DDBTableName&quot; ]] ]<br>              - index<br>              - !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;SecondaryIndex&quot; ]<br>          ScalableDimension: dynamodb:index:ReadCapacityUnits<br>          ServiceNamespace: dynamodb<br><br>      &#39;DynamoDB${TableName}SecondaryIndexReadScalingPolicy&#39;:<br>        Type: &quot;AWS::ApplicationAutoScaling::ScalingPolicy&quot;<br>        Properties:<br>          ScalingTargetId: !Ref<br>            &#39;Fn::Sub&#39;: &#39;DynamoDB${TableName}SecondaryIndexReadCapacityScalableTarget&#39;<br>          PolicyName: !Sub &quot;DynamoDBRead${TableName}AutoScalingPolicy&quot;<br>          PolicyType: TargetTrackingScaling<br>          TargetTrackingScalingPolicyConfiguration:<br>            TargetValue: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;TargetValue&quot; ]<br>            ScaleInCooldown: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;ScaleInCooldown&quot; ]<br>            ScaleOutCooldown: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;ScaleOutCooldown&quot; ]<br>            PredefinedMetricSpecification:<br>              PredefinedMetricType: DynamoDBReadCapacityUtilization<br><br>      &#39;DynamoDB${TableName}SecondaryIndexWriteCapacityScalableTarget&#39;:<br>        Type: &quot;AWS::ApplicationAutoScaling::ScalableTarget&quot;<br>        Properties:<br>          MaxCapacity: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;MaxCapacity&quot; ]<br>          MinCapacity: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;MinCapacity&quot; ]<br>          RoleARN: !GetAtt DynamodbDynamodbScalingRole.Arn<br>          ResourceId: !Join<br>            - /<br>            - - table<br>              - !Join [&#39;-&#39;, [!Ref Environment, Fn::FindInMap: [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;DDBTableName&quot; ]] ] # !Ref TableName<br>              - index<br>              - !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;SecondaryIndex&quot; ]<br>          ScalableDimension: dynamodb:index:WriteCapacityUnits<br>          ServiceNamespace: dynamodb<br><br>      &#39;DynamoDB${TableName}SecondaryIndexWriteScalingPolicy&#39;:<br>        Type: &quot;AWS::ApplicationAutoScaling::ScalingPolicy&quot;<br>        Properties:<br>          ScalingTargetId: !Ref<br>            &#39;Fn::Sub&#39;: &#39;DynamoDB${TableName}SecondaryIndexWriteCapacityScalableTarget&#39;<br>          PolicyName: !Sub &quot;DynamoDBWrite${TableName}AutoScalingPolicy&quot;<br>          PolicyType: TargetTrackingScaling<br>          TargetTrackingScalingPolicyConfiguration:<br>            TargetValue: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;TargetValue&quot; ]<br>            ScaleInCooldown: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;ScaleInCooldown&quot; ]<br>            ScaleOutCooldown: !FindInMap [&quot;ProvisionedDynamoDBtables&quot;, !Ref TableName,&quot;ScaleOutCooldown&quot; ]<br>            PredefinedMetricSpecification:<br>              PredefinedMetricType: DynamoDBWriteCapacityUtilization</pre><p>I have enabled autoscaling for more than 80 tables per env using this. There are not much detailed resources around this so I hope this helps you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=197862e3ff9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing AWS ALB Ingress controller on EKS]]></title>
            <link>https://medium.com/@iamaniruddhaj/installing-aws-alb-ingress-controller-on-eks-aa05cea0848a?source=rss-b26e9700ec72------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa05cea0848a</guid>
            <category><![CDATA[ingress]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[ingresscontroller]]></category>
            <category><![CDATA[aws-alb]]></category>
            <dc:creator><![CDATA[Aniruddha Jawanjal]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 09:19:35 GMT</pubDate>
            <atom:updated>2024-02-27T09:19:35.317Z</atom:updated>
            <content:encoded><![CDATA[<pre>$ curl -o iam_policy_latest.json https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/main/docs/install/iam_policy.json</pre><pre>$ aws iam create-policy \<br>    --policy-name ArgoCDAWSLoadBalancerControllerIAMPolicy \<br>    --policy-document file://iam_policy_latest.json \<br>    --profile boydaws<br><br>    {<br>    &quot;Policy&quot;: {<br>        &quot;PolicyName&quot;: &quot;ArgoCDAWSLoadBalancerControllerIAMPolicy&quot;,<br>        &quot;PolicyId&quot;: &quot;&lt;policy-id&gt;&quot;,<br>        &quot;Arn&quot;: &quot;arn:aws:iam::&lt;aws-account-id&gt;:policy/ArgoCDAWSLoadBalancerControllerIAMPolicy&quot;,<br>        &quot;Path&quot;: &quot;/&quot;,<br>        &quot;DefaultVersionId&quot;: &quot;v1&quot;,<br>        &quot;AttachmentCount&quot;: 0,<br>        &quot;PermissionsBoundaryUsageCount&quot;: 0,<br>        &quot;IsAttachable&quot;: true,<br>        &quot;CreateDate&quot;: &quot;&quot;,<br>        &quot;UpdateDate&quot;: &quot;&quot;<br>    }<br>}</pre><pre>$ eksctl create iamserviceaccount \<br>  --profile awsprofile \<br>  --cluster=&lt;eks-cluster-name&gt; \<br>  --namespace=kube-system \<br>  --name=aws-load-balancer-controller \<br>  --attach-policy-arn=arn:aws:iam::&lt;aws-account-id&gt;:policy/ArgoCDAWSLoadBalancerControllerIAMPolicy \<br>  --override-existing-serviceaccounts \<br>  --approve <br><br>$ eksctl  get iamserviceaccount --profile awsprofile --cluster &lt;eks-cluster-name&gt;</pre><pre>$  kubectl get sa -n kube-system<br><br>$ kubectl get sa aws-load-balancer-controller -n kube-system<br><br>$ kubectl describe sa aws-load-balancer-controller -n kube-system </pre><pre>$ helm version --short | cut -d + -f 1<br><br>$ helm repo add eks https://aws.github.io/eks-charts<br><br># Install the AWS Load Balancer Controller.<br>## Template<br>$ helm install aws-load-balancer-controller eks/aws-load-balancer-controller \<br>  -n kube-system \<br>  --set clusterName=&lt;eks-cluster-name&gt; \<br>  --set serviceAccount.create=false \<br>  --set serviceAccount.name=aws-load-balancer-controller \<br>  --set region=&lt;aws-region&gt; \<br>  --set vpcId=&lt;vpc-id&gt; \<br>  --set image.repository=&lt;aws-account-id&gt;.dkr.ecr.us-east-1.amazonaws.com/amazon/aws-load-balancer-controller<br>NAME: aws-load-balancer-controller<br>NAMESPACE: kube-system<br>STATUS: deployed<br>REVISION: 1<br>TEST SUITE: None<br>NOTES:<br>AWS Load Balancer controller installed!</pre><pre># Verify that the controller is installed.<br>kubectl -n kube-system get deployment <br>kubectl -n kube-system get deployment aws-load-balancer-controller<br>kubectl -n kube-system describe deployment aws-load-balancer-controller</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa05cea0848a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying ArgoCD on AWS EKS]]></title>
            <link>https://medium.com/@iamaniruddhaj/deploying-argocd-on-aws-eks-notes-to-self-9e2fd42b60d0?source=rss-b26e9700ec72------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2fd42b60d0</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[argo-cd]]></category>
            <dc:creator><![CDATA[Aniruddha Jawanjal]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 07:25:05 GMT</pubDate>
            <atom:updated>2024-02-27T09:22:20.230Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey everyone, this is just list of commands I used while setting up ArgoCD on AWS EKS. This is just rough notes I had while performing ArgoCD implementation.</p><p><strong># Create Cluster</strong></p><pre>eksctl create cluster --name=eks-proj \<br>                      --region=us-east-1 \<br>                      --zones=us-east-1a,us-east-1b \<br>                      --without-nodegroup \<br>                      --profile=aws-argo</pre><p><strong># Template</strong></p><pre>eksctl utils associate-iam-oidc-provider \<br>    --region us-east-1 \<br>    --cluster eks-proj \<br>    --approve \<br>    --profile=aws-argo</pre><p><strong># Replace with region &amp; cluster name</strong></p><pre>eksctl utils associate-iam-oidc-provider \<br>    --region us-east-1 \<br>    --cluster eks-proj \<br>    --approve \<br>    --profile=aws-argo</pre><p><strong># Create Public Node Group</strong></p><pre>eksctl create nodegroup --cluster=eks-proj \<br>                       --region=us-east-1 \<br>                       --name=eks-proj-ng-public1 \<br>                       --node-type=t3.medium \<br>                       --nodes=2 \<br>                       --nodes-min=2 \<br>                       --nodes-max=4 \<br>                       --node-volume-size=20 \<br>                       --ssh-access \<br>                       --ssh-public-key=eks-proj \<br>                       --managed \<br>                       --asg-access \<br>                       --external-dns-access \<br>                       --full-ecr-access \<br>                       --appmesh-access \<br>                       --alb-ingress-access \<br>                       --profile=aws-argo</pre><p><strong># Flow</strong></p><p>App code updated → Image built → Pushed to Gitlab docker registry → Update helm → Create &amp; merge PR for updated helm chart</p><p><strong># Login to EKS</strong></p><pre>aws eks update-kubeconfig --name eks-proj --namespace argocd --region us-east-1 --profile aws-argo<br>kubectl config set-context --current --namespace argocd</pre><p><strong># Build and push image to Gitlab Docker registry</strong></p><p>Note: Docker image can not have a differente name than repo name.</p><p><a href="https://gitlab.com/gitlab-org/gitlab/-/issues/19211#note_1045777316">https://gitlab.com/gitlab-org/gitlab/-/issues/19211#note_1045777316</a></p><pre>docker login registry.gitlab.com -u aniruddha.jawanjal --password glpat-&lt;api-key&gt;<br>docker build -t registry.gitlab.com/aniruddha.jawanjal/argocddemo:latest --build-arg PROJECT_NAME=argocddemo .<br>docker push  registry.gitlab.com/aniruddha.jawanjal/argocddemo:latest</pre><p># <strong>Installing and Configuring ArgoCD</strong></p><p>First we need to setup our EKS cluster on CLI. Once done, we can install ArgoCD using manifest file</p><pre>kubectl create namespace argocd<br>kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml</pre><p>then install argoCD cli</p><pre>curl -sSL -o argocd-linux-amd64 https://github.com/argoproj/argo-cd/releases/latest/download/argocd-linux-amd64<br>sudo install -m 555 argocd-linux-amd64 /usr/local/bin/argocd<br>rm argocd-linux-amd64</pre><p>By default ArgoCD uses admin user. We can get password using `<em>argocd admin initial-password -n argocd</em>` command. Now we can load the ArgoCD on browser using port forwarding with kubectl using `<em>kubectl port-forward svc/argocd-server -n argocd 8080:443</em>` if we haven’t configured the ingress yet. You can load argocd on <a href="https://localhost:8080/">https://localhost:8080</a> — you’ll need to accept security risk warning on browser as we will be using openssl certs at this point.</p><p>Login to ArgoCD cli using `argocd login &lt;ARGOCD_SERVER&gt;` command. You’ll need to enter username &lt;admin&gt; and password. Once done, you can manage ArgoCD from CLI.</p><pre><br>kubectl port-forward svc/argocd-server 8080:443 -n argocd<br>kubectl get secret argocd-initial-admin-secret -n argocd -o yaml<br>kubectl get secret argocd-initial-admin-secret -n argocd -o yaml<br>echo &lt;password&gt; | base64 -d</pre><p>Argocd username: admin</p><p>Argocd password: &lt;get-from-argocd&gt;</p><p><strong># Access issues for IAM Users</strong></p><p>For user access issues, Ref. <a href="https://repost.aws/knowledge-center/eks-kubernetes-object-access-error">https://repost.aws/knowledge-center/eks-kubernetes-object-access-error</a></p><pre>eksctl create iamidentitymapping --cluster eks-proj --region=us-east-1 --arn &quot;arn:aws:iam::&lt;account-id&gt;:user/&lt;username&gt;&quot;  --profile=aws-argo</pre><p><strong># Building an Argocd app manually (Argocd CLI)</strong></p><ul><li>Sample springboot app with helmchart: <a href="https://github.com/binblee/springboot-helm-chart/tree/master">https://github.com/binblee/springboot-helm-chart/tree/master</a></li><li>Get Cluster endpoint:</li></ul><pre><br>aws eks describe-cluster --name eks-proj --query &quot;cluster.endpoint&quot; --profile=aws-argo<br>&quot;https://&lt;eks-endpoint&gt;.gr7.us-east-1.eks.amazonaws.com&quot;</pre><ul><li>Installed Argocd CLI on local machine</li></ul><pre>brew install argocd</pre><ul><li>Login to Argocd</li></ul><pre>argocd login 127.0.0.1:443</pre><ul><li>Add K8s cluster to Argocd</li></ul><pre>kubectl config get-contexts -o name # Get context detail to be added in Argocd <br>argocd cluster add arn:aws:eks:us-east-1:&lt;account-id&gt;:cluster/eks-proj # Add cluster to Argocd </pre><p>and check in argocd dashboard.</p><ul><li>Add repo to Argocd</li></ul><pre>HTTPS: argocd repo add https://github.com/argoproj/argocd-example-apps --username &lt;username&gt; --password &lt;password&gt;<br>SSH: argocd repo add git@gitlab.com:argoproj/argocd-example-apps.git --ssh-private-key-path /User/path-to-ssh-key</pre><p><strong>## Adding Projects and applications to ArgoCD</strong></p><p>Project is container which includes multiple microservices(<strong>applications</strong>) for a specific environment. We hace created “develop” project using manifest file. We have restricted access to only development EKS cluster for this project in project manifest file. This way, we can ensure that applications(microservices) are getting deployed to relevant EKS cluster only.</p><p>To add an environment: Add project file with required values.</p><p>To add a microservice: Add an application helm-chart in applications folder</p><p><strong># Creating an argocd </strong><a href="https://argo-cd.readthedocs.io/en/stable/user-guide/projects/"><strong>project</strong></a><strong> using manifest file</strong></p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: AppProject<br>metadata:<br>  name: develop<br>  namespace: argocd<br>  # Finalizer that ensures that project is not deleted until it is not referenced by any application<br>  finalizers:<br>    - resources-finalizer.argocd.argoproj.io<br>spec:<br>  description: Development environment for the Application<br><br>  # Allow manifests to deploy from any Git repos<br>  sourceRepos:<br>  - &#39;*&#39;<br><br>  # Only permit applications to deploy to the guestbook namespace in the same cluster<br>  destinations:<br>  - namespace: &#39;*&#39;<br>    server: https://&lt;argocd-eks-endpoint&gt;.gr7.us-east-2.eks.amazonaws.com<br><br>  sourceNamespaces:<br>  - develop-*<br><br>  clusterResourceWhitelist:<br>      - group: &#39;*&#39;<br>        kind: &#39;*&#39;</pre><p><strong># Creating an application inside project on argocd</strong></p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: application-name<br>  namespace: argocd<br>spec:<br>  project: develop   #Project name which we created earlier <br>  source:<br>    repoURL: &#39;git@gitlab.com:&lt;repo-url&gt;.git&#39;    #Path to git repo<br>    path: helm-charts/&lt;helm-chart-name&gt;          #Helm chart path<br>    targetRevision: develop          # Branch name to target<br>    helm:<br>      valueFiles:<br>        - values.develop.yaml<br><br>  destination:<br>    server: &#39;https://&lt;eks-endpoint&gt;.gr7.us-east-2.eks.amazonaws.com&#39; # Replace with the address of your Kubernetes cluster<br>    namespace: &quot;&lt;application-namespace&gt;&quot;<br>    <br>  syncPolicy:<br>    automated:<br>      prune: true<br>      selfHeal: true</pre><p>OR</p><ul><li>Create an application using ArgoCD CLI</li></ul><pre>argocd app create demoapp --repo git@gitlab.com:argoproj/argocd-example-apps.git --path . --revision feature/ajawanjal/demo-springboot-helm --dest-server https://&lt;oidc-&gt;.gr7.us-east-1.eks.amazonaws.com --dest-namespace default</pre><p><strong># ArgoCD ALB Ingress controller</strong></p><p>You’ll first need to install AWS LB Controller on ArgoCD EKS cluster to get this working. Follow <a href="https://medium.com/@iamaniruddhaj/installing-aws-alb-ingress-controller-on-eks-aa05cea0848a">https://medium.com/@iamaniruddhaj/installing-aws-alb-ingress-controller-on-eks-aa05cea0848a</a> OR follow <a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.7/deploy/installation/">https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.7/deploy/installation/</a></p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: argocd-ingress<br>  namespace: argocd<br>  annotations:<br>    kubernetes.io/ingress.class: alb<br>    alb.ingress.kubernetes.io/scheme: internal<br>    alb.ingress.kubernetes.io/certificate-arn: &quot;arn:aws:acm:&lt;region&gt;:&lt;account-id&gt;:certificate/&lt;acm-cert-id&gt;&quot;<br>    alb.ingress.kubernetes.io/ssl-policy: ELBSecurityPolicy-2016-08<br>    alb.ingress.kubernetes.io/backend-protocol: HTTPS<br>    alb.ingress.kubernetes.io/healthcheck-path: /login<br>    alb.ingress.kubernetes.io/subnets: &#39;&lt;comma-separated-list-of-subnets&gt;&#39;<br>    alb.ingress.kubernetes.io/target-type: &#39;ip&#39;<br>    alb.ingress.kubernetes.io/security-groups: &#39;&lt;sg-to-use&gt;&#39;<br>    alb.ingress.kubernetes.io/listen-ports: &#39;[{&quot;HTTP&quot;:80,&quot;HTTPS&quot;: 443}]&#39;<br>    alb.ingress.kubernetes.io/actions.ssl-redirect: &#39;{&quot;Type&quot;: &quot;redirect&quot;, &quot;RedirectConfig&quot;: { &quot;Protocol&quot;: &quot;HTTPS&quot;, &quot;Port&quot;: &quot;443&quot;, &quot;StatusCode&quot;: &quot;HTTP_301&quot;}}&#39;<br>  finalizers:<br>    - ingress.k8s.aws/resources<br>  labels:<br>    app: argocd-ingress<br>spec:<br>  rules:<br>    - host: argocd.domain.com<br>      http:<br>        paths:<br>          - path: /<br>            backend:<br>              service:<br>                name: argocd-server<br>                port:<br>                  number: 443<br>            pathType: Prefix</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2fd42b60d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>