<?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 Jeshik Phuyal on Medium]]></title>
        <description><![CDATA[Stories by Jeshik Phuyal on Medium]]></description>
        <link>https://medium.com/@jeshikphuyal?source=rss-560fae6ec207------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fwYJdyEDnSZhP_mh</url>
            <title>Stories by Jeshik Phuyal on Medium</title>
            <link>https://medium.com/@jeshikphuyal?source=rss-560fae6ec207------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:59:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeshikphuyal/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[Archiving PostgreSQL Data to S3 in Parquet Format and Querying It with AWS Glue and Athena]]></title>
            <link>https://jeshikphuyal.medium.com/archiving-postgresql-to-s3-with-parquet-glue-and-athena-a-step-by-step-aws-guide-f8387733ef95?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8387733ef95</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-athena]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws-glue]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 15:42:08 GMT</pubDate>
            <atom:updated>2026-09-28T04:51:11.196Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s the situation: a PostgreSQL database that started lean and manageable gradually became a storage and performance problem. Not because the application was poorly designed — just because time passed, records accumulated, and nobody had yet made a deliberate decision about what to do with historical data.</p><p>By the time we started this project, we had tens of millions of rows sitting in tables that most queries didn’t need. Operational queries were slowing down. Table bloat was affecting vacuuming. Index sizes were creeping up. And storage costs for the managed RDS instance were no longer trivial.</p><p>The fix wasn’t complicated in concept: move the old data out, keep it accessible, don’t over-engineer the retrieval layer. This post documents exactly how we did that — step by step through the AWS Console — from S3 structure to Athena queries.</p><p><strong>Architecture overview:</strong></p><pre>PostgreSQL → S3 (Parquet) → AWS Glue Data Catalog → Amazon Athena</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pq1IJYy7VdXPPrDQWpROzw.png" /><figcaption><strong>fig: Architecture Overview</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5A6exVcTPWHoEy8J4_QJPw.jpeg" /></figure><h3>Why PostgreSQL Was Struggling</h3><p>When your PostgreSQL table holds 50 million rows and your application only ever queries the last 90 days of data, you’re paying a constant tax. Every auto vacuum run is touching more rows. Your indexes are larger than they need to be, which means more memory pressure and slower index scans. ANALYZE takes longer. Even COPY and backup operations slow down.</p><p>We ran into all of this. Query times that should have been milliseconds were creeping into seconds — not because of bad queries, but because the planner was working with bloated statistics and oversized indexes. And the RDS storage bill reflected every single one of those historical rows sitting idle.</p><p>After archiving, PostgreSQL immediately felt healthier. Vacuum completed faster. Index sizes dropped. Query plans improved. That alone made the project worthwhile.</p><h3>Why Parquet Over CSV</h3><p>Before getting into the setup, it’s worth understanding why we chose Parquet — because this decision shapes how you configure Glue and Athena.</p><p><strong>Columnar storage means less scanning.</strong> Parquet stores data column by column. When Athena runs SELECT event_type, COUNT(*) FROM archive WHERE dt = &#39;2024-01-15&#39;, it only reads the event_type column — not payload, user_id, or the other 20 columns in your table. CSV reads entire rows regardless.</p><p><strong>Athena charges by bytes scanned.</strong> At $5 per terabyte, every query you run has a cost. Parquet with Snappy compression can reduce scan volume by 60–80% compared to CSV on the same data. Over months of queries, this adds up.</p><p><strong>Schema is preserved.</strong> A TIMESTAMP in Parquet stays a timestamp. A BIGINT stays a bigint. You don&#39;t end up with type inference surprises when a column value like 1704067200 gets read as a string or float.</p><h3>S3 Partition Design : Plan This First</h3><p><strong>Do not skip this section.</strong> Partition structure is the most consequential design decision in this setup. Changing it after the fact means rewriting all your data and recreating your Glue table.</p><p>We used a two-level partition:</p><pre>s3://archive-bucket/archives/dt=YYYY-MM-DD/logical_group_partition=&lt;identifier&gt;/data.parquet</pre><p><strong>dt (date) as the first partition</strong> — almost every historical query has a date filter. Athena translates WHERE dt = &#39;2024-01-15&#39; into an S3 prefix scan, skipping every other date&#39;s files entirely. This is called partition pruning, and it&#39;s the biggest performance lever you have.</p><p><strong>logical_group_partition as the second partition</strong> — a secondary business grouping (an account ID, region, tenant ID whatever makes sense for your domain). Queries that filter on both date and this identifier are highly targeted. Even queries that only filter on date benefit from the first partition.</p><p>Full path example:</p><pre>s3://company-archive/archives/dt=2024-01-13/logical_group_partition=abc123/data.parquet<br>s3://company-archive/archives/dt=2024-01-14/logical_group_partition=abc123/data.parquet<br>s3://company-archive/archives/dt=2024-01-15/logical_group_partition=xyz789/data.parquet<br>s3://company-archive/archives/dt=2024-01-16/logical_group_partition=abc123/data.parquet</pre><p>The key=value folder naming is not optional — it&#39;s the convention Glue and Athena use to automatically recognize partition columns.</p><h3>Step-by-Step AWS Console Setup</h3><h3>STEP 1 — Create the Archive S3 Bucket</h3><ol><li>Open the <strong>AWS Console</strong> and navigate to <strong>S3</strong></li><li>Click <strong>“Create bucket”</strong></li><li>Fill in the details:</li></ol><ul><li><strong>Bucket name</strong>: company-data-archive (must be globally unique across all AWS)</li><li><strong>AWS Region</strong>: Choose the same region you will use for Glue and Athena — keeping everything in one region avoids cross-region data transfer charges</li></ul><p>4. Under <strong>Object Ownership</strong>: select <strong>“ACLs disabled (recommended)”</strong></p><p>5. Under <strong>Block Public Access settings</strong>: leave all four checkboxes <strong>enabled</strong> — archived data should never be publicly accessible</p><p>6. Under <strong>Bucket Versioning</strong>: set to <strong>“Enable”</strong> if you need protection against accidental overwrites or have compliance requirements; otherwise leave it disabled</p><p>7. Under <strong>Default encryption</strong>:</p><ul><li>Select <strong>“Server-side encryption with Amazon S3 managed keys (SSE-S3)”</strong> for simplicity</li><li>Or <strong>“SSE-KMS”</strong> if your organization requires KMS-managed keys</li></ul><p>8. Leave all other settings at their defaults</p><p>9. Click <strong>“Create bucket”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvFdRStMjaxHi8n8MKuryA.png" /></figure><h3>STEP 2 — Create the Athena Query Results Bucket</h3><p>Athena writes every query’s output to S3. You need a dedicated bucket for this — keep it separate from your archive data to avoid confusion and simplify access policies.</p><ol><li>Back in <strong>S3</strong>, click <strong>“Create bucket”</strong> again</li><li>Fill in:</li></ol><ul><li><strong>Bucket name</strong>: company-athena-query-results</li><li><strong>AWS Region</strong>: Same region as your archive bucket</li></ul><p>3. Keep Block Public Access settings all <strong>enabled</strong></p><p>4. Enable <strong>SSE-S3</strong> encryption</p><p>5. Click <strong>“Create bucket”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5D10XqKfID_sxUkE4OGPw.png" /></figure><blockquote><strong><em>Tip</em></strong><em>: After setup, add a lifecycle rule to this bucket to automatically expire objects after 30–90 days. Query results accumulate quickly and you rarely need them long-term. Go to the bucket → </em><strong><em>Management</em></strong><em> → </em><strong><em>Lifecycle rules</em></strong><em> → </em><strong><em>Create lifecycle rule</em></strong><em>, expire objects after your chosen number of days.</em></blockquote><h3>STEP 3 — Upload Parquet Files with the Correct Folder Structure</h3><p>This step assumes you’ve already exported your PostgreSQL data to Parquet files. The folder naming is critical Glue and Athena depend on it.</p><ol><li>In S3, click into your <strong>company-data-archive</strong> bucket</li><li>Click <strong>“Create folder”</strong>, name it archives this is your base prefix</li><li>Inside archives, create your first date partition folder:</li></ol><ul><li>Click <strong>“Create folder”</strong></li><li>Name it exactly: dt=2024-01-15 the key=value format is mandatory</li></ul><p>4. Inside dt=2024-01-15, create a group partition folder:</p><ul><li>Click <strong>“Create folder”</strong></li><li>Name it: logical_group_partition=abc123</li></ul><p>5. Inside logical_group_partition=abc123,Click <strong>“Upload”</strong> and upload your data.parquet file</p><p>Your final S3 path should be:</p><pre>company-data-archive/archives/dt=2024-01-15/logical_group_partition=abc123/data.parquet</pre><p>Repeat this structure for each date and group combination. In practice you’ll automate uploads via script or AWS CLI the key is that the folder structure must follow this exact convention every time.</p><p><strong>AWS CLI equivalent:</strong></p><pre>aws s3 cp ./data.parquet \<br>  s3://company-data-archive/archives/dt=2024-01-15/logical_group_partition=abc123/data.parquet</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttS3zskyVBpiN7EDArxZoQ.png" /></figure><h3>STEP 4 — Create an IAM Role for AWS Glue</h3><p>Glue needs permission to read your S3 archive and write metadata to the Glue Data Catalog.</p><ol><li>Navigate to <strong>IAM → Roles → Create role</strong></li><li>Under <strong>Trusted entity type</strong>: select <strong>“AWS service”</strong></li><li>Under <strong>Use case</strong>: search for and select <strong>“Glue”</strong></li><li>Click <strong>Next</strong></li><li>On the <strong>Add permissions</strong> page, attach:</li></ol><ul><li><strong>AWSGlueServiceRole</strong> — the AWS-managed policy for core Glue permissions</li></ul><p>6. You also need a custom S3 read policy. Click <strong>“Create policy”</strong> (opens in a new tab):</p><ul><li>Click <strong>JSON</strong> and paste the following:</li></ul><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:ListBucket&quot;<br>           ],<br>           &quot;Resource&quot;: [<br>             &quot;arn:aws:s3:::company-data-archive&quot;,<br>             &quot;arn:aws:s3:::company-data-archive/*&quot;<br>           ]<br>         }<br>       ]<br>     }</pre><ul><li>Name it GlueArchiveS3ReadPolicy</li><li>Click <strong>“Create policy”</strong></li></ul><p>7. Back on the role creation tab, click the refresh icon, search for GlueArchiveS3ReadPolicy, and attach it</p><p>8. Click <strong>Next</strong></p><p>9. Name the role: GlueArchiveRole</p><p>10. Click <strong>“Create role”</strong></p><h3>STEP 5 — Create the Glue Database</h3><ol><li>Navigate to <strong>AWS Glue</strong> in the AWS Console</li><li>In the left sidebar under <strong>Data Catalog</strong>, click <strong>“Databases”</strong></li><li>Click <strong>“Add database”</strong></li><li>Fill in:</li></ol><ul><li><strong>Name</strong>: archive_db</li><li><strong>Description</strong>: Archive database for historical PostgreSQL records (optional but helpful)</li><li><strong>Location — optional</strong>: s3://company-data-archive/archives/</li></ul><p>5. Click <strong>“Create database”</strong></p><p>You’ll see archive_db in the database list. It&#39;s empty — tables come next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ww_0LldZCQMSS7fT85oSEQ.png" /></figure><h3>STEP 6 — Create a Glue Table Using the Crawler (Automatic Schema Discovery)</h3><p>The Crawler scans your S3 prefix, reads your Parquet files, and generates a table definition automatically. Good for exploration and prototyping.</p><ol><li>In the Glue left sidebar, click <strong>“Crawlers”</strong></li><li>Click <strong>“Create crawler”</strong></li></ol><p><strong>Step 1 — Crawler properties:</strong></p><ul><li>Name: archive-crawler</li><li>Description: optional</li><li>Click <strong>Next</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbiltA3S7PkFtjSxGH3nGg.png" /></figure><p><strong>Step 2 — Choose data sources and classifiers:</strong></p><ul><li>Click <strong>“Add a data source”</strong></li><li>Data source: <strong>S3</strong></li><li>Network connection: leave blank</li><li>S3 path: s3://company-data-archive/archives/</li><li>Subsequent crawler runs: select <strong>“Crawl all sub-folders”</strong></li><li>Click <strong>“Add an S3 data source”</strong></li><li>Click <strong>Next</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*gBQ9KTowLXVc9REIHEYQfA.png" /></figure><p><strong>Step 3 — Configure security settings:</strong></p><ul><li>IAM role: select <strong>“Choose an existing IAM role”</strong></li><li>From the dropdown, select <strong>GlueArchiveRole</strong></li><li>Click <strong>Next</strong></li></ul><p><strong>Step 4 — Set output and scheduling:</strong></p><ul><li>Target database: click <strong>“Add database”</strong> or select <strong>archive_db</strong> from the dropdown</li><li>Table name prefix: leave blank (or enter archived_ if you want a prefix)</li><li>Crawler schedule: select <strong>“On demand”</strong></li><li>Click <strong>Next</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keMfEsWKaeG9TYzLG9VoiQ.png" /></figure><p><strong>Step 5 — Review and create:</strong></p><ul><li>Review all settings</li><li>Click <strong>“Create crawler”</strong></li></ul><p><strong>Run the Crawler:</strong></p><ol><li>Back on the Crawlers list, check the box next to archive-crawler</li><li>Click <strong>“Run”</strong></li><li>Watch the status column — it will show “Running” then “Succeeded” (typically 1–3 minutes)</li><li>Navigate to <strong>Databases → archive_db → Tables</strong> and you’ll see a new table created automatically</li></ol><p>The Crawler infers column types from your Parquet schema and partition keys from the key=value folder structure.</p><blockquote><strong><em>Important caveat</em></strong><em>: Crawler-inferred schemas are not always reliable. If your Parquet files have any inconsistency in nullability, precision, or mixed types in edge cases, the Crawler may generate a schema that causes query errors later. For production, use the manual approach below.</em></blockquote><h3>OR Create a Glue Table Manually (Recommended for Production)</h3><p>This is what we used in production. It takes 15–20 extra minutes but gives you full control over column types and partition definitions. Nothing changes unless you explicitly change it.</p><ol><li>In Glue, click <strong>“Tables”</strong> in the left sidebar</li><li>Click <strong>“Add table”</strong></li></ol><p><strong>Step 1 — Set table properties:</strong></p><ul><li>Table name: archived_records</li><li>Database: select archive_db from the dropdown</li><li>Description: Archived historical records from PostgreSQL (optional)</li><li>Click <strong>Next</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDQ3y-8PIdH6DsxaVBwtDg.png" /></figure><p><strong>Step 2 — Add a data store:</strong></p><ul><li>Data store: <strong>S3</strong></li><li>Data format: <strong>Parquet</strong></li><li>Include path: s3://company-data-archive/archives/</li><li>Click <strong>Next</strong></li></ul><p><strong>Step 3 — Choose a data format:</strong></p><ul><li>Format: <strong>Parquet</strong> (should already be selected)</li><li>Click <strong>Next</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znh8my_VPybeV7n3rReg3g.png" /></figure><p><strong>Step 4 — Define the schema:</strong></p><p>Click <strong>“Add ”</strong> for each column in your dataset. Example schema:</p><p>Column name Data type Notes record_id bigint Primary key from PostgreSQL event_type string payload string JSON content stored as string created_at timestamp Store in UTC updated_at timestamp Store in UTC status string region_code string amount double Use double, not float, for decimal precision user_id bigint</p><blockquote><strong><em>Do not add </em></strong><strong><em>dt or </em></strong><strong><em>logical_group_partition here.</em></strong><em> These are partition columns and go in the next step. If you add them both here and as partition keys, you&#39;ll see duplicate columns in query results.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0o022pZLFW9s-4WmxzGdMQ.png" /></figure><p><strong>Step 5 — Define partition keys:</strong></p><p>Scroll down to find the <strong>“Partition keys”</strong> section. Click <strong>“Add partition key”</strong> for each:</p><p>Partition key Data type Notes dt date First partition — matches folder level logical_group_partition string Second partition</p><p>Order matters here. The partition key order must match the S3 folder hierarchy — dt first, then logical_group_partition.</p><p><strong>Step 6 — Review and create:</strong></p><ul><li>Review the full definition — columns, partition keys, S3 location, and format</li><li>Click <strong>“Finish”</strong> or <strong>“Create”</strong></li></ul><p>You’ll now see archived_records under archive_db. Click into it to verify everything looks correct before moving on.</p><h3>STEP 7 — Configure Amazon Athena</h3><ol><li>Navigate to <strong>Amazon Athena</strong> in the AWS Console</li><li>If this is your first time using Athena in this region, you’ll see a prompt to set a query result location — address it immediately, Athena won’t run queries without it</li><li>Click the <strong>“Settings”</strong> tab (or the gear icon in the query editor)</li><li>Click <strong>“Manage”</strong> next to Query result location</li><li>Enter: s3://company-athena-query-results/</li><li>Under <strong>Encrypt query results</strong> (optional but recommended): select <strong>SSE-S3</strong></li><li>Click <strong>“Save”</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLwsuKWvtSqvCAgkqC5H_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*dNVrzWr2tjtDBc4V-zvVtA.png" /></figure><p><strong>Select your database:</strong></p><ol><li>Back in the main Athena query editor, find the <strong>database dropdown</strong> on the left panel</li><li>Select <strong>archive_db</strong></li><li>You should see archived_records appear in the tables list</li></ol><h3>STEP 8 — Load Partitions into the Catalog</h3><p>When you create a Glue table manually, the partitions sitting in S3 are not automatically known to the catalog. You must register them.</p><p><strong>Option A — MSCK REPAIR TABLE</strong></p><p>In the Athena query editor, run:</p><pre>MSCK REPAIR TABLE archive_db.archived_records;</pre><p>This scans your S3 base path, finds all key=value directory combinations, and registers each as a partition. It&#39;s the simplest approach for initial setup.</p><p>After it completes, verify partitions were found:</p><pre>SHOW PARTITIONS archive_db.archived_records;</pre><p>You should see output like:</p><pre>dt=2024-01-15/logical_group_partition=abc123<br>dt=2024-01-15/logical_group_partition=xyz789<br>dt=2024-01-16/logical_group_partition=abc123</pre><p><strong>Option B — ALTER TABLE ADD PARTITION</strong></p><p>For ongoing pipelines where you add new data regularly, register partitions explicitly after each upload:</p><pre>ALTER TABLE archive_db.archived_records<br>ADD PARTITION (dt = &#39;2024-01-15&#39;, logical_group_partition = &#39;abc123&#39;)<br>LOCATION &#39;s3://company-data-archive/archives/dt=2024-01-15/logical_group_partition=abc123/&#39;;</pre><p>This is more reliable than MSCK REPAIR for incremental loads because it&#39;s explicit and immediate — you don&#39;t need to scan the entire S3 prefix every time.</p><p><strong>Option C — Glue Console (for one-off additions)</strong></p><ol><li>Go to <strong>Glue → Tables → archived_records</strong></li><li>Click <strong>“Actions → View partitions”</strong></li><li>Click <strong>“Add partition”</strong></li><li>Enter the partition values and the exact S3 location for that partition</li></ol><h3>STEP 9 — Run a Verification Query</h3><p>Before trusting the setup for real work, run a test query:</p><pre>SELECT COUNT(*)<br>FROM archive_db.archived_records<br>WHERE dt = &#39;2024-01-15&#39;;</pre><p><strong>If you get zero results or an error, check these things in order:</strong></p><ol><li>Did MSCK REPAIR TABLE complete without errors? Run it again and watch for output.</li><li>Does the S3 path in the Glue table definition exactly match where your files are? Go to Glue → Tables → archived_records → <strong>&quot;Edit table&quot;</strong> and verify the include path.</li><li>Are the Parquet files valid? Download one file from S3 and inspect it locally with a Parquet reader.</li><li>Does the IAM user or role running Athena have s3:GetObject and s3:ListBucket permissions on the archive bucket? Check the IAM policy attached to your Athena execution context.</li><li>Did you accidentally include dt and logical_group_partition as regular columns inside the Parquet files? If so, remove them from the Parquet schema — partition values come from the S3 path, not the file content.</li></ol><h3>Query Examples in Athena</h3><p><strong>Count records for a specific date — reads only one day’s partitions:</strong></p><pre>SELECT COUNT(*)<br>FROM archive_db.archived_records<br>WHERE dt = DATE &#39;2024-01-15&#39;;</pre><p><strong>Filter by both partition keys — most efficient query possible:</strong></p><pre>SELECT record_id, event_type, created_at, status<br>FROM archive_db.archived_records<br>WHERE dt = DATE &#39;2024-01-15&#39;<br>  AND logical_group_partition = &#39;abc123&#39;<br>ORDER BY created_at DESC<br>LIMIT 100;</pre><p><strong>Aggregate over a date range — reads 31 days of partitions:</strong></p><pre>SELECT<br>  dt,<br>  event_type,<br>  COUNT(*) AS record_count<br>FROM archive_db.archived_records<br>WHERE dt BETWEEN DATE &#39;2024-01-01&#39; AND DATE &#39;2024-01-31&#39;<br>GROUP BY dt, event_type<br>ORDER BY dt, record_count DESC;</pre><p><strong>Find failed records across a quarter:</strong></p><pre>SELECT record_id, event_type, created_at, status<br>FROM archive_db.archived_records<br>WHERE dt BETWEEN DATE &#39;2024-01-01&#39; AND DATE &#39;2024-03-31&#39;<br>  AND status = &#39;FAILED&#39;<br>ORDER BY created_at DESC;</pre><p><strong>Daily record counts for a specific group over a full year:</strong></p><pre>SELECT dt, COUNT(*) AS daily_count<br>FROM archive_db.archived_records<br>WHERE logical_group_partition = &#39;abc123&#39;<br>  AND dt BETWEEN DATE &#39;2024-01-01&#39; AND DATE &#39;2024-12-31&#39;<br>GROUP BY dt<br>ORDER BY dt;</pre><blockquote><strong><em>Always filter on at least one partition key.</em></strong><em> A query with no </em><em>dt filter scans every partition in the archive. On two years of daily data, that could be thousands of partitions and hundreds of gigabytes. Athena will run it — slowly and at full cost.</em></blockquote><h3>Performance Optimization Lessons</h3><p><strong>Keep Parquet files between 128 MB and 512 MB.</strong> Athena has per-file overhead — opening the file, reading the Parquet footer, then reading data blocks. A partition with 200 tiny 5 MB files is slower and costs more to scan than the same data in 3 files of 200 MB each. If your batches produce small files, merge them before or after upload.</p><p><strong>Select only the columns you need.</strong> Because Parquet is columnar, SELECT record_id, status reads only two columns from disk. SELECT * reads everything, including large string columns like payload. Be explicit with column lists in production queries.</p><p><strong>Use </strong><strong>DATE literals, not string literals, for partition filters.</strong> Write WHERE dt = DATE &#39;2024-01-15&#39; rather than WHERE dt = &#39;2024-01-15&#39;. The former is type-safe and avoids implicit cast overhead.</p><p><strong>Don’t add more partition levels than you need.</strong> Each partition is a row in the Glue catalog. Millions of fine-grained partitions means slow MSCK REPAIR, slow partition listing, and planning overhead in Athena. Two levels was the right balance for our data volume.</p><h3>Cost Benefits</h3><p>RDS storage costs roughly 10x more per GB than S3 Standard. After archiving tens of millions of rows, we dropped to a smaller RDS instance class with less allocated storage — the month-over-month savings paid back the project quickly.</p><p>Athena at $5/TB scanned sounds expensive, but partition pruning and Parquet’s columnar compression mean most queries scan between 50 MB and 2 GB. A full month of ad-hoc historical queries typically cost a few dollars. S3 Standard storage for the archive itself runs around $0.023/GB/month — add an S3 lifecycle rule to transition data to S3 Infrequent Access after 30 days for roughly half that cost.</p><h3>Common Mistakes and How to Fix Them</h3><p><strong>Wrong datatype from the Crawler</strong> — The Crawler samples files and guesses types. Mixed types in edge cases produce wrong inference. Fix: define the table manually and specify types explicitly.</p><p><strong>Missing partitions after new uploads</strong> — New files in S3 aren’t visible to Athena until the partition is registered. Always run MSCK REPAIR TABLE or ALTER TABLE ADD PARTITION after every upload. Automate this.</p><p><strong>Timestamp timezone mismatches</strong> — Standardize on UTC before export. Store as timestamp type in Glue, not string. Filter with TIMESTAMP &#39;2024-01-15 00:00:00&#39; in queries.</p><p><strong>Partition columns inside the Parquet file</strong> — If dt and logical_group_partition appear as columns inside your Parquet files AND as partition keys in Glue, you&#39;ll get duplicate columns or errors. Drop them from the Parquet schema — their values come from the S3 path.</p><p><strong>Hundreds of tiny files</strong> — Slows queries, increases scan cost. Target 128–512 MB per file. Compact small files before finalizing the archive.</p><p><strong>Not setting the Athena results bucket before running queries</strong> — Every query will fail. Set the results location in Athena Settings first.</p><h3>Real Production Lessons Learned</h3><p><strong>Test the full pipeline with a small batch before writing millions of rows.</strong> Export 10,000 rows, run through every step — upload, Glue table, partition registration, Athena query. Catch type mismatches and path errors early. Redoing a 50-million-row export because of a column type problem is not how you want to spend a weekend.</p><p><strong>Manual Glue tables over the Crawler in production.</strong> The Crawler is convenient, but not predictable. A manually defined table means schema changes are deliberate and nothing drifts silently between Crawler runs.</p><p><strong>Partition registration is not optional — automate it.</strong> Every upload should trigger partition registration. No exceptions. If someone uploads data manually and forgets this step, queries return zero rows with no error message — just silence. That’s a confusing failure mode.</p><p><strong>Athena is for analytical queries, not millisecond lookups.</strong> For audit queries, compliance checks, and historical aggregations where waiting 5–30 seconds is acceptable — it’s excellent. For application-layer queries that need sub-second responses on archived data, you need something else.</p><p><strong>Keep an archival inventory in PostgreSQL.</strong> A small table tracking which date ranges have been archived, when, and to which S3 prefix costs almost nothing and answers a lot of operational questions without touching S3 or Athena at all.</p><p>The infrastructure side of this project is genuinely straightforward once you follow the steps in order. The real work is in the data export pipeline — validating that records match, handling nulls and edge cases, and making sure partition columns are handled correctly. Get that right and the AWS setup is the easy part.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8387733ef95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating S3 Bucket Replication Using Terraform]]></title>
            <link>https://jeshikphuyal.medium.com/automating-s3-bucket-replication-using-terraform-9dfdd03d025d?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dfdd03d025d</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Wed, 30 Apr 2025 08:07:54 GMT</pubDate>
            <atom:updated>2025-04-30T08:07:54.315Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Amazon S3 Cross-Region Replication (CRR) allows automatic, asynchronous copying of objects across buckets in different AWS regions. This is particularly useful for compliance, disaster recovery, or data locality.</p><p>In this article, we’ll walk through how to <strong>automate S3 bucket replication using Terraform</strong>, covering the configuration of source and destination buckets, IAM roles, and the replication rules.</p><h3>🔧 Use Case</h3><p>You have a bucket in us-east-1 and want to replicate its contents to another bucket in us-west-2. Rather than manually configuring it through the AWS Console, you want to <strong>automate</strong> this process using <strong>Terraform</strong> for consistency and scalability.</p><h3>🧰 Prerequisites</h3><ul><li>Terraform installed (&gt;= 1.0.0)</li><li>AWS CLI configured with the necessary permissions</li><li>Two AWS regions enabled (source and destination)</li></ul><h3>Step 1: Download and Install Terraform (if not previously installed)</h3><p><em>Method 1: Using PowerShell (Windows)</em></p><pre>winget install HashiCorp.Terraform</pre><p><em>Method 2: Manual Installation</em></p><ol><li>Download from the official Terraform site: <a href="https://www.terraform.io/downloads">https://www.terraform.io/downloads</a></li><li>Extract the ZIP file.</li><li>Move terraform.exe to a new folder in C:\Program Files\Terraform.</li></ol><h3>Step 2 : Add Terraform to the System PATH</h3><ol><li>Press Win + S, type <strong>&quot;environment variables&quot;</strong>, and open: Edit the system environment variables.</li><li>Click <strong>Environment Variables</strong>.</li><li>Under <strong>System variables</strong>, select Path, then click <strong>Edit</strong>.</li><li>Click <strong>New</strong> and add:</li></ol><pre>C:\Program Files\Terraform\<br># (or wherever you placed terraform.exe)</pre><p>5. Click <strong>OK</strong> to close all dialogs.</p><h3>Step 3: Verify Installation</h3><p>Open new terminal and run:</p><pre>terraform -version</pre><h3>Step 4: Set Up Project Directory Structure</h3><p>Create a project folder and organize files like this:</p><pre>s3-replication/<br>├── main.tf<br>├── variables.tf<br>├── provider.tf<br>├── buckets.tf<br>├── iam.tf<br>└── replication.tf</pre><h3>Step 5: Define the Provider</h3><p>📄 provider.tf</p><pre>provider &quot;aws&quot; {<br>  region     = var.aws_region<br>  access_key = &quot;xxxxxxxxxxxxxxxxxx&quot;<br>  secret_key = &quot;xxxxxxxxxxxxxxxxxxxxxxxxxx&quot;<br>}<br>provider &quot;aws&quot; {<br>  alias      = &quot;destination&quot;<br>  region     = var.destination_region<br>  access_key = &quot;xxxxxxxxxxxxxxxxxx&quot;<br>  secret_key = &quot;xxxxxxxxxxxxxxxxxxxxx&quot;<br>}<br>provider &quot;aws&quot; {<br>  alias      = &quot;source&quot;<br>  region     = var.aws_region<br>  access_key = &quot;xxxxxxxxxxxxxxxxxx&quot;<br>  secret_key = &quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;<br>}</pre><h3>Step 6: Define Your Variables</h3><p>📄 variables.tf</p><pre>variable &quot;aws_region&quot; {<br>  default = &quot;ap-south-1&quot; #source region <br>}<br>variable &quot;source_bucket_name&quot; {<br>  default = &quot;replications3terraform&quot; #unique bucket name forsource<br>}<br>variable &quot;destination_bucket_name&quot; {<br>  default = &quot;terraformreplications3&quot; #unique bucket name for destination<br>}<br>variable &quot;destination_region&quot; {<br>  default = &quot;us-east-1&quot; # Change this to your actual destination region<br>}</pre><h3>Step 7: Create S3 Buckets and Enable Versioning</h3><p>📄 buckets.tf</p><pre># Source Bucket<br>resource &quot;aws_s3_bucket&quot; &quot;source&quot; {<br>  bucket = var.source_bucket_name<br>  provider = aws.source<br>}<br>resource &quot;aws_s3_bucket_versioning&quot; &quot;source_versioning&quot; {<br>  bucket = aws_s3_bucket.source.id<br>  provider = aws.source<br>  versioning_configuration {<br>    status = &quot;Enabled&quot;<br>  }<br>}<br># Destination Bucket (cross-region)<br>resource &quot;aws_s3_bucket&quot; &quot;destination&quot; {<br>  bucket   = var.destination_bucket_name<br>  provider = aws.destination<br>}<br>resource &quot;aws_s3_bucket_versioning&quot; &quot;destination_versioning&quot; {<br>  bucket   = aws_s3_bucket.destination.id<br>  provider = aws.destination<br>  versioning_configuration {<br>    status = &quot;Enabled&quot;<br>  }<br>}</pre><h3>Step 8: Define IAM Role and Policy for Replication</h3><p>📄 iam.tf</p><pre># IAM Role for S3 Replication<br>resource &quot;aws_iam_role&quot; &quot;replication_role&quot; {<br>  name = &quot;s3-replication-role-new&quot;<br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;,<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;,<br>        Principal = {<br>          Service = &quot;s3.amazonaws.com&quot;<br>        },<br>        Action = &quot;sts:AssumeRole&quot;<br>      }<br>    ]<br>  })<br>}<br># IAM Policy for replication access<br>resource &quot;aws_iam_policy&quot; &quot;replication_policy&quot; {<br>  name = &quot;s3-replication-policy&quot;<br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;,<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;,<br>        Action = [<br>          &quot;s3:GetObjectVersion&quot;,<br>          &quot;s3:GetObjectVersionAcl&quot;,<br>          &quot;s3:GetObjectVersionForReplication&quot;,<br>          &quot;s3:GetObjectLegalHold&quot;,<br>          &quot;s3:GetObjectVersionTagging&quot;,<br>          &quot;s3:GetObjectRetention&quot;<br>        ],<br>        Resource = &quot;${aws_s3_bucket.source.arn}/*&quot;<br>      },<br>      {<br>        Effect = &quot;Allow&quot;,<br>        Action = [<br>          &quot;s3:ReplicateObject&quot;,<br>          &quot;s3:ReplicateDelete&quot;,<br>          &quot;s3:ReplicateTags&quot;<br>        ],<br>        Resource = &quot;${aws_s3_bucket.destination.arn}/*&quot;<br>      }<br>    ]<br>  })<br>}<br># Attach the policy to the role<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;replication_attachment&quot; {<br>  role       = aws_iam_role.replication_role.name<br>  policy_arn = aws_iam_policy.replication_policy.arn<br>}</pre><h3>Step 9: Configure Replication Rule</h3><p>📄 replication.tf</p><pre>resource &quot;aws_s3_bucket_replication_configuration&quot; &quot;replication&quot; {<br>  bucket = aws_s3_bucket.source.id<br>  role   = aws_iam_role.replication_role.arn<br><br>rule {<br>    id     = &quot;replication-rule&quot;<br>    status = &quot;Enabled&quot;<br>    filter {<br>      prefix = &quot;&quot; # replicate all objects<br>    }<br>    destination {<br>      bucket        = &quot;arn:aws:s3:::${aws_s3_bucket.destination.bucket}&quot;<br>      storage_class = &quot;STANDARD&quot;<br>    }<br>      # Add this section to handle delete marker replication<br>      delete_marker_replication {<br>      status = &quot;Enabled&quot;  # Can also be set to &quot;Disabled&quot; depending on your use case<br>      }<br>    }<br>  }</pre><h3>Step 10: Optional Outputs</h3><p>📄 main.tf</p><pre># You can keep this file empty or use it for outputs<br>output &quot;source_bucket&quot; {<br>  value = aws_s3_bucket.source.id<br>}<br>output &quot;destination_bucket&quot; {<br>  value = aws_s3_bucket.destination.id<br>}</pre><h3>Step 11: Deploy the Infrastructure</h3><p>Open your terminal and run the following commands:</p><pre>terraform init       # Initialize Terraform<br>terraform apply      # Apply the configuration</pre><p>Type yes when prompted. And this is the output you will see once, you apply the infrastructure.</p><h3>Step 12: Testing the setup</h3><p>Once deployed, uploading any object to the <strong>source bucket, </strong>will automatically replicate it to the <strong>destination bucket.</strong></p><h3>Conclusion</h3><p>By following this guide, you’ve successfully set up a complete and automated <strong>S3 Bucket Replication</strong> pipeline using Terraform. This not only ensures consistent data backups across buckets but also enables better disaster recovery strategies and region-based availability. With Terraform, making changes to infrastructure becomes as easy as updating code, giving you flexibility, scalability, and automation — essential for modern cloud infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dfdd03d025d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Automating S3 Event Notifications with AWS Lambda and SNS Using Terraform]]></title>
            <link>https://jeshikphuyal.medium.com/automating-s3-event-notifications-with-aws-lambda-and-sns-using-terraform-b3c4a32615dc?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3c4a32615dc</guid>
            <category><![CDATA[aws-sns]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Wed, 30 Apr 2025 07:48:46 GMT</pubDate>
            <atom:updated>2025-04-30T07:48:46.310Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧩 Introduction</h3><p>Monitoring and automating cloud workflows is a crucial aspect of modern DevOps. A common requirement is to <strong>send notifications when a new file is uploaded to an Amazon S3 bucket</strong>. In this post, we will build a <strong>fully automated S3 → Lambda → SNS</strong> notification system using <strong>Terraform</strong> and deploy everything directly from <strong>VS Code</strong>.</p><p>By the end of this tutorial, you will have a system that:</p><ul><li>Detects new objects in an S3 bucket</li><li>Triggers a Lambda function</li><li>Publishes a message to an SNS topic</li><li>Sends an email notification to a subscriber</li></ul><h3>🛠️ Tools and Technologies</h3><ul><li><strong>AWS Services</strong>: S3, Lambda, SNS, IAM</li><li><strong>Terraform</strong>: Infrastructure as Code</li><li><strong>VS Code</strong>: Code editor with Terraform extension</li><li><strong>Node.js</strong>: For writing the Lambda function</li></ul><h3>🗂️ Project Structure</h3><pre>s3-lambda-sns-automation/<br>├── main.tf<br>├── variables.tf<br>├── outputs.tf<br>├── lambda/<br>│   └── index.js</pre><h3>🧪 Step-by-Step Implementation</h3><h3>✅ Step 1: Create Lambda Function Code</h3><p><strong>lambda/index.js</strong>:</p><pre>const AWS = require(&quot;aws-sdk&quot;);<br>const sns = new AWS.SNS();<br><br>exports.handler = async (event) =&gt; {<br>  const eventName = event.Records[0].eventName;<br>  const bucketName = event.Records[0].s3.bucket.name;<br>  const objectKey = event.Records[0].s3.object.key;<br><br>  const message = `S3 Event: ${eventName} occurred in bucket: ${bucketName}, key: ${objectKey}`;<br><br>  const params = {<br>    Message: message,<br>    TopicArn: process.env.SNS_TOPIC_ARN<br>  };<br><br>  await sns.publish(params).promise();<br>  return { statusCode: 200, body: JSON.stringify(&#39;Notification sent!&#39;) };<br>};</pre><h3>✅ Step 2: Define Terraform Configuration</h3><h4>main.tf:</h4><pre>provider &quot;aws&quot; {<br>  region = var.region<br>}<br><br>resource &quot;aws_s3_bucket&quot; &quot;upload_bucket&quot; {<br>  bucket = &quot;my-sns-trigger-bucket-example&quot;<br>  force_destroy = true<br>}<br><br>resource &quot;aws_sns_topic&quot; &quot;notify_topic&quot; {<br>  name = &quot;s3-event-topic&quot;<br>}<br><br>resource &quot;aws_sns_topic_subscription&quot; &quot;email_sub&quot; {<br>  topic_arn = aws_sns_topic.notify_topic.arn<br>  protocol  = &quot;email&quot;<br>  endpoint  = var.email<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;lambda_exec_role&quot; {<br>  name = &quot;lambda-s3-sns-role-demo&quot;<br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;,<br>    Statement = [{<br>      Action = &quot;sts:AssumeRole&quot;,<br>      Principal = {<br>        Service = &quot;lambda.amazonaws.com&quot;<br>      },<br>      Effect = &quot;Allow&quot;,<br>      Sid = &quot;&quot;<br>    }]<br>  })<br>}<br><br>resource &quot;aws_iam_policy_attachment&quot; &quot;lambda_policy_attach&quot; {<br>  name       = &quot;lambda-policy-attach&quot;<br>  roles      = [aws_iam_role.lambda_exec_role.name]<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole&quot;<br>}<br><br>resource &quot;aws_iam_role_policy&quot; &quot;lambda_sns_policy&quot; {<br>  name = &quot;lambda-sns-publish&quot;<br>  role = aws_iam_role.lambda_exec_role.id<br><br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;,<br>    Statement = [{<br>      Effect   = &quot;Allow&quot;,<br>      Action   = &quot;sns:Publish&quot;,<br>      Resource = aws_sns_topic.notify_topic.arn<br>    }]<br>  })<br>}<br><br>data &quot;archive_file&quot; &quot;lambda_zip&quot; {<br>  type        = &quot;zip&quot;<br>  source_dir  = &quot;${path.module}/lambda&quot;<br>  output_path = &quot;${path.module}/lambda.zip&quot;<br>}<br><br>resource &quot;aws_lambda_function&quot; &quot;s3_event_handler&quot; {<br>  filename         = data.archive_file.lambda_zip.output_path<br>  function_name    = &quot;s3-sns-handler&quot;<br>  role             = aws_iam_role.lambda_exec_role.arn<br>  handler          = &quot;index.handler&quot;<br>  runtime          = &quot;nodejs18.x&quot;<br>  source_code_hash = data.archive_file.lambda_zip.output_base64sha256<br><br>  environment {<br>    variables = {<br>      SNS_TOPIC_ARN = aws_sns_topic.notify_topic.arn<br>    }<br>  }<br>}<br><br>resource &quot;aws_lambda_permission&quot; &quot;allow_s3&quot; {<br>  statement_id  = &quot;AllowS3Invoke&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.s3_event_handler.arn<br>  principal     = &quot;s3.amazonaws.com&quot;<br>  source_arn    = aws_s3_bucket.upload_bucket.arn<br>}<br><br>resource &quot;aws_s3_bucket_notification&quot; &quot;s3_notify&quot; {<br>  bucket = aws_s3_bucket.upload_bucket.id<br><br>  lambda_function {<br>    lambda_function_arn = aws_lambda_function.s3_event_handler.arn<br>    events              = [&quot;s3:ObjectCreated:*&quot;, &quot;s3:ObjectRemoved:*&quot;]<br>  }<br><br>  depends_on = [aws_lambda_permission.allow_s3]<br>}</pre><h3>✅ Step 3: Define Variables</h3><h4>variables.tf:</h4><pre>variable &quot;region&quot; {<br>  default = &quot;us-east-1&quot;<br>}<br><br>variable &quot;email&quot; {<br>  description = &quot;Email to subscribe to SNS topic&quot;<br>  type        = string<br>}</pre><h3>✅ Step 5: Output Values</h3><h4>outputs.tf:</h4><pre>output &quot;s3_bucket_name&quot; {<br>  value = aws_s3_bucket.upload_bucket.bucket<br>}<br><br>output &quot;sns_topic_arn&quot; {<br>  value = aws_sns_topic.notify_topic.arn<br>}</pre><h3>⚡ Deploying the Setup</h3><p>Run the following in your terminal:</p><pre>terraform init<br>terraform apply</pre><p>Provide your email address when prompted. Check your inbox to confirm the SNS subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnytmu3srtFFQXac0uxhjQ.png" /></figure><h3>🚀 Test the Notification</h3><h3>Upload a file:</h3><pre>echo &quot;test file&quot; &gt; file.txt<br>aws s3 cp file.txt s3://my-sns-trigger-bucket-example/</pre><h3>Delete a file:</h3><pre>aws s3 rm s3://my-sns-trigger-bucket-example/file.txt</pre><h3>💚 Cleanup</h3><p>To delete all resources:</p><pre>terraform destroy</pre><h3>🔧 Conclusion</h3><p>Using Terraform to automate S3 notifications through Lambda and SNS creates a powerful event-driven pipeline for monitoring and alerting. This setup is highly extendable for workflows like logging, triggering builds, or initiating security actions.</p><p>Stay tuned for more AWS automation content!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3c4a32615dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Scalable Static Website on AWS with Terraform: EC2, Load Balancer, and CloudFront]]></title>
            <link>https://jeshikphuyal.medium.com/deploying-a-scalable-static-website-on-aws-with-terraform-ec2-load-balancer-and-cloudfront-8044888f7807?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/8044888f7807</guid>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-load-balancer]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 09:11:08 GMT</pubDate>
            <atom:updated>2025-04-28T09:11:08.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fp24BblQK6MQiKFI0rhyRw.png" /></figure><p>This guide walks you through a step-by-step Terraform-based deployment pipeline for a static website hosted on an EC2 instance, fronted by an Application Load Balancer (ALB), and finally distributed using Amazon CloudFront.</p><h3>Steps:</h3><p><em>Step 1: Download and Install Terraform ( if not installed previously)<br>Step 2 : Add Terraform to the System PATH<br>Step 3: Verify Installation<br>Step 4: Hosting static site on EC2<br>Step 5: Add Load Balancer (ALB) in front of EC2<br>Step 6: Add CloudFront as CDN for the Load Balancer</em></p><h3>Step 1: Download and Install Terraform (if not previously installed)</h3><p><em>Method 1: Using PowerShell (Windows)</em></p><pre>winget install HashiCorp.Terraform</pre><p><em>Method 2: Manual Installation</em></p><ol><li>Download from the official Terraform site: <a href="https://www.terraform.io/downloads">https://www.terraform.io/downloads</a></li><li>Extract the ZIP file.</li><li>Move terraform.exe to a new folder in C:\Program Files\Terraform.</li></ol><h3>Step 2 : Add Terraform to the System PATH</h3><ol><li>Press Win + S, type <strong>&quot;environment variables&quot;</strong>, and open: Edit the system environment variables.</li><li>Click <strong>Environment Variables</strong>.</li><li>Under <strong>System variables</strong>, select Path, then click <strong>Edit</strong>.</li><li>Click <strong>New</strong> and add:</li></ol><pre>C:\Program Files\Terraform\<br># (or wherever you placed terraform.exe)</pre><p>5. Click <strong>OK</strong> to close all dialogs.</p><h3>Step 3: Verify Installation</h3><p>Open new terminal and run:</p><pre>terraform -version</pre><h3>Step 4: Hosting static site on EC2</h3><p>We’ll do this in your VS Code terminal.</p><p><strong>1. Create SSH Key Pair</strong></p><p>Make sure you have an existing .pem key file or generate one from the AWS Console (EC2 → Key Pairs).</p><p><strong>2. Create a Project Folder</strong></p><pre>mkdir ec2_alb_cf_terraform<br>cd ec2_alb_cf_terraform</pre><p><strong>3. Create the Required Files</strong></p><p>You’ll need 4 files:</p><h3>📄 main.tf</h3><p>This file sets up the main AWS components like the EC2 instance, security groups.</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br># Provider<br>provider &quot;aws&quot; {<br>  region = &quot;ap-south-1&quot;<br>  access_key = &quot;xxxxxxxxxxxxxxxxxxxx&quot;<br>  secret_key = &quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;<br>}<br>//EC2 and security groups<br><br>//CREATING EC2 INSTANCE<br># Generate SSH key pair<br>resource &quot;tls_private_key&quot; &quot;rsa_4096&quot; {<br>  algorithm = &quot;RSA&quot;<br>  rsa_bits  = 4096<br>}<br># # Upload the public key to AWS<br># resource &quot;aws_key_pair&quot; &quot;key_pair&quot; {<br>#   key_name   = var.key_name<br>#   public_key = tls_private_key.rsa_4096.public_key_openssh<br># }<br># Save the private key to local .pem file<br>resource &quot;local_file&quot; &quot;private_key&quot; {<br>  content  = tls_private_key.rsa_4096.private_key_pem<br>  filename = &quot;${var.key_name}.pem&quot;<br>}<br># Security group to allow SSH<br>resource &quot;aws_security_group&quot; &quot;ssh_access&quot; {<br>  name        = &quot;allow_ssh&quot;<br>  description = &quot;Allow SSH inbound traffic&quot;<br>  ingress {<br>  description = &quot;HTTP&quot;<br>  from_port   = 80<br>  to_port     = 80<br>  protocol    = &quot;tcp&quot;<br>  cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>}<br>  ingress {<br>    description = &quot;SSH&quot;<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br># Launch EC2 instance<br>resource &quot;aws_instance&quot; &quot;public_instance&quot; {<br>  ami                         = &quot;ami-0f1dcc636b69a6438&quot;<br>  instance_type               = &quot;t2.micro&quot;<br>  key_name                    = &quot;demo&quot; # change to your pem file name.<br>  vpc_security_group_ids      = [aws_security_group.ssh_access.id]<br>  user_data                   = file(&quot;${path.module}/user_data.sh&quot;)<br><br>  tags = {<br>    Name = &quot;DemoInstance&quot; # Change to your new instance name<br>  }<br>}</pre><h3>📄 user_data.sh</h3><p>This file is a bootstrap script that installs Apache and serves a static HTML page when the EC2 boots.</p><pre>#!/bin/bash<br>dnf update -y<br>dnf install -y httpd<br>systemctl start httpd<br>systemctl enable httpd<br>echo &quot;&lt;h1&gt;Hello from EC2 - Static Website&lt;/h1&gt;&quot; &gt; /var/www/html/index.html</pre><h3>📄 variables.tf</h3><p>This file allows for better configuration management by parameterizing values. For this case , pem file name.</p><pre>variable &quot;key_name&quot; {<br>  default = &quot;demo&quot; # your pem file name.<br>}</pre><h3>📄 outputs.tf</h3><p>defines output values like the EC2 public IP, ALB DNS, and CloudFront URL to quickly access deployed resources.</p><pre>output &quot;ec2_public_ip&quot; {<br>  value = aws_instance.public_instance.public_ip<br>  description = &quot;Public IP of the EC2 instance&quot;<br>}</pre><h3>▶️ Deploy EC2 and host a static site</h3><p>Deploy the changes with:</p><pre>terraform init<br>terraform apply</pre><p>Check if it run successfully, following output is seen in terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12QNquYoEFDqdm0-hY2C3g.png" /></figure><p>Now, Go to AWS Console → EC2 , you can see new instance is launched. Then copy the public IPv4 address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WfUeQkz1aaQOjxA6zZwTUA.png" /></figure><h3>Step 5: Add Load Balancer (ALB) in front of EC2</h3><ol><li><strong>Create a new file to set up the main ALB components for static site.</strong></li></ol><h3>📄 alb.tf</h3><pre>resource &quot;aws_lb_target_group&quot; &quot;tg&quot; {<br>  name     = &quot;web-tg&quot;<br>  port     = 80<br>  protocol = &quot;HTTP&quot;<br>  vpc_id   = &quot;vpc-042c50710d18ef2bb&quot;  # Updated with your VPC ID<br>}<br>resource &quot;aws_lb&quot; &quot;alb&quot; {<br>  name               = &quot;web-alb&quot;<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [aws_security_group.ssh_access.id]  # Correct security group reference<br>  subnets            = [&quot;subnet-0825ebaeee72cfaa2&quot;, &quot;subnet-030c31a108ba88fda&quot;]  # Updated with your subnet IDs<br>}<br>resource &quot;aws_lb_listener&quot; &quot;listener&quot; {<br>  load_balancer_arn = aws_lb.alb.arn<br>  port              = 80<br>  protocol          = &quot;HTTP&quot;<br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.tg.arn<br>  }<br>}<br>resource &quot;aws_lb_target_group_attachment&quot; &quot;web_instance&quot; {<br>  target_group_arn = aws_lb_target_group.tg.arn<br>  target_id        = aws_instance.public_instance.id  # Correct EC2 instance reference<br>  port             = 80<br>}</pre><p>2. <strong>Add following content on “<em>outputs.tf”</em> file:</strong></p><pre>output &quot;alb_dns_name&quot; {<br>  value = aws_lb.alb.dns_name<br>}</pre><p>3. <strong>Apply the changes with:</strong></p><pre>terraform apply</pre><p>When, ran successfully following output is seen on terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEq1UCLfHkX5ZpN-CMLdEw.png" /></figure><p>Now, Go to AWS Console → EC2 → Load balancers, you can see new load balancer has been created. Then copy the DNS name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AqOdtgcQSMDMQ5BuYwa_5Q.png" /></figure><h3>Step 6: Add CloudFront as CDN for the Load Balancer</h3><ol><li><strong>Create a new file to set up the main cloud front components for static site.</strong></li></ol><h3>📄cloudfront.tf</h3><pre>resource &quot;aws_cloudfront_distribution&quot; &quot;cdn&quot; {<br>  origin {<br>    domain_name = aws_lb.alb.dns_name<br>    origin_id   = &quot;alb-origin&quot;<br>    <br>    custom_origin_config {<br>      http_port              = 80<br>      https_port             = 443<br>      origin_protocol_policy = &quot;http-only&quot;<br>      origin_ssl_protocols   = [&quot;TLSv1.2&quot;]<br>    }<br>  }<br>  enabled             = true<br>  is_ipv6_enabled     = true<br>  default_root_object = &quot;index.html&quot;<br>  default_cache_behavior {<br>    allowed_methods  = [&quot;GET&quot;, &quot;HEAD&quot;]<br>    cached_methods   = [&quot;GET&quot;, &quot;HEAD&quot;]<br>    target_origin_id = &quot;alb-origin&quot;<br>    forwarded_values {<br>      query_string = false<br>      cookies {<br>        forward = &quot;none&quot;<br>      }<br>    }<br>    viewer_protocol_policy = &quot;allow-all&quot;<br>  }<br>  restrictions {<br>    geo_restriction {<br>      restriction_type = &quot;none&quot;<br>    }<br>  }<br>  viewer_certificate {<br>    cloudfront_default_certificate = true<br>  }<br>  tags = {<br>    Name = &quot;StaticSiteCloudFront&quot;<br>  }<br>}</pre><p>2. <strong>Add following content on “<em>outputs.tf”</em> file:</strong></p><pre>output &quot;cloudfront_domain&quot; {<br>  value = aws_cloudfront_distribution.cdn.domain_name<br>}</pre><p>3. <strong>Re-apply the changes with:</strong></p><pre>terraform apply</pre><p>When, ran successfully following output is seen on terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7rAarO90_bLBSVdQXTCbQ.png" /></figure><p>Now, Go to AWS Console → CloudFront → Distributers , you can see new distributer has been created. Then copy the Domain name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DkGhHrXutpOU1XHIR0QjFg.png" /></figure><h3>Cleanup</h3><p>To remove all created resources:</p><pre>terraform destroy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3AnFaVWpPhzsxIeBVzCJw.png" /></figure><h3>Conclusion</h3><p>With just a few Terraform files, we created a highly available and globally distributed static website infrastructure. By combining EC2, ALB, and CloudFront, we ensure speed, reliability, and scale — all provisioned automatically using code. This setup is great for personal projects, portfolios, or even production-ready services. And the best part? You can destroy everything just as easily using terraform destroy .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8044888f7807" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Provisioning of EC2 Instance and S3 Bucket with Terraform]]></title>
            <link>https://jeshikphuyal.medium.com/automated-provisioning-of-ec2-instance-and-s3-bucket-with-terraform-7181771e2764?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/7181771e2764</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 07:57:11 GMT</pubDate>
            <atom:updated>2025-04-28T07:57:40.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebRFe0Sl7AYeK8UNlxsaZw.png" /></figure><p>This guide walks you through installing Terraform, setting up the environment, and deploying an <strong>EC2 instance</strong> and <strong>S3 bucket</strong> on AWS using Terraform.</p><h3>Steps:</h3><p><em>Step 1: Download and Install Terraform<br>Step 2 : Add Terraform to the System PATH<br>Step 3: Verify Installation<br>Step 4: Launch EC2 with Terraform<br>Step 5: Create S3 using Terraform</em></p><h3>Step 1: Download and Install Terraform</h3><p><em>Method 1: Using PowerShell (Windows)</em></p><pre>winget install HashiCorp.Terraform</pre><p><em>Method 2: Manual Installation</em></p><ol><li>Download from the official Terraform site: <a href="https://www.terraform.io/downloads">https://www.terraform.io/downloads</a></li><li>Extract the ZIP file.</li><li>Move terraform.exe to a new folder in C:\Program Files\Terraform.</li></ol><h3>Step 2 : Add Terraform to the System PATH</h3><ol><li>Press Win + S, type <strong>&quot;environment variables&quot;</strong>, and open: Edit the system environment variables.</li><li>Click <strong>Environment Variables</strong>.</li><li>Under <strong>System variables</strong>, select Path, then click <strong>Edit</strong>.</li><li>Click <strong>New</strong> and add:</li></ol><pre>C:\Program Files\Terraform\<br># (or wherever you placed terraform.exe)</pre><p>5. Click <strong>OK</strong> to close all dialogs.</p><h3>Step 3: Verify Installation</h3><p>Open new terminal and run:</p><pre>terraform -version</pre><h3>Step 4: Launch EC2 with Terraform</h3><p>We’ll do this in your VS Code terminal.</p><p><strong>1. Create SSH Key Pair</strong></p><p>Make sure you have an existing .pem key file or generate one from the AWS Console (EC2 → Key Pairs).</p><p><strong>2. Create a Project Folder</strong></p><pre>mkdir terraform-ec2<br>cd terraform-ec2</pre><p><strong>3. Create the Required Files</strong></p><p>You’ll need 3 files:</p><h3>📄 main.tf</h3><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br>provider &quot;aws&quot; {<br>  region = &quot;ap-south-1&quot;<br>  access_key = &quot;&quot; # provide your access_key<br>  secret_key = &quot;&quot; # provide your secret key <br>}<br># Generate SSH key pair<br>resource &quot;tls_private_key&quot; &quot;rsa_4096&quot; {<br>  algorithm = &quot;RSA&quot;<br>  rsa_bits  = 4096<br>}<br># # Upload the public key to AWS<br># resource &quot;aws_key_pair&quot; &quot;key_pair&quot; {<br>#   key_name   = var.key_name<br>#   public_key = tls_private_key.rsa_4096.public_key_openssh<br># }<br># Save the private key to local .pem file<br>resource &quot;local_file&quot; &quot;private_key&quot; {<br>  content  = tls_private_key.rsa_4096.private_key_pem<br>  filename = &quot;${var.key_name}.pem&quot;<br>}<br># Security group to allow SSH<br>resource &quot;aws_security_group&quot; &quot;ssh_access&quot; {<br>  name        = &quot;allow_ssh&quot; #give unique name<br>  description = &quot;Allow SSH inbound traffic&quot;<br>  ingress {<br>    description = &quot;SSH&quot;<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br># Launch EC2 instance<br>resource &quot;aws_instance&quot; &quot;public_instance&quot; {<br>  ami                         = &quot;ami-0f1dcc636b69a6438&quot;<br>  instance_type               = &quot;t2.micro&quot;<br>  key_name                    = &quot;demo&quot; # change to your pem file name<br>  vpc_security_group_ids      = [aws_security_group.ssh_access.id]<br>  tags = {<br>    Name = &quot;EC2-terraformInstance&quot; # change to your required instance<br>  }<br>}</pre><h3>📄 variables.tf</h3><pre>variable &quot;key_name&quot; {<br>  default = &quot;servicekey&quot; # change to your pem file name<br>}</pre><h3>📄 output.tf</h3><pre>output &quot;instance_ip&quot; {<br>  value = aws_instance.public_instance.public_ip<br>}<br><br>output &quot;pem_file_path&quot; {<br>  value = local_file.private_key.filename<br>}</pre><p><strong>4: Initialize and Apply Terraform</strong></p><p><strong><em>a) Initialize Terraform</em></strong></p><p>In terminal (inside terraform-ec2 folder):</p><pre>terraform init</pre><p><strong><em>b) Preview the Plan</em></strong></p><pre>terraform plan</pre><p><strong><em>c) Apply changes</em></strong></p><pre>terraform apply<br><br># Type yes when prompted.</pre><p>If successful, you will see following output in terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNUcjsfK7ALDAPaZAYR_dQ.png" /></figure><p>✅ <em>After applying Terraform, you can log in to the AWS Console and navigate to the EC2 Dashboard. You will see your EC2 instance running.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A47e_2EKfKAbknWPTBwi3g.png" /></figure><p><strong>5 : Destroying EC2 Instance</strong></p><p><em>Preview What Will Be Destroyed:</em></p><pre>terraform plan -destroy</pre><p><em>Destroy the EC2 instance:</em></p><pre>terraform destroy</pre><p>If successfull, you will see following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyFGeMSf30ztp8B2ozxTdw.png" /></figure><h3>Create S3 using Terraform</h3><p>To create S3 using Terraform we will need only one file.</p><p><strong>1 : Create a new file</strong></p><h3>📄s3-bucket.tf file</h3><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br>provider &quot;aws&quot; {<br>  region = &quot;ap-south-1&quot;<br>  access_key = &quot;xxxxxxxxxxxxx&quot;<br>  secret_key = &quot;xxxxxxxxxxxxxxxxxxxxxxxxxx&quot;<br>}<br>resource &quot;aws_s3_bucket&quot; &quot;my_bucket&quot; {<br>  bucket = &quot;terrasadis3bucket&quot;  # MUST be globally unique<br>  force_destroy = true  # Allows deletion even if objects exist<br>}<br>output &quot;bucket_name&quot; {<br>  value = aws_s3_bucket.my_bucket.bucket<br>}</pre><p><strong>2 : Initialize and Apply Terraform</strong></p><p><strong><em>a) Initialize Terraform</em></strong></p><p>In terminal (inside terraform-ec2 folder):</p><pre>terraform init</pre><p><strong><em>b) Preview the Plan</em></strong></p><pre>terraform plan</pre><p><strong><em>c) Apply changes</em></strong></p><pre>terraform apply</pre><pre># Type yes when prompted.</pre><p>If successful, you will see following output in terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_0UHnT6iyp-YqZW8ItEpw.png" /></figure><p>✅ <em>After applying Terraform, you can log in to the AWS Console and navigate to the S3 Dashboard. You will see your new S3 bucket has been created.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFEDoTgZLXYN5FJf4wFpWQ.png" /></figure><p><strong>3 : Destroy S3 Bucket</strong></p><p>To destroy the s3 bucket run :</p><pre>terraform destroy</pre><p>If successful, you will see following output in terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CI9sAclB6CMPD9LGj40Rug.png" /></figure><h3>Conclusion</h3><p>Using Terraform simplifies the provisioning of cloud infrastructure. With just a few configuration files and commands, you’ve successfully launched and managed an <strong>EC2 instance</strong> and an <strong>S3 bucket</strong> on AWS. This approach makes your deployments <strong>reproducible</strong>, <strong>scalable</strong>, and <strong>automated</strong>, ensuring efficient infrastructure management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7181771e2764" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Website Migration From Lightsail To EC2.]]></title>
            <link>https://jeshikphuyal.medium.com/wordpress-website-migration-from-lightsail-to-ec2-22e09f6ddb82?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/22e09f6ddb82</guid>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[lightsail]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 08:43:09 GMT</pubDate>
            <atom:updated>2025-05-06T07:29:20.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>Website Migration From Lightsail To EC2 instance.</h3><p><strong>Amazon EC2 (Elastic Compute Cloud)</strong> is a web service offered by AWS that provides resizable, secure compute capacity in the cloud. It allows users to launch virtual servers, known as instances, on demand and configure them with various operating systems, networking options, and storage types. EC2 is highly flexible and scalable, supporting a wide range of instance types to meet different performance and budget requirements. It’s ideal for running enterprise applications, web servers, and development environments. Users have full control over their instances, including SSH access, security group configurations, and the ability to automate deployments through tools like AWS CloudFormation or Terraform.</p><p><strong>Amazon Lightsail</strong> is a simplified cloud platform from AWS designed for users who need a straightforward way to deploy and manage virtual private servers. It bundles compute, storage, and networking into an easy-to-use interface, making it suitable for small businesses, developers, and those new to the cloud. Lightsail offers pre-configured blueprints for common applications like WordPress, LAMP, and Node.js, allowing users to launch servers quickly without deep technical knowledge. While it lacks the advanced customization and scaling options of EC2, Lightsail is cost-effective and user-friendly, making it ideal for simple websites, test environments, and small-scale projects.</p><h3>Step 1: Host WordPress in AWS Lightsail</h3><ol><li><strong>Create a Lightsail Instance</strong></li></ol><ul><li>Go to the <a href="https://lightsail.aws.amazon.com/">AWS Lightsail Console</a>.</li><li>Click <strong>Create Instance</strong> → Select <strong>Linux/Unix</strong> → Choose <strong>WordPress Blueprint</strong>.</li><li>Choose an instance plan (cheapest is fine for testing).</li><li>Set a name (e.g., wordpress-ls) and create the instance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCJt5IeBP_MqyUmENRxEAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*408hWDbfrqEMZzQyFld60Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AF7_eX8ai8tp0ernviZMiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Umhkwgxt8yYP6uo1x75jtg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shm28ZJQIYuqR5MSD_-MCQ.png" /></figure><p><strong>2. Access WordPress Admin Panel</strong></p><ul><li>Connect to your instance using SSH (click <strong>“Connect using SSH”</strong> in Lightsail)</li><li>Type: cat bitnami_application_password</li><li>Copy the password displayed</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6FgnmNgzQDnRFski4M7qQ.png" /></figure><ul><li>Open http://&lt;Lightsail-IP&gt;/wp-admin/.</li></ul><p>Now Login to the wordpress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPe5bH2lQdZwjdduoD0ofg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8CNWIZ4hgfjfMd6RpThSg.png" /></figure><h3>Step 2: Backup the WordPress Site in S3</h3><ol><li><strong>Create S3 Bucket.</strong></li></ol><ul><li>Go to S3 in AWS Console</li><li>Click “Create bucket”</li><li>Name it (e.g., “backup-wordpress-demo”)</li><li>Keep default settings, click “Create bucket”</li></ul><p><strong>2. Backup the Database</strong>:</p><ul><li>In <strong>Lightsail SSH Terminal</strong>, run:<br>This will generate a pwd.</li></ul><pre>cat /opt/bitnami/wordpress/wp-config.php</pre><pre># Use the Bitnami MariaDB command (note the correct path)<br>/opt/bitnami/mariadb/bin/mariadb-dump -u bn_wordpress -p bitnami_wordpress &gt; wordpress-dump.sql<br><br># Enter the password when prompted</pre><p><strong>2. Backup WordPress Files</strong>:</p><pre>sudo zip -r wordpress-site.zip /opt/bitnami/wordpress/wp-content /opt/bitnami/wordpress/wp-config.php</pre><ul><li><strong>Set Up AWS CLI:</strong></li></ul><pre>sudo apt install awscli -y<br>aws configure<br># Enter your AWS Access Key, Secret Key, region (e.g., ap-south-1), and output format (json)</pre><ul><li>Enter your <strong>AWS Access Key &amp; Secret Key</strong>.</li><li>Choose <strong>region</strong> (e.g., us-east-1).</li><li>Upload backup files to S3:</li></ul><pre>aws s3 cp wordpress-dump.sql s3://Your-Bucket-Name/<br>aws s3 cp wordpress-site.zip s3://Your-Bucket-Name/</pre><p>✅ <strong>Now, the WordPress backup is safely stored in S3!</strong></p><h3>Step 3: Migrate WordPress to EC2</h3><h3>1. Launch an EC2 Instance</h3><ol><li>Go to <strong>AWS EC2 Console</strong> → Click <strong>Launch Instance</strong>.</li><li><strong>Choose Amazon Linux or Ubuntu</strong>.</li><li><strong>Select Instance Type</strong> (t2.micro for free-tier).</li><li><strong>Configure Security Group</strong>:</li></ol><ul><li>Allow <strong>HTTP (80)</strong>, <strong>HTTPS (443)</strong>, and <strong>SSH (22)</strong>.</li></ul><p><strong>5. Launch &amp; Download Key Pair</strong> (e.g., ec2-key.pem).</p><h3>2. Connect to EC2 &amp; Install LAMP Stack</h3><p><strong>Connect to EC2 via SSH:</strong></p><pre>ssh -i ec2-key.pem ec2-user@&lt;ec2-public-ip&gt;</pre><p><strong>Install LAMP Stack (Apache, MySQL, PHP)</strong></p><pre># Update system<br>sudo dnf update -y<br><br># Install Apache<br>sudo dnf install httpd -y<br>sudo systemctl start httpd<br>sudo systemctl enable httpd<br><br># Install MariaDB (MySQL)<br>sudo dnf install mariadb105-server -y<br>sudo systemctl start mariadb<br>sudo systemctl enable mariadb<br><br># Secure MySQL installation<br>sudo mysql_secure_installation<br># Answer prompts:<br># - Set root password: Y<br># - Remove anonymous users: Y<br># - Disallow root login remotely: Y<br># - Remove test database: Y<br># - Reload privilege tables: Y<br><br># Install PHP and extensions<br>sudo dnf install php php-mysqlnd php-json php-xml php-mbstring php-curl php-zip unzip -y<br><br># Restart Apache to apply PHP settings<br>sudo systemctl restart httpd</pre><h4>✅ <strong>LAMP stack is now installed!</strong> 🚀</h4><h3><strong>3. Install AWS CLI and Download Backups</strong></h3><pre># Install AWS CLI<br>sudo dnf install aws-cli -y<br><br># Configure AWS CLI<br>aws configure<br># Enter your credentials and region<br><br># Download backups from S3<br>aws s3 cp s3://Your-Bucket-Name/wordpress-dump.sql .<br>aws s3 cp s3://Your-Bucket-Name/wordpress-site.zip .</pre><h4>Install WordPress Core</h4><pre># Navigate to the WordPress installation directory<br>cd /var/www/html<br><br># Remove default WordPress files (be cautious with this step)<br>sudo rm -rf *  <br><br># Download the latest WordPress<br>sudo wget https://wordpress.org/latest.tar.gz<br><br># Extract the WordPress files<br>sudo tar -xzf latest.tar.gz --strip-components=1<br><br># Clean up the tar file<br>sudo rm latest.tar.gz</pre><h4>Extract Backup Content</h4><pre># Create a temporary directory for extraction<br>sudo mkdir -p /tmp/wp-extract<br><br># Extract the backup of the WordPress site files<br>sudo unzip ~/wordpress-site.zip -d /tmp/wp-extract<br><br># Replace the wp-content directory with your backup<br>sudo rm -rf /var/www/html/wp-content<br>sudo cp -r /tmp/wp-extract/opt/bitnami/wordpress/wp-content /var/www/html/<br><br># Copy the wp-config.php file (but don’t overwrite it yet)<br>sudo cp /tmp/wp-extract/opt/bitnami/wordpress/wp-config.php /tmp/wp-config-backup.php</pre><p>✅ <strong>WordPress files are now in the web directory!</strong></p><h3>4. Create Database and User</h3><p>You’ll need to create a new database and user for WordPress:</p><pre># Connect to MySQL<br>sudo mysql -u root -p<br><br># In the MySQL prompt:<br>CREATE DATABASE wordpress;<br>CREATE USER &#39;user&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;choose-strong-password&#39;;<br>GRANT ALL PRIVILEGES ON wordpress.* TO &#39;user&#39;@&#39;localhost&#39;;<br>FLUSH PRIVILEGES;<br>EXIT;</pre><p>Make sure to replace choose-strong-password with a strong password for the user.</p><p><strong>Import the Database:</strong></p><pre># Check your home directory<br>ls ~/<br><br># If the file is in your home directory, use this command to move it<br>mv ~/wordpress-dump.sql /var/www/html/<br><br>cd /var/www/html<br>mysql -u user -p wordpress &lt; wordpress-dump.sql</pre><p>✅ <strong>Database is now restored!</strong> 🎉</p><h3>5. Configure WordPress</h3><ol><li><strong>Create </strong><strong>wp-config.php:</strong></li></ol><pre># Create wp-config.php<br><br>cd /var/www/html<br>sudo cp wp-config-sample.php wp-config.php<br>sudo nano wp-config.php</pre><p>2. <strong>Update these lines:</strong></p><pre>define(&#39;DB_NAME&#39;, &#39;wordpress&#39;);<br>define(&#39;DB_USER&#39;, &#39;user&#39;);<br>define(&#39;DB_PASSWORD&#39;, &#39;choose-strong-password&#39;);<br>define(&#39;DB_HOST&#39;, &#39;localhost&#39;);</pre><p>In your wp-config.php, Add the following lines just after the <strong>Database Settings</strong>:</p><pre>define(&#39;WP_HOME&#39;, &#39;http://&lt;your-ec2-ip&gt;&#39;);<br>define(&#39;WP_SITEURL&#39;, &#39;http://&lt;your-ec2-ip&gt;&#39;);</pre><p><strong>Save and exit the file</strong> by pressing CTRL + X, then Y, and hit Enter.</p><p>3. <strong>Set Proper Permissions:</strong></p><p>Ensure that the web server has the proper permissions to read and write the files in your WordPress directory:</p><pre>sudo chown -R apache:apache /var/www/html<br>sudo chmod -R 755 /var/www/html</pre><p>4. <strong>Restart Apache Web Server:</strong></p><pre>sudo systemctl restart httpd</pre><p>✅ <strong>WordPress is now linked to the database!</strong> 🚀</p><h3><strong>Fix: Reset Password for </strong>user</h3><p>Try resetting the password using MySQL:</p><ol><li><strong>Log into MySQL as root</strong></li></ol><pre>sudo mysql -u root -p</pre><p>2.<strong> Select the WordPress database</strong></p><pre>USE wordpress;</pre><p>3.<strong> Reset the password for </strong>user</p><pre>UPDATE wp_users SET user_pass = MD5(&#39;YourStrongPassword123&#39;) WHERE user_login = &#39;user&#39;;</pre><p><em>(Replace </em><em>YourStrongPassword123 with your preferred password.)</em></p><p>4.<strong> Exit MySQL</strong></p><pre>EXIT;</pre><h3>6. Access WordPress on EC2</h3><p>Open a browser and visit:</p><pre>http://&lt;ec2-public-ip&gt;/wp-admin</pre><h3><strong>ENTER</strong></h3><ul><li><strong>Username:</strong> user</li><li><strong>Password:</strong> YourStrongPassword123</li></ul><p>🎉 <strong>WordPress is now hosted on EC2!</strong> 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBrk4Aa0myBOZK09U-yepg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZPwdmKuz1NCSipclczDcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6oWjv4jkMH2UWMTKpZ58Q.png" /></figure><p>You now have access to your Wordpress and files.</p><h3>✅ Summary</h3><p>✔ Hosted WordPress in <strong>Lightsail</strong><br> ✔ Backed up site &amp; stored in <strong>S3</strong><br> ✔ Migrated WordPress to <strong>EC2</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22e09f6ddb82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Cloud Access: How to Create Your Private Tunnel to AWS EC2 Instances]]></title>
            <link>https://jeshikphuyal.medium.com/secure-cloud-access-how-to-create-your-private-tunnel-to-aws-ec2-instances-e79dc304b67f?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/e79dc304b67f</guid>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[openvpn]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 07:03:22 GMT</pubDate>
            <atom:updated>2025-04-02T07:09:17.368Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Security is paramount when working with cloud infrastructure. If you’re managing AWS EC2 instances that contain sensitive data or critical applications, directly exposing them to the public internet is a significant security risk.</p><p>Enter OpenVPN — your solution for establishing secure, encrypted connections to private EC2 instances from anywhere in the world. This step-by-step guide will walk you through creating your own private tunnel into your AWS environment, combining robust security with the flexibility remote access demands.</p><h3>Why Use a VPN for AWS Access?</h3><p>Before diving into the technical steps, let’s understand why this approach matters:</p><ul><li><strong>Enhanced Security</strong>: All traffic between your local machine and EC2 instances is encrypted</li><li><strong>Access Control</strong>: Limit who can connect to your private instances</li><li><strong>Simplified Network Architecture</strong>: No need to assign public IPs to all your instances</li><li><strong>Compliance</strong>: Meet security requirements for sensitive workloads</li></ul><h3>What You’ll Need</h3><ul><li>An AWS account</li><li>Basic familiarity with EC2 and security groups</li><li>Administrative access to your local machine</li><li>About 20 minutes of your time</li></ul><h3>Step-by-Step Implementation</h3><h3>Step 1: Launch a Dedicated VPN EC2 Instance</h3><p>First, we’ll create the EC2 instance that will serve as our VPN gateway:</p><ol><li>Navigate to the <strong>EC2 Dashboard</strong> → <strong>Instances</strong> → <strong>Launch Instance</strong></li><li>Select <strong>Ubuntu</strong> as your AMI</li><li>Choose an instance type (t2.micro works well for testing and is free-tier eligible)</li><li>Create or select an existing key pair for SSH access</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGRmRnQFlHkWpDn3MV8YNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWx3uXK4EqfFiaOWihvPQA.png" /></figure><h3>Step 2: Configure Security Groups</h3><p>Security group configuration is crucial for the VPN server to function properly:</p><ol><li>Under <strong>Network Settings</strong>, click <strong>Edit</strong></li><li>Configure the security group with the following rules:</li></ol><ul><li>Type: SSH — Port 22 (for administrative access)</li><li>Type: UDP — Port 1194 (standard OpenVPN port)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQPwoWhu_YnFXXFMuBc97A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1Wi3AF3xMmlF1BkQ18rqw.png" /></figure><p>Complete the configuration and launch your instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3orpbzq2r_26k1qDH99fUw.png" /></figure><h3>Step 3: Connect to Your EC2 Instance</h3><p>Once your instance is running, connect via SSH:</p><pre>ssh -i /path/to/key.pem ubuntu@your-ec2-public-ip</pre><h3>Step 4: Install and Configure OpenVPN</h3><p>Now for the exciting part — setting up your VPN server:</p><pre># Update system packages<br>sudo apt update<br>sudo apt upgrade -y<br><br># Download OpenVPN installer script<br>wget https://git.io/vpn -O openvpn-install.sh<br><br># Make it executable<br>chmod +x openvpn-install.sh<br><br># Run the installer<br>sudo ./openvpn-install.sh</pre><p>Follow the prompts to create your VPN profile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knH7R9tQK1_-btfTLPZGfQ.png" /></figure><p>The installer will generate a client configuration file (*.ovpn) that contains everything needed to connect to your VPN.</p><h3>Step 5: Download the Configuration File</h3><p>Transfer the .ovpn file to your local machine using SCP:</p><pre>scp -i &lt;path-of-pemfile&gt; ubuntu@&lt;public-ip-address&gt;:/home/ubuntu/&lt;.ovpnfilename&gt; &lt;path-where you want to download in local&gt;</pre><p>The configuration file will download to your specified location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4uyXeZ1raQB6svYrV9ZVaA.png" /></figure><h3>Step 6: Connect Using OpenVPN Client</h3><ol><li>Download and install the <a href="https://openvpn.net/community-downloads/">OpenVPN client</a> for your operating system</li><li>Open the OpenVPN client</li><li>Import your .ovpn configuration file</li></ol><h3>Step 7: Verify Your Connection</h3><p>Once connected, your OpenVPN client will display connection details:</p><p>You’ll also notice a VPN icon in your system tray, indicating an active secure connection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*PK1T5aAeipC7f-cq-8A4Hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*9864MVoTRU0T6wFR1TyRPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*aE8CSgKLhtT-9B4iM4gXHA.png" /></figure><h3>Testing Your Connection</h3><p>With the VPN active, you can now:</p><ul><li>Connect to private EC2 instances using their private IP addresses</li><li>Access internal AWS services securely</li><li>Browse the internet through your EC2 instance’s IP (useful for testing geolocation-restricted services)</li></ul><p>Try pinging a private instance to confirm connectivity:</p><pre>ping 10.0.0.123</pre><h3>Security Best Practices</h3><p>To further enhance your VPN setup:</p><ul><li><strong>Implement MFA</strong>: Consider adding multi-factor authentication</li><li><strong>Rotate certificates</strong>: Generate new client certificates periodically</li><li><strong>Audit access logs</strong>: Monitor who connects and when</li><li><strong>Firewall rules</strong>: Restrict access to only necessary IP ranges on your VPN server</li></ul><h3>Conclusion</h3><p>By implementing OpenVPN on an EC2 instance, you’ve created a secure gateway to your AWS infrastructure. This approach significantly enhances your security posture by ensuring all traffic to private instances is encrypted and authenticated.</p><p>The beauty of this solution is its simplicity and cost-effectiveness — with minimal setup time, you’ve eliminated multiple attack vectors while maintaining convenient remote access to your cloud resources.</p><p>What other cloud security measures have you implemented? Share your experiences in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e79dc304b67f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Static Website Deployment with AWS EC2, GitHub, and AWS CodePipeline]]></title>
            <link>https://jeshikphuyal.medium.com/automating-static-website-deployment-with-aws-ec2-github-and-aws-codepipeline-99847a1cc216?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/99847a1cc216</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws-codepipeline]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 10:17:36 GMT</pubDate>
            <atom:updated>2025-04-30T09:02:38.869Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Deploying and maintaining a static website manually can be time-consuming. By leveraging AWS services such as EC2, GitHub, and CodePipeline, you can automate the deployment process, ensuring that any code changes in your GitHub repository are automatically reflected in your hosted website.</p><p>In this guide, we will set up a fully automated pipeline using AWS Management Console.</p><h3>Prerequisites</h3><ul><li>An AWS account</li><li>A GitHub account with a repository containing a static website</li><li>Basic knowledge of AWS services and Git</li></ul><h4>EC2 Instance Role</h4><p>Go to iam role &gt; create a new role</p><ul><li><strong>Name</strong>: EC2-CodeDeploy-SSM-Role</li><li><strong>Attached Policies</strong>:</li><li>AmazonSSMManagedInstanceCore</li><li>AWSCodeDeployRole</li><li>AmazonS3ReadOnlyAccess</li></ul><h3>Step 1: Launch an EC2 Instance</h3><ol><li><strong>Log in to the AWS Management Console</strong>.</li><li>Navigate to <strong>EC2</strong> from the AWS dashboard.</li><li>Configure the following settings:</li></ol><ul><li><strong>Name</strong>: StaticWebsiteInstance</li><li><strong>Amazon Machine Image (AMI)</strong>: Choose Amazon Linux 2.</li><li><strong>Instance Type</strong>: t2.micro (Free Tier eligible)</li><li><strong>Key Pair</strong>: Create or select an existing key pair for SSH access.</li><li><strong>Network settings</strong>:</li><li>Ensure <strong>Auto-assign public IP</strong> is enabled.</li><li>Create a new security group allowing <strong>HTTP (port 80)</strong> and <strong>SSH (port 22)</strong> access.</li></ul><p>4. Click <strong>Launch Instance</strong>.</p><p>5. Once the instance is running, copy its <strong>Public IPv4 address</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j3FJfkszsTLC5Alv2UOpyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__7h8I6h9gL7zQGgR5N2QA.png" /></figure><p>Once the EC2 is launched, attach the above created roles.</p><h3>Step 2: Install Web Server and AWS CodeDeploy Agent</h3><ol><li>Connect to your EC2 instance using SSH:</li></ol><pre>ssh -i your-key.pem ec2-user@your-ec2-public-ip</pre><p>2. Update the package manager:</p><pre>sudo yum update -y</pre><p>3. Install and start Apache:</p><pre>sudo yum install -y httpd<br>sudo systemctl start httpd<br>sudo systemctl enable httpd</pre><p>4. Install AWS CodeDeploy Agent:</p><pre>sudo yum install -y ruby<br>cd /home/ec2-user<br>wget https://aws-codedeploy-us-east-1.s3.amazonaws.com/latest/install<br>chmod +x install<br>sudo ./install auto<br>sudo systemctl start codedeploy-agent<br>sudo systemctl enable codedeploy-agent</pre><h3>Step 3: Set Up a GitHub Repository</h3><ol><li>Go to <a href="https://github.com/">GitHub</a> and create a new repository.</li><li>Clone the repository to your local machine:</li></ol><pre>git clone https://github.com/your-username/your-repo.git cd your-repo</pre><p>3. Add static website files (index.html, style.css, etc.).</p><p>4. Create an appspec.yml file with the following content:</p><pre>version: 0.0<br>os: linux<br>files:<br>  - source: /<br>    destination: /var/www/html<br>hooks:<br>  AfterInstall:<br>    - location: scripts/postScript.sh<br>      timeout: 300<br>      runas: root</pre><p>5. Create a scripts/postScript.sh file:</p><pre>#!/bin/bash<br>echo &quot;=== STARTING POST-DEPLOY SCRIPT ===&quot;<br>echo &quot;Current directory: $(pwd)&quot;<br>echo &quot;Contents of /var/www/html/scripts/:&quot;<br>ls -la /var/www/html/script/<br><br># Restart Apache<br>sudo systemctl restart httpd<br>echo &quot;Apache status: $(systemctl status httpd)&quot;<br>echo &quot;=== SCRIPT COMPLETED ===&quot;</pre><p>7. Commit and push the changes:</p><pre>git add .<br>git commit -m &quot;Initial commit&quot;<br>git push origin main</pre><h3>Step 5: Set Up AWS CodePipeline</h3><ol><li>Navigate to <strong>AWS CodePipeline</strong>.</li><li>Click <strong>Create Pipeline</strong>.</li><li>Configure the pipeline:</li></ol><ul><li><strong>Pipeline name</strong>: StaticWebsitePipeline</li><li><strong>Service role</strong>: Create a new role or use an existing one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ovn6PlC337B__y-sQm_Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQcO6iiycfsaFsdCEPb9eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9O9AIGhoWgKvnurT7kMcw.png" /></figure><p><strong>4. Source Stage</strong>:</p><ul><li>Select <strong>GitHub</strong>.</li><li>Connect to your GitHub repository and choose the Repository and branch name.</li></ul><p><strong>5. Build Stage</strong> (Optional):</p><ul><li>Skip this step since we are deploying static files.</li></ul><p><strong>6. Deploy Stage</strong>:</p><ul><li>Select <strong>AWS CodeDeploy</strong>.</li><li>Choose Amazon EC2</li><li>Instance Type: EC2</li><li>Key: Name</li><li>Value: Your ec2 instance name.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnXtSQ44HzYxcmyhSBoIgw.png" /></figure><p>Target directory: destination value of appsec.yml<br>PostScript: path of your postScript.sh (e.g., script/postScript.sh)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qe7L23J1gqZYmTFjg2JDjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBZK_vMLhcphMYyCSne_9g.png" /></figure><p>Click <strong>Create Pipeline.</strong></p><h4>CodePipeline Service Role</h4><p>Now, Go to iam role &gt; search for Auto-generated pipeline role (eg.,AWSCodePipelineServiceRole-...)</p><ul><li><strong>Attached Policies</strong>:</li><li>AWSCodePipelineFullAccess</li><li>AmazonEC2FullAccess</li><li>AWSCodeDeployFullAccess</li><li>AmazonSSMFullAccess</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hlf78JYQbtFrU_e8H88Q1Q.png" /></figure><h3>Step 6: Test the Pipeline</h3><ol><li>Modify index.html in your local repository.</li><li>Commit and push changes:</li></ol><pre>git add .<br>git commit -m &quot;Updated index.html&quot;<br>git push origin main</pre><ol><li>Go to <strong>AWS CodePipeline</strong> → Monitor the pipeline execution.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1Je-JGOZ6Nlsx_9MRt-0g.png" /></figure><ol><li>Once deployment completes, visit http://your-ec2-public-ip to see the changes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voIbPEHkLP4s-iKIUoMlTg.png" /></figure><h3>Conclusion</h3><p>Congratulations! 🎉 You have successfully automated the deployment of your static website using AWS EC2, GitHub, and CodePipeline. Now, any changes you push to GitHub will automatically update your hosted website.</p><p>Need help or improvements? Drop a comment! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99847a1cc216" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Word Count Processing with S3, Lambda, and EC2]]></title>
            <link>https://jeshikphuyal.medium.com/automating-word-count-processing-with-s3-lambda-and-ec2-d65fa50f4341?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/d65fa50f4341</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[lambda-function]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 08:11:52 GMT</pubDate>
            <atom:updated>2025-03-24T08:56:39.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mT9evz7Y0p7U5_LXz6Zfpw.png" /></figure><p>This guide will help you set up an automated system where an <strong>EC2 instance</strong> is triggered by an <strong>S3 file upload</strong>, processes the text file to count words, and stores the result back in <strong>S3</strong>. After processing, the EC2 instance will shut down automatically.</p><h3>AWS Services Used:</h3><ul><li><strong>S3</strong> → Stores the input text file and saves the processed output.</li><li><strong>Lambda</strong> → Detects new uploads and triggers the EC2 instance.</li><li><strong>EC2</strong> → Performs the word count processing.</li><li><strong>IAM</strong> → Grants required permissions to services.</li><li><strong>CloudWatch</strong> → Monitors logs.</li></ul><h3>Step 1: Create S3 Buckets</h3><p>We need two S3 buckets:</p><ul><li><strong>Input Bucket</strong> → Stores uploaded text files for processing. (e.g., wordcount-input-bucket-demo)</li><li><strong>Output Bucket</strong> → Stores the word count results. (e.g., wordcount-output-bucket-demo)</li></ul><h3>Create Buckets</h3><ol><li>Go to the <strong>AWS S3 Console</strong>.</li><li>Click <strong>Create bucket</strong>.</li><li>Enter the <strong>Bucket name</strong> (e.g., wordcount-input-bucket-demo).</li><li>Choose a <strong>Region</strong>.</li><li>Keep settings as default and click <strong>Create bucket</strong>.</li><li>Repeat the steps to create the <strong>output bucket</strong> (e.g., wordcount-output-bucket-demo).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VG5DsJKrFMbhxS97G0mhBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5CN_Q9T3oEAqLBz5vS7XA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYulIACS0dCrZZTl5sr61Q.png" /></figure><h3>Step 2: Launch an EC2 Instance</h3><ol><li>Create an EC2 Instance</li><li>Go to <strong>AWS EC2 Console</strong> → Click <strong>Launch instance</strong>.</li><li>Give name: (e.g., Word-count-demo)</li><li>Choose <strong>Amazon Linux 2 AMI</strong>.</li><li>Select instance type <strong>t2.micro (Free Tier Eligible).</strong></li><li>Select Key pair name.</li><li><strong>Security Group:</strong> Allow <strong>SSH</strong> access for setup.</li><li>In <strong>Advanced details &gt; IAM Role</strong>, create and attach a role with <strong>S3 full access</strong> and <strong>EC2 Full access permissions</strong>.</li><li>Add a <strong>User Data Script</strong> to install required packages:</li></ol><pre>#!/bin/bash<br>yum update -y<br>yum install -y aws-cli</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oaVL1zLYpAqJHA4oyYuNPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GG1FcCs1V7iRlFF0o3q4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQ7nl9TXKcAQDZKfFuZcYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ITazV4AQKKvsp2Xqz--4w.png" /></figure><p>Now,<strong> Launch instance </strong>&amp; <strong>Copy the Instance ID</strong> (you’ll need this in Step 3).</p><h3>Step 3: Create an AWS Lambda Function</h3><p>We’ll create a Lambda function that will <strong>start the EC2 instance</strong> when a new file is uploaded to S3.</p><h3>1. Create Lambda Function</h3><ol><li>Go to <strong>AWS Lambda Console</strong>.</li><li>Click <strong>Create function</strong> → Select <strong>Author from scratch</strong>.</li><li>Enter a <strong>Function name</strong>: TriggerEC2OnS3Upload.</li><li>Select <strong>Runtime</strong>: Python 3.13.</li><li>Under <strong>Permissions</strong>, create and attach an <strong>IAM Role</strong> with <strong>EC2 Full access permissions</strong>.</li><li>Click <strong>Create function</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDpAjvf3SxkAhkguM01BUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b08xDVC0fdAocs_hnwWR_w.png" /></figure><h3>2. Add Python Code</h3><ol><li>In the <strong>Function code</strong> section, replace the default code with:</li></ol><pre>import json<br>import boto3<br><br>ec2 = boto3.client(&#39;ec2&#39;)<br><br>def lambda_handler(event, context):<br>    instance_id = &#39;i-xxxxxxxxxxxxxxx&#39;  # Replace with your EC2 instance ID<br>    <br>    # Start the EC2 instance<br>    ec2.start_instances(InstanceIds=[instance_id])<br>    print(f&quot;EC2 instance {instance_id} started.&quot;)<br>    <br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(&#39;EC2 instance started successfully!&#39;)<br>    }</pre><ol><li>Replace <strong>i-xxxxxxxxxxxxxxx</strong> with your <strong>actual EC2 instance ID</strong>.</li><li>Click <strong>Deploy</strong>.</li></ol><h3>Step 4: Configure S3 Event Notification for Lambda</h3><p>We need to <strong>trigger Lambda when a new file is uploaded</strong>.</p><ol><li>Go to the <strong>S3 Console</strong> → Open wordcount-input-bucket-demo.</li><li>Navigate to <strong>Properties</strong> → <strong>Event notifications</strong>.</li><li>Click <strong>Create event notification</strong>.</li><li>Name the event: S3TriggerLambda.</li><li>Under <strong>Event types</strong>, select <strong>PUT</strong> (for new file uploads).</li><li>Choose <strong>Destination</strong> → <strong>Lambda function</strong> → Select TriggerEC2OnS3Upload.</li><li>Click <strong>Save changes</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiM7Nh_8RMuAYaEcMrvteg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LDBWbxeRw-0d1f91P1IJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JYqjcspIZlwI--ka2DqhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tr-EjVFG3qvBJiU3gbDxQ.png" /></figure><p>Now, when a file is uploaded, <strong>Lambda will start the EC2 instance</strong>.</p><h3>Step 5: Configure Word Count Script on EC2</h3><p>Once the EC2 instance starts, it will:</p><ol><li>Fetch the latest file from the input S3 bucket.</li><li>Count the words.</li><li>Upload the result to the output S3 bucket.</li><li>Shut itself down.</li></ol><h3>1. Connect to EC2</h3><ol><li>Go to the <strong>AWS EC2 Console</strong>.</li><li>Copy the <strong>Public IP Address</strong> of your instance.</li><li>Open a terminal and connect via SSH:</li></ol><pre>ssh -i /path/to/your-key.pem ec2-user@your-ec2-public-ip</pre><h3>2. Create the Processing Script</h3><ol><li>Create a new script:</li></ol><pre>nano word_count.sh</pre><p>2. Paste the following script:</p><pre>#!/bin/bash<br>BUCKET_NAME=&#39;wordcount-input-bucket-demo&#39;<br>OUTPUT_BUCKET=&#39;wordcount-output-bucket-demo&#39;<br><br># Fetch the latest file from S3<br>LATEST_FILE=$(aws s3 ls s3://$BUCKET_NAME/ | sort | tail -n 1 | awk &#39;{print $4}&#39;)<br>aws s3 cp s3://$BUCKET_NAME/$LATEST_FILE /tmp/$LATEST_FILE<br><br># Check if file exists<br>if [ ! -f /tmp/$LATEST_FILE ]; then<br>    echo &quot;File not found!&quot; &gt; /tmp/error.txt<br>    aws s3 cp /tmp/error.txt s3://$OUTPUT_BUCKET/error.txt<br>    exit 1<br>fi<br><br>WORD_COUNT=$(wc -w &lt; /tmp/$LATEST_FILE)<br>echo &quot;Word count calculated: $WORD_COUNT&quot; &gt;&gt; /tmp/debug.log<br><br># Save results<br>RESULT_FILE=&quot;wordcount_$(date +%Y%m%d%H%M%S).txt&quot;<br>echo &quot;Word count: $WORD_COUNT&quot; &gt; /tmp/$RESULT_FILE<br>aws s3 cp /tmp/$RESULT_FILE s3://$OUTPUT_BUCKET/$RESULT_FILE<br><br></pre><p><strong>Note:</strong> Change Bucket name and Output bucket name with your respective buckets.</p><p>Save the file (<strong>CTRL+X → Y → Enter</strong>).</p><p>Make it executable:</p><pre>chmod +x word_count.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYyGB1_tCPByLarEGocUyg.png" /></figure><h3>Step 6: Testing the Setup</h3><ol><li><strong>Upload a text file</strong> (e.g., sample.txt) to wordcount-input-bucket-demo.</li><li><strong>Check if the EC2 instance starts</strong>.</li><li><strong>Verify the output in S3</strong>:</li></ol><ul><li>The processed file should be in wordcount-output-bucket-demo.</li><li>Example file: wordcount_20250321.txt.</li></ul><pre>./word_count.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OpYuiA5vH3AIpYlddPAcg.png" /></figure><p>Click on <strong>Open </strong>button on the top right corner</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbh2TsIFbOoI20w5dLkPZQ.png" /></figure><p>Here, Total Word Count is calculated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTdrvaHqDgakJA5rFm6VdA.png" /></figure><h3>Conclusion</h3><p>You’ve now successfully set up an automated word-counting system using <strong>S3, Lambda, and EC2</strong>. 🚀</p><ul><li><strong>S3 stores input/output files</strong>.</li><li><strong>Lambda triggers EC2 on new uploads</strong>.</li><li><strong>EC2 processes the text file, counts words, and uploads results</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d65fa50f4341" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Image Compression on AWS Using EC2, S3, and Lambda]]></title>
            <link>https://jeshikphuyal.medium.com/automating-image-compression-on-aws-using-ec2-s3-and-lambda-48ef5d483e6e?source=rss-560fae6ec207------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ef5d483e6e</guid>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[image-compression]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Jeshik Phuyal]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 09:46:21 GMT</pubDate>
            <atom:updated>2025-03-22T10:01:56.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n06Ka4DgQogmMgrV9oKfgQ.png" /></figure><h3>Introduction</h3><p>In this project, we will automate the process of compressing images uploaded to an S3 bucket using an EC2 instance. The workflow is as follows:</p><ol><li>A new image is uploaded to an <strong>S3 bucket</strong>.</li><li>An <strong>AWS Lambda function</strong> triggers an <strong>EC2 instance</strong>.</li><li>The <strong>EC2 instance</strong> fetches the image, compresses it, and uploads the compressed image back to <strong>S3</strong>.</li></ol><p>All configurations will be done using the <strong>AWS Console</strong> without any manual instance start-up.</p><h3>Step 1: Launch an EC2 Instance with S3 Read/Write Permissions</h3><ol><li>Navigate to <strong>AWS Console</strong> → <strong>EC2 Dashboard</strong> → Click <strong>Launch Instance</strong>.</li><li>Provide a <strong>Name</strong> (e.g., ImageCompressorInstance).</li><li>Select <strong>Amazon Linux 2023</strong> as the AMI.</li><li>Choose an <strong>Instance Type</strong> (t2.micro for free tier).</li><li>Configure <strong>Key Pair</strong> (to SSH into the instance).</li><li>Under <strong>IAM Role</strong>, click <strong>Create new IAM Role</strong>:</li></ol><ul><li>Select <strong>AWS Service</strong> → <strong>EC2</strong>.</li><li>Attach the <strong>AmazonS3FullAccess</strong> policy.</li><li>Name it EC2S3AccessRole and attach it to the instance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLjahUUwbiGquaFhSJ7Png.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dhtbzqZF81coFc9Wef-JA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_RrVNizxXktilw6WZ30kA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmstg9RrNVOAltCzMb09Zg.png" /></figure><p>Click <strong>Launch Instance</strong>.</p><p>Here our instance is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-29CE-0bN51kxSrV6KRCQ.png" /></figure><h3>Step 2: Create an S3 Bucket</h3><ol><li>Open <strong>S3 Dashboard</strong> → Click <strong>Create Bucket</strong>.</li><li>Enter a <strong>Bucket Name</strong> (e.g., my-image-processing-bucket-demo).</li><li>Choose a <strong>Region</strong> (same as EC2 instance).</li><li>Uncheck Block all public access.</li><li>Click <strong>Create Bucket</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23X4KEoT4auFoO2rnMKOXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lXymet2fuhFF4De73d4iQ.png" /></figure><h3>Upload an Image to S3</h3><ol><li>Open the <strong>S3 bucket</strong>.</li><li>Click <strong>Upload</strong> → Select an image file.</li><li>Click <strong>Upload</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4W-iESNv-MTp8ZDdNxqpNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tA1yoEMJyV2wTKLqR2pq7Q.png" /></figure><h3>Create IAM Role for Lambda</h3><ol><li>Go to <strong>IAM</strong> → <strong>Roles</strong>.</li><li>Find the role assigned to your Lambda function.</li><li>Attach the following policies:</li></ol><ul><li><strong>AmazonEC2FullAccess</strong> (to start EC2 instance).</li><li><strong>AmazonS3FullAccess</strong> (to read/write S3).</li></ul><p>4. Give role name (e.g., my-lambda-policies).</p><p>5. Click <strong>Create</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xeQpUGXD6SGhrSxm-AhDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3R1K5Ludco4Dtt0myEsCQ.png" /></figure><h3>Step 3: Create an AWS Lambda Function to Trigger EC2</h3><ol><li>Navigate to <strong>AWS Lambda</strong> → Click <strong>Create function</strong>.</li><li>Select <strong>Author from scratch</strong>.</li><li>Enter <strong>Function Name</strong> (TriggerEC2ForCompression).</li><li>Choose <strong>Runtime</strong>: Python 3.9.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJebXMt4gyoVQOfMixZsWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SaRc4BFoIrb6Aw6CHWyYLg.png" /></figure><p>Click <strong>Create function</strong>.</p><h3>Modify Lambda Code</h3><ol><li>Replace your-region and your-instance-id with your EC2 instance&#39;s region and ID.</li><li>Click <strong>Deploy</strong>.</li></ol><p>Replace the default code with:</p><pre>import boto3<br><br>def lambda_handler(event, context):<br>    ec2 = boto3.client(&#39;ec2&#39;, region_name=&#39;Your Region&#39;)<br>    instance_id = &#39;Your EC2 instance ID&#39;  # Replace with your EC2 instance ID<br>    <br>    # Start the EC2 instance<br>    ec2.start_instances(InstanceIds=[instance_id])<br>    <br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: &#39;EC2 instance started successfully&#39;<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOMrf1rHWVIoDRzRkvHkiw.png" /></figure><h3>Step 4: Set Up an S3 Event Trigger for Lambda</h3><ol><li>Open <strong>S3</strong> → Click <strong>my-image-processing-bucket-demo</strong>.</li><li>Go to <strong>Properties</strong> → Scroll to <strong>Event notifications</strong>.</li><li>Click <strong>Create Event Notification</strong>:</li></ol><ul><li>Name: TriggerLambdaOnUpload</li><li>Event Type: <strong>PUT (Object Created)</strong></li><li>Destination: <strong>Lambda Function</strong></li><li>Select TriggerEC2ForCompression.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kol2NvkAbRI74rYQS5HRMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KhP0rZcNeFDkapNuMv1dA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rMg5oIihyIhAIjBDKDvSBQ.png" /></figure><p>4. Click <strong>Save changes.</strong></p><h3>Step 5: Install Image Compression Script on EC2</h3><ol><li>SSH into the EC2 instance:</li></ol><pre>chmod 400 &quot;your-key.pem&quot;</pre><pre>ssh -i &quot;your-key.pem&quot; ec2-user@your-ec2-public-ip</pre><p>2. Install dependencies:</p><pre>sudo yum update -y<br>sudo dnf install -y python3.9 python3-pip<br>pip3 install pillow boto3<br>python3 --version</pre><p>3. Create a script to compress the image:</p><pre>nano compress_image.py</pre><p>4. Add the following code:</p><p>Replace SOURCE_BUCKET and DESTINATION_BUCKET with your own bucket.</p><p><strong>Note:</strong> Change<strong> image_key = ‘your image path/key’</strong> from the below code manually.</p><p>Click your <strong>bucket &gt; your uploaded image &gt; image key.</strong></p><pre>import boto3<br>from PIL import Image<br>import io<br><br># AWS credentials and resources<br>s3 = boto3.client(&#39;s3&#39;)<br><br># Source and destination bucket details<br>SOURCE_BUCKET = &#39;bucketname&#39;   # Replace with your own bucket<br>DESTINATION_BUCKET = &#39;bucketname&#39;. # Destination Bucket can be existing Bucket,Replace with your own bucket<br><br>def compress_image(key):<br>    # Download the image from S3<br>    response = s3.get_object(Bucket=SOURCE_BUCKET, Key=key)<br>    image_data = response[&#39;Body&#39;].read()<br><br>    # Compress the image<br>    image = Image.open(io.BytesIO(image_data))<br>    compressed_image = io.BytesIO()<br>    image.save(compressed_image, format=&#39;PNG&#39;, quality=30)  # Adjust quality as needed<br><br>    # Upload compressed image back to S3<br>    s3.put_object(Bucket=DESTINATION_BUCKET, Key=f&#39;compressed/{key}&#39;, Body=compressed_image.getvalue())<br><br>    print(f&quot;Image &#39;{key}&#39; compressed and uploaded successfully.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    # Manually specify the image key (adjust this if needed)<br>    image_key = &#39;your image path/key&#39;  # Example path<br>    compress_image(image_key)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCLg2MNtk74xrXrya0TfVg.png" /></figure><p><strong>Note:</strong> Check format in the above code and change according to your file format. Here, we are using PNG format.</p><p>Save the file (CTRL+X, Y, Enter).</p><h3>Step 6: Run Script</h3><pre>chmod +x compress_image.py</pre><pre>ls  # To check ur existing image in bucket</pre><pre>python3 compress_image.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXWfI3zlrkq1bfBVLJSpQQ.png" /></figure><h3>Step 7: Test the Workflow</h3><ol><li>Upload an image to <strong>S3</strong>.</li><li>The <strong>S3 event trigger</strong> calls <strong>Lambda</strong>.</li><li><strong>Lambda</strong> starts the <strong>EC2 instance</strong>.</li><li>The <strong>EC2 instance</strong> compresses the image and uploads it back to S3.</li><li>Check S3 for compressed image.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hzx2L_7T7DvqOOGciNbUYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSnzh_y4i4i6pI0kVwXgRA.png" /></figure><h3>Conclusion</h3><p>You have successfully automated image compression using AWS services: ✅ <strong>EC2</strong> for processing<br> ✅ <strong>S3</strong> for storage<br> ✅ <strong>Lambda</strong> for event-driven execution</p><p>This setup ensures efficient image compression without manual intervention. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ef5d483e6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>