<?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 Nirmal Bastakoti on Medium]]></title>
        <description><![CDATA[Stories by Nirmal Bastakoti on Medium]]></description>
        <link>https://medium.com/@nnirmalb10?source=rss-2d57fd58e69a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r_Kgxk2c0PzYpnywooES8A.jpeg</url>
            <title>Stories by Nirmal Bastakoti on Medium</title>
            <link>https://medium.com/@nnirmalb10?source=rss-2d57fd58e69a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:24:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nnirmalb10/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[Scalable SAST Automation Using AWS Serverless Services: AWS Lambda, API Gateway, and CodePipeline]]></title>
            <link>https://medium.com/@nnirmalb10/scalable-sast-automation-using-aws-serverless-services-aws-lambda-api-gateway-and-codepipeline-60b0ecbe433c?source=rss-2d57fd58e69a------2</link>
            <guid isPermaLink="false">https://medium.com/p/60b0ecbe433c</guid>
            <dc:creator><![CDATA[Nirmal Bastakoti]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 14:45:01 GMT</pubDate>
            <atom:updated>2026-04-28T09:32:30.973Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is meant to serve as a guide on how the Universal SAST Pipeline was created, which is a SAST pipeline where multiple repos are mapped to a single pipeline.</p><p>Changes made within multiple repos trigger the same CodePipeline. This reduces operational overhead greatly, as the same pipeline can be used to facilitate SAST operations for multiple repositories.</p><p>A brief architecture diagram of how this workflow was created is given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lmOKwSjdBpRze3L_.png" /></figure><p>As shown in the diagram above, the Bitbucket repositories have been connected to an AWS API gateway via webhooks, such that whenever a change is pushed to the repository, it invokes an AWS lambda function, which in turn triggers a workload within AWS CodePipeline.</p><p>Additionally, the AWS CodePipeline is fed two variables, “Repository name” and “Commit ID” by the lambda function. This is used by the AWS CodePipeline to clone the repositories and then perform SAST analysis of the respective repositories.</p><p><strong>Note: </strong>This differs from the traditional method of adding multiple source connections to the IPCodePipeline source stage, as in the traditional method, if a change is made to one repo then AWS CodePipeline is triggered for all associated repositories.</p><h3>Setup overview</h3><h3>Step 1: Created a repository within Bitbucket with a sample Buildspec.yml</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*Q3tERQDJEsZBsbeR4awEpw.png" /></figure><h3>Step 2: Created a pipeline within AWS CodePipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2YI6v46KyJDjZu5jh3Apw.png" /></figure><p>The source was linked to the Bitbucket repo we created in Step 1.</p><h3>Step 3: Define the following pipeline variables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Plj6V6TxPmpPugKR.png" /></figure><h3>Step 4: Within the repositories to be scanned, define two webhooks, one for PushRepo and one for Pull Requests.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqBFXjmoFZsmdxPe8E_x7Q.png" /></figure><p>The webhooks point to a lambda function via an API gateway.</p><h3>Step 5: Define a lambda function to extract the repository name, Branch name, commit ID, and PullRequest ID</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*15D4LW6KisGkNEXz.png" /></figure><p>Then the lambda function starts a code pipeline, passing those variables to CodePipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*UojT0JLqAodzp91Z.png" /></figure><h3>Step 6: Within the Build stage, reference the environment variables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nx_bbVYw5BAuC0bj_ZBJCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vCT2tsV_1q1q8nVN.png" /></figure><h3>Step 7: Defined the buildspec to echo the retrieved variables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P9PllYKOhQO1bGE-.png" /></figure><h3>Step 8: Defined the sonar-buildspec.yml for the SAST stage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OuI-YrzTLH9QXYB3.png" /></figure><p>It uses the variables received from the lambda function to scan the project.</p><p><strong>Note: A Sonar-project.properties file must exist within the Specific repo that is to be scanned. The Sonar.project-key variable is defined within this file.</strong> <strong>An example of a sonar-project.properties file:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*GBMbk_W3affhqoPo.png" /></figure><h3>Execution Overview:</h3><p>In this section, I will make a small change to the SAST-ONE repo and show the workflow it triggers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g6_RSwWNVaNMBLMP.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*bpeiCcjMY-xQ-Xyi5myRlw.png" /></figure><h3>Step 1: Source</h3><p>It triggers the source stage where it loads the sonar-buildspec.yml, which we defined in our original repo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJQr5_6HXW1QOkI2GOP9RA.png" /></figure><h3>Step 2: The SAST analysis is performed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*oSkza9GE_qHSFKmq.png" /></figure><p>CodeBuild will successfully scan the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbeyhodtWR-LqBjQPOTN0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*pby-AECrkTnlf4J_0-husA.png" /></figure><p>And the result will be visible in the SonarQube Dashboard</p><p>The pipeline will then conclude execution successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NcyKBRInZkZWBh7H.png" /></figure><p>That concludes this guide on how to setup and use the Universal SAST Pipeline with AWS Serverless services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60b0ecbe433c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Managing Dev and Prod Environments in Serverless APIs]]></title>
            <link>https://medium.com/@nnirmalb10/best-practices-for-managing-dev-and-prod-environments-in-serverless-apis-057ec6fd061f?source=rss-2d57fd58e69a------2</link>
            <guid isPermaLink="false">https://medium.com/p/057ec6fd061f</guid>
            <dc:creator><![CDATA[Nirmal Bastakoti]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 16:43:05 GMT</pubDate>
            <atom:updated>2026-04-29T11:29:59.365Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog demonstrates how to design, build, and deploy a fully serverless REST API using Amazon API Gateway and AWS Lambda. From mock integrations to production-ready backend implementations, it covers essential concepts like mapping templates, versioning, aliases, and environment-based deployments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1xxTSE4zPgumkUoO1nZOQ.png" /></figure><p><strong>Steps</strong></p><p>1. In the AWS Management Console search bar, enter <strong>API Gateway</strong>, and click the <strong>API Gateway</strong> result under Services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GW5Q9fEdbCZh5P08.png" /></figure><p>2. Click <strong>Create an API</strong>, then click Build in the <strong>REST API</strong> card:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gwen16nsnjJhPbEo.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R7MxmVK8d8QLKdtj.png" /></figure><p>3. In the Create new API form, select <strong>New API</strong> and enter the following values:</p><p><strong><em>API name:</em></strong><em> NirAPI</em></p><p><strong><em>Description:</em></strong><em> Implementation API</em></p><p><strong><em>Endpoint Type:</em></strong><em> Regional</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sl4Q_QTiOvw5VrO3.png" /></figure><p>4. Click <strong>Create API.</strong></p><p>The API is now created and you can define a model for it.</p><p>5. Click API &gt; NirAPI &gt; Models in the left navigation panel and click <strong>Create model</strong> to define a new API Gateway model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*QAE5eyW7Pi7GfCB9.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2kT0rx7mnoVaSbEz.png" /></figure><p>6. In the New Model form, enter the following values and then click <strong>Create</strong>:</p><p><strong><em>Model name:</em></strong><em> Item</em></p><p><strong><em>Content type:</em></strong><em> application/json</em></p><p><strong><em>Model schema:</em></strong></p><blockquote>{<br> “$schema”: “http://json-schema.org/draft-04/schema#&quot;,<br> “title”: “Item Schema”,<br> “type”: “object”,<br> “properties”: {<br> “ID”: { “type”: “number” },<br> “name”: { “type”: “string” },<br> “price”: { “type”: “number” }<br> }<br>}</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/0*3cZeUQOIIy-vKaRZ.png" /></figure><p>The new Item model is listed under Models in the left navigation panel.</p><p>7. Create another model for a list of items with the following values:</p><p><em>Model name: Items</em></p><p><strong><em>Content type:</em></strong><em> application/json</em></p><p><em>Model schema:</em></p><blockquote>{<br> “id”: “Items”,<br> “title”: “Items”,<br> “type”: “array”,<br> “items”: {“$ref”: “https://apigateway.amazonaws.com/restapis/YOUR_API_ID/models/Item&quot;}<br>}</blockquote><p><em>Note: You need to replace YOUR_API_ID in the items JSON entry above with your actual API ID. You can find your API ID in the breadcrumb trail of the API Gateway Console (Amazon API Gateway &gt; APIs &gt; NirAPI (*YOUR_API_ID*)):</em></p><p>You should now see both Item and Items beneath Models. You are now ready to create API resources and methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*lTdcDx_fBgb1Btyv.png" /></figure><p>8. Click on <strong>Resources</strong> in the left navigation pane, then <strong>Create Resource.</strong></p><p>Resources are the key abstraction for information in a RESTful API. You will create resources for lists of items and individual items.</p><p>9. In the New Child Resource form, enter the following values and then click <strong>Create Resource:</strong></p><p><strong><em>Proxy resource:</em></strong><em> unchecked</em></p><p><strong><em>Resource Path:</em></strong><em> /</em></p><p><strong><em>Resource Name:</em></strong><em> items</em></p><p><strong><em>Enable API Gateway CORS:</em></strong><em> unchecked</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1RaCj8f0za7qlnBJ.png" /></figure><p>The /items resource is now selected in the Resources panel. Notice there are no methods created yet. You will add a GET method to retrieve a list of items.</p><p>10. Click on <strong>Create Method</strong> and enter the following values and then click Create method:</p><p><strong><em>Method type: </em></strong><em>GET</em></p><p><strong><em>Integration type:</em></strong><em> Mock</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w8uQF2Gm1w3q2KME.png" /></figure><p>The mock integration allows you to define API resources and methods whenever you don’t have a real backend implementation yet. The advantage of this is that you can now use the <strong>Items</strong> model previously created to generate fake data. For example, this would allow you to provide a temporary API endpoint to your frontend/mobile developer, even before you have a real implementation.</p><p>11. Click on the <strong>Integration Response</strong> tab:</p><p>12. In the <strong>Default Response</strong> section, click Edit, then expand the Mapping templates section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5pXq3ebpSOkOsaV8.png" /></figure><p>13. Select Items from the Generate template drop-down:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GDY6jFSfI2cZOJ0x.png" /></figure><p>14. Overwrite the generated template with the following sample code to generate a list of 3 Item objects, with different IDs, prices and names:</p><blockquote>[<br>#foreach($ID in [1, 2, 3])<br> #set($price = $ID * 1.5)<br> #set($name = “foo” + $ID)<br> {<br> “ID” : $ID,<br> “name” : “$name”,<br> “price” : $price<br> }<br> #if($foreach.hasNext),#end<br>#end<br>]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EjVjs50tBjPh99ax.png" /></figure><p>15. Click <strong>Save</strong>.</p><p>You will be redirected to the Resources page.</p><p>16. From the Resources page, select the <strong>Test tab</strong>:</p><p>17. Click the <strong>Test</strong> button.</p><p>The response should resemble the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*WDU6O1boaTLuFG2O.png" /></figure><p>The method returns the template you defined. You will now define an API resource for individual items with the /items/{ID} path.</p><p>18. Scroll to the top of the Resources page and click Create resource.</p><p>19. In the Create Resource form, enter the following values and then click <strong>Create resource:</strong></p><p><strong>Proxy resource: </strong>unchecked</p><p><strong>Resource Path:</strong> /items/</p><p><strong>Resource Name:</strong> {ID}</p><p><strong>CORS (Cross Origin Resource Sharing): </strong>unchecked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7wLXaciimQo-GW82.png" /></figure><p>You only need to insert the {ID} part of the path since <strong>/items/</strong> is automatically added when creating a new resource with <strong>/items</strong> selected in the resource panel. This means the Item resource is a child of the Items resource. The {ID} path variable makes the path dynamic. This way, API Gateway will treat any value as a dynamic ID and pass it to the backend implementation, which will return the corresponding data.</p><p>20. Create a <strong>GET</strong> method with a <strong>Mock</strong> integration:</p><p>21. Click <strong>Integration Response </strong>and modify <strong>Mapping Templates</strong> of the 200 response status to the following:</p><p>This template extracts the dynamic ID parameter, casts it to an integer, and returns an Item object with fake generated data.</p><p><em>Note: Refer to steps 12–15 for modifying the Mapping templates.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zyr7VucmkFgIrIC-.png" /></figure><p>22. Test the new /items/{ID} resource as you’ve just created. This time, you need to enter a value under ID before clicking the Test button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*WLRDnR-lWWnHjwKP.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*3cCM5DdrR3EaJg1V.png" /></figure><p>If you leave the ID field blank, an “Internal Server Error” is returned. Any integer value should return a valid JSON response. You will replace the simple Mock implementation with a real implementation in the following Lab Steps. For now, you can proceed to deploy the API with the mock backends.</p><p><em>Note: Refer to steps 16 and 17 for testing the resource.</em></p><p>23. Click Deploy API from the top of the page and select *New Stage* from the Stage drop-down menu. Enter the following values and then click Deploy:</p><p><strong>Stage name: </strong>dev</p><p><strong>Deployment description: </strong>Only mock items list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I1reGgN5qB05sIfv.png" /></figure><p>The API is now deployed and ready to serve requests at the /items and /items/{ID} endpoints in the dev stage/environment.</p><p>24. Repeat the Deploy API action from the Resources panel action again, this time creating the prod (production) stage.</p><p><strong>Summary:</strong><br>Creating a model</p><p>Creating API resources</p><p>Creating API resource methods using a mock backend integration</p><p>Deploying the API to each stage</p><p><strong>Creating an AWS Lambda Function Backend:</strong></p><p>1. In the AWS Management Console search bar, enter <em>Lambda</em>, and click the <strong>Lambda</strong> result under <strong>Services</strong>:</p><p>2. Click <strong>Create function</strong>:</p><p>3. In the <strong>Author from scratch</strong> form, enter the following values:</p><ul><li><strong>Name</strong>: <em>ItemsFunction</em></li><li><strong>Runtime</strong>: Python 3.x (The latest version of Python 3)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*vD75oRJedC4oQO4R.png" /></figure><p>4. To assign an IAM role, expand <strong>Change default execution role</strong>, and select the following:</p><ul><li><strong>Execution role</strong>: Select <strong>Use an existing role</strong></li><li><strong>Existing role</strong>: Select <strong>lambda_basic_execution</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l2PXuHgQc_1NUGpj.png" /></figure><p>5. Scroll to the bottom and click <strong>Create function</strong>:</p><p>6. Scroll down to the <strong>Code source</strong> section and overwrite the contents of the <strong>lambda_function.py</strong> file with the following code:</p><blockquote># static list of items<br>items = [<br> {“ID”: 1, “name”: “Pen”, “price”: 2.5},<br> {“ID”: 2, “name”: “Pencil”, “price”: 1.5},<br> {“ID”: 3, “name”: “Highlighter”, “price”: 3.0},<br> {“ID”: 4, “name”: “Ruler”, “price”: 5.0},<br>]<br>def lambda_handler(event, context):<br> print(“Event: %s” % event) # log event data<br> ID = event.get(“ID”) # extract ID<br> # list case<br> if not ID:<br> return items<br> # ID case<br> found = [item for item in items if item[“ID”] == ID]<br> if found:<br> return next(iter(found))<br> # nothing was found<br> raise Exception(“NotFoundError”)</blockquote><p>Your <strong>Code source</strong> section will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-bZoy00ivsU93AAi.png" /></figure><p>The function is very simple, without any specific dependency or infrastructure requirement.</p><p>The logic is straightforward:</p><ul><li>If no ID is given, return the whole list</li><li>If the ID exists, return the corresponding Item</li><li>Otherwise, raise an error</li></ul><p>The other AWS Lambda configuration fields can be left at their defaults.</p><p>7. To deploy your function, click <strong>Deploy</strong> at the bottom left of the code editor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*Qtpu_onZskgRG5-8.png" /></figure><p>You will see a notification that your function has been deployed:</p><p>You can now test the function.</p><p>8. Below <strong>Deploy</strong> button click <strong>Test</strong>:</p><p>In the pop-up, click <strong>Create new test event</strong>:</p><p>9. In the <strong>Create new test event</strong> form, enter the following values into the form:</p><ul><li><strong>Event name</strong>: <em>GetItems</em></li><li><strong>Event body</strong>: Replace the existing contents with the following JSON in the event editor text-area:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qNMAd4x0aCqwKPhK.png" /></figure><p>The {} represents an empty object in JSON. Because no ID is specified, the test will confirm the code path for returning all the items.</p><p>10. Scroll to the bottom and click <strong>Save</strong>.</p><p>11. Click <strong>Test</strong> once more to run the <strong>GetItems</strong> test you just created:</p><p>Find and expand the <strong>OUTPUT</strong> tab. This tab contains the results of the test:</p><p>The result confirms that the list of all items is returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_fe6wUId-V6Y-JOK.png" /></figure><p>12. Repeat the test process to test two more code paths for the following cases:</p><ul><li>An object such as <em>{“ID”: 1}</em>, which will return only one item.</li><li>An object such as <em>{“ID”: 5}</em>, which will return an NotFoundError.</li></ul><p><em>Please note that in a real-world scenario you’d normally perform these operations on a database (DynamoDB, RDS, Firebase, etc.).</em></p><p><strong>Summary:</strong></p><p>You have created and tested the Lambda function that will serve as the backend for your API in API Gateway. Before you can use it, it is best to understand versioning so you can use different versions of the function in the dev and stage environments.</p><p><strong>Versioning and Aliasing the Lambda Function</strong></p><p>You will create different versions of the AWS Lambda function corresponding with the dev and prod stages you created in API Gateway.</p><p>Each Lambda function has a default $LATEST version, which is the one you can always work on and edit. Once your code is stable enough or whenever your code changes significantly, you can create a new <em>version</em>. A simple incremental number will be assigned to the new version and you will be able to use and test any version. As you can imagine, this is a useful mechanism to keep track of your functions history and eventually rollback to previous versions.</p><p>Using versions is helpful, but sometimes even that is not flexible enough. For example, you can only bind your API Gateway resources and methods to a specific version of your Lambda function: whenever you create a new Lambda Version, you’d need to update your API Gateway configuration as well. Fortunately, AWS provides the concept of <em>alias</em> to improve this situation.</p><p>An alias is a useful abstraction that allows you to refer to a function version without actually using a version number. For example, you may want to create a prod alias and connect it to your API Gateway production stage. You could do the same with a dev alias, bound to your development stage.</p><p>The best practice would be always referencing to aliases when configuring your API Gateway backend integrations. By default, API Gateway will point to the $LATEST version, but you can always configure it to use a specific version or alias.</p><p>The following are examples of how the version and alias mappings work:</p><p>You will now create a new version and two new aliases for the Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k41ozhPTwc2_P0e6.png" /></figure><p>A form will open allowing you to optionally specify a description of the new version.</p><p>2. To publish a new version, click <strong>Publish</strong>:</p><p><em>Please note that you cannot modify published versions. You can only work on the $LATEST version.</em></p><p>Next, you will create an alias for your AWS Lambda function.</p><p>3. At the top-right, click <strong>Actions</strong>, click the <strong>Create alias</strong> menu item, and enter the following form values:</p><ul><li><strong>Name</strong>: <em>dev</em></li><li><strong>Description</strong>: <em>Development alias</em></li><li><strong>Version</strong>: <strong>$LATEST</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HyCSddUD9S8epjdx.png" /></figure><p>You are creating an alias for the dev stage.</p><p>The dev stage will always work with the latest version of the function. By binding the dev alias to our $LATEST version, you will be able to quickly implement changes and test them without explicitly publishing new versions. Of course, you can always adapt this configuration to your own needs. You usually don’t want to be so aggressive in automatically releasing the latest function to production. You will alias prod to a specific version instead.</p><p>4. To save your alias and return to the function’s details page, click <strong>Save</strong>, and then at the top click <strong>ItemsFunction</strong>.</p><p>5. To create an alias for production, at the top click <strong>Actions</strong>, <strong>Create alias</strong> and enter the following form values:</p><ul><li><strong>Name</strong>: <em>prod</em></li><li><strong>Description</strong>: <em>Production alias</em></li><li><strong>Version</strong>: Select the number (not $LATEST)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RsQ9OKorAYfgsIQs.png" /></figure><p>Notice the <strong>Weighted alias</strong> option. Traffic to an AWS Lambda function can be split between multiple versions. This allows you to test a new version of a function on a subset of traffic before fully deploying it. Weighted aliases aren’t used in this lab.</p><p>6. To save your alias and return to the function’s details page, click <strong>Save</strong>, and then at the top click <strong>ItemsFunction</strong>.</p><p>7. To see the aliases you created, click the <strong>Aliases</strong> tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HLeNrpekMwK8NRkY.png" /></figure><p>You will see the <strong>dev</strong> and <strong>prod</strong> aliases listed.</p><p>You can also see the version you published by clicking on the <strong>Versions</strong> tab.</p><h3>Summary</h3><p>Now that the Lambda function is configured with versions and aliases, you can use it as an API Gateway backend. In the next step, you will properly configure API Gateway resources to use the Lambda function.</p><p><strong>Configuring the API Gateway Backend</strong></p><p>You will update the API Gateway Integration Request from Mock to AWS Lambda. You will map both API endpoints to the same Lambda function.</p><p>2. Click <strong>Integration request</strong> &gt; <strong>Edit</strong> and set the following values:</p><ul><li><strong><em>Integration type</em></strong><em>: </em><strong><em>Lambda Function</em></strong></li><li><strong><em>Use Lambda Proxy integration</em></strong><em>: unchecked</em></li><li><strong><em>Lambda Region</em></strong><em>: us-west-2</em></li><li><strong><em>Lambda Function</em></strong><em>: ItemsFunction</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ygq9JctG4cOnbjYN.png" /></figure><p>Remember, when you simply select the Lambda Function name, API Gateway will use its <em>$LATEST</em> version. Using $LATEST is generally not recommended since you always want to bind your API Resources to stable Lambda aliases (dev, stage, etc.). The next instruction shows how to map each API Gateway stage to the correct Lambda alias.</p><p>3. To use the dev alias, add <em>:dev</em> to the end of the <strong>Lambda Function</strong>. The complete value is <em>ItemsFunction:dev</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*XQBXlyHHTJ1M8IxN.png" /></figure><p>4. Click <strong>Save.</strong></p><p>5. To update the alias of the Lambda function, click <strong>Edit</strong> in the <strong>Integration request</strong> settings section, and change <strong>:dev</strong> to <strong>:prod</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*cC2JBP2gbX8OlQOV.png" /></figure><p>You are changing the value to give API Gateway permission to the prod alias as well as the dev alias.</p><p>6. Click <strong>Save</strong>.</p><p>You will now do similar actions for the /items/{ID} resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*VLrkn72-J87Cw3Aa.png" /></figure><ul><li><strong>Integration type</strong>: <strong>Lambda Function</strong></li><li><strong>Use Lambda Proxy integration</strong>: unchecked</li><li><strong>Lambda Region</strong>: us-west-2</li><li><strong>Lambda Function</strong>: <em>ItemsFunction:dev</em></li><li><strong>Request body passthrough</strong>: <strong>When there are no templates defined</strong></li></ul><p>This time you need to configure the <strong>Mapping Templates</strong> because the resource includes a dynamic {ID} variable. You will map the ID path parameter to a Lambda event parameter, via a custom mapping template.</p><p>9. Scroll down to <strong>Mapping templates</strong>.</p><p>10. Enter the following values:</p><ul><li><strong>Content type</strong>: <em>application/json</em></li><li><strong>Generate template</strong>: <strong>Items</strong></li><li><strong>Template body</strong>:</li></ul><blockquote>{<br> “ID”: $input.params(“ID”)<br>}</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5JRRVWHP0erMleJQ.png" /></figure><p>11. Click <strong>Save</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*txf83zvS4dkR_yaU.png" /></figure><p>13. Click <strong>Save</strong>.</p><p>At this point, all the API Gateway Resources can access both Lambda Aliases and we won’t need to manually grant any additional permission. You now need to redeploy the API into the prod stage.</p><p>14. Click <strong>Deploy API</strong> and select <strong>prod</strong> for <strong>Stage</strong> before clicking <strong>Deploy</strong>.</p><p>If everything went fine, the same endpoint will finally return real data from the Lambda function, instead of fake data.</p><p>In theory, you’d need to deploy the dev-configured Resources into the dev Stage and the prod-configured resources into the prod Stage. For now, you can just deploy the same configuration into both stages (dev and prod) since you will completely change the backend configuration in the next step, to make it more dynamic and flexible.</p><p>15. Go back to <strong>Resources</strong>, click <strong>Deploy API</strong> and select <strong>dev</strong> for <strong>Stage</strong> before clicking <strong>Deploy</strong>.</p><p>Always remember that you can test your API integration in the AWS Console before deploying it (return to <strong>Method Execution</strong> and click <strong>TEST</strong>). This way you will also be shown the corresponding API Gateway logs for debugging purposes.</p><p><strong>Summary:</strong></p><p>You have configured the API backend integration to use the Lambda function you created. You deployed the updated API to both the dev and prod stages.</p><p><strong>Following best practices for Versions, Aliases and Stages</strong></p><p>You have previously created the following resources:</p><ul><li><em>Lambda function (ItemsFunction)</em></li><li><em>Lambda Versions ($LATEST and 1)</em></li><li><em>Lambda Aliases (dev and prod)</em></li><li><em>API Gateway Stages (dev and prod)</em></li><li><em>API Gateway Resources (ItemsList and Item)</em></li></ul><p>Both the API endpoints are attached to the same Lambda function and they currently use its version 1. This configuration is not very robust and doesn’t allow you to update your Lambda function and see the updates in your dev environment.</p><p>The recommended best practice is connecting your API Gateway stages to the corresponding Lambda Alias, so that you can easily manage new functionalities, testing, bug fixing, rollbacks, etc. You can achieve this setup by creating a new <em>stage variable</em> and then use this variable as a Lambda alias in your API Gateway backend configuration. Stage Variables can be used to configure the request integration of your resources so that you don’t have to modify them every time you want to re-deploy your API.</p><p>1. In the <strong>dev Stage Editor</strong>, click on the <strong>Stage variables</strong> tab &gt; <strong>Edit </strong>&gt;<strong> Add stage variable</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XsHH1A1lq6ahH0qL.png" /></figure><p>2. Enter the following values before clicking <strong>Save</strong>:</p><p>3. Select the <strong>prod</strong> stage and create a <em>lambdaAlias</em> stage variable with the value of <em>prod</em>.</p><p>Now you can update the API Gateway Resources’ configuration to use the stage variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UH7vkRuT8p4TpkES.png" /></figure><blockquote>ItemsFunction:${stageVariables.lambdaAlias}</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*puh3s0x5rLhAYja8.png" /></figure><p><em>Note: Because the Lambda alias is dynamically configured via a stage variable in API Gateway, API Gateway cannot automatically create the necessary permissions. You would normally have to manually grant API Gateway permission to invoke the dev and prod Lambda function aliases.</em></p><p>API Gateway warns you about this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*vt7aAwowAc_Jd4ur.png" /></figure><p>You can grant the permission with the AWS CLI.</p><p>5. Re-deploy your dev and prod stages before proceeding ( <strong>Deploy API</strong>).</p><p>To test the API, you can no longer use the <strong>Test </strong>button in the <strong>Method Execution diagram</strong> because the method now depends on being executed in the context of a specific stage.</p><p>7. Paste the <strong>Invoke URL </strong>into a new browser tab and append <em>/items </em>to the end before navigating to the URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*NvgTWSultGF4TQIh.png" /></figure><p>The list of items is returned, confirming that the stage variable for the prod stage is configured correctly.</p><p>You have configured stage variables to reference the Lambda function used for the API Gateway backend integration. Now that API Gateway is correctly configured you are free to update the Lambda function code and play with its alias mapping without coming back to API Gateway.</p><p><strong>Conclusion</strong></p><p>In conclusion, this blog demonstrated how to build a simple serverless API using Amazon API Gateway and AWS Lambda, starting from mock data and moving to a real backend. By using concepts like models, mapping templates, and Lambda aliases, you now have a flexible setup that can easily support both development and production environments. This approach makes your API easier to manage, update, and scale as your application grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=057ec6fd061f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Secure and Scalable APIs with AWS Lambda and Amazon Cognito]]></title>
            <link>https://medium.com/@nnirmalb10/building-secure-and-scalable-apis-with-aws-lambda-and-amazon-cognito-7f1c16c91834?source=rss-2d57fd58e69a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f1c16c91834</guid>
            <dc:creator><![CDATA[Nirmal Bastakoti]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 05:58:51 GMT</pubDate>
            <atom:updated>2024-11-07T05:58:51.256Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital world, creating secure and scalable APIs is critical for building successful applications and services. Amazon Web Services (AWS) offers a powerful suite of tools to help achieve this. In this blog, we’ll explore how to integrate Amazon Cognito, AWS’s reliable user authentication and authorization service, with AWS Lambda, a serverless compute service, to build secure APIs. By combining Cognito’s strong authentication features with the flexibility of Lambda functions, developers can protect APIs from unauthorized access and ensure they scale effortlessly to accommodate growth and evolving requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHy-rrSCaue3zmNta1_aaQ.png" /></figure><p>Amazon Cognito is a user authentication, authorization, and user management service provided by AWS, designed to secure applications by managing user access and data. It offers two main components:</p><ol><li><strong>User Pools</strong> – This feature enables developers to add sign-up, sign-in, and access control to web and mobile applications. User Pools support features like multi-factor authentication (MFA), customizable sign-in experiences, and integration with external identity providers (such as Google, Facebook, and Apple). They allow you to define and manage a database of users and provide an authentication token to secure API requests.</li><li><strong>Identity Pools</strong> — These provide temporary, limited-access AWS credentials for users authenticated via a Cognito User Pool or an external identity provider. Identity Pools enable users to access other AWS services directly, such as S3, DynamoDB, or Lambda, without needing to directly store AWS credentials in the app.</li></ol><p><strong>Step 1: Setting up the Lambda Function</strong></p><p>a. To start, create a Lambda function in the AWS Management Console.</p><p>b. Define the function’s runtime environment and add the code logic based on your application’s requirements.</p><p>c. Make sure the Lambda function is configured correctly to handle incoming requests and generate the necessary responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czDDIX5baz6aZAn4kcpnBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RTl7sbWJz6EXSkcvvg_CA.png" /></figure><p><strong>Step 2: Creating API Gateway</strong></p><p>a. Next, navigate to the API Gateway service in the AWS Management Console and create a new API.</p><p>b. Define the resources and methods for your API, integrating it with the Lambda function created in the previous step.</p><p>c. Set up any additional configurations, such as request and response mappings, as needed.</p><p><em>Create a method in API gateway by integrating it with the lambda function created earlier:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*Zx-GVkYovqTYtpfhG4vtUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUc7KZT-Rr7i2-haGUwgxQ.png" /><figcaption>This image shows the integration of API gateway with the lambda function created earlier</figcaption></figure><p><strong>Step 3: Deploying API Gateway</strong></p><p>a. Once your API is configured, deploy it to a stage to generate an Invoke URL.</p><p>b. This URL will serve as the endpoint for accessing your API and invoking the associated Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCuUXrdCYr2haR6lCwt2Rg.png" /><figcaption>Deploy the API by creating new stage</figcaption></figure><p><strong>Step 4: Setting Up Amazon Cognito User Pool</strong></p><p>a. Switch to the Amazon Cognito service in the AWS Management Console and create a new User Pool.</p><p>b. Configure the user pool settings , including attributes, policies, and authentication methods to meet your application’s requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OivfSfS7wbzqqvgHlm8-7A.png" /><figcaption>Go to Cognito console and click on create User pool</figcaption></figure><p>In the next step you can set up the password according to your requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVfNrsQGwIQCA4ASo94u5g.png" /></figure><p>On the next step you can choose the email sender according to your requirement</p><p>(I am using ‘Send email with Cognito’ option for this demo)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*_r22Ckw6ay0l96MeGU3fHg.png" /></figure><p>In the next step give your userpool a name and click on use the cognito hosted UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8wPeY58icMIShvb7wk_lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*aXx8P0jW3qFUJSQwEfZlyg.png" /><figcaption>Give a custom domain name (In this case I am using Cognito domain)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*qeIVM_OxTOuny93PKAZHUw.png" /></figure><p>In the next step review your configurations and click on Create User Pool.</p><p><strong>Step 5: Creating User Accounts</strong></p><p>a. To create user accounts, access the Hosted UI for your Cognito User Pool and navigate to the sign-up page.</p><p>b. Register user accounts by entering the required details and completing the sign-up process.</p><p>Go to the user pool you created and navigate to App integration where you will find the App Client created earlier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zp56uj037uvOSilGubuDTw.png" /></figure><p>Click on the app client where you will find the Hosted UI url:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Tch1Nli8B6oIqnLzC893w.png" /></figure><p>Click on View Hosted UI which will take you to the Hosted UI URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*TTGMuZhvCYCHs8_88n9Fvg.png" /></figure><p>Click on Sign up and create a user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*fJYejAdarUVuRzd9R3qwyQ.png" /></figure><p>You will get verification code in your email. After that you can see the created user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aekvc7dLMJElo1zInVdpPA.png" /></figure><p><strong>Step 6: Configuring Authorizer in API Gateway</strong></p><p>a. Return to the API Gateway console and go to the “Authorizers” section.</p><p>b. Create a new authorizer and select “Cognito” as the type.</p><p>c. Specify the User Pool ID and App Client ID that correspond to your Cognito User Pool.</p><p>Go to the API Gateway console and click on navigate to Authorizers on your left panel and click on create Authorizer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*lTRZ5ILCyhn38WO-ruuU-A.png" /></figure><p><strong>Step 7: Generating Authorization Token</strong></p><p>To obtain an authorization token, open AWS CloudShell or another terminal interface and execute the following command:</p><pre>aws cognito-idp admin-initiate-auth - user-pool-id &lt;userpoolid&gt; - client-id &lt;clientid&gt; - auth-flow ADMIN_NO_SRP_AUTH - auth-parameters USERNAME=&lt;username&gt;,PASSWORD=&lt;password&gt;</pre><p><em>Replace &lt;userpoolid&gt; with the ID of your user pool, &lt;clientid&gt; with the app client ID, and &lt;username&gt; and &lt;password&gt; with the credentials from the sign-up process in the Hosted UI. This token will be used to authenticate requests to your API endpoints secured with Amazon Cognito.</em></p><p><strong>Step 8: Integrating Authorizer with API Gateway</strong></p><p>a. Edit the method request settings for your API endpoints in API Gateway.</p><p>b. Set the previously created Cognito authorizer to secure access to these endpoints.</p><p>c. Save the changes and redeploy your API to apply the updated configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MYtEqNKwr0eqIKKOL6hxPg.png" /></figure><p><strong>Step 9: Testing the API with Postman</strong></p><p>a. To test your API, download and install Postman if you haven’t already.</p><p>b. Launch Postman and create a new request. In the request settings, enter the API endpoint URL obtained after deploying the API Gateway.</p><p>c. Set up the request headers, including the Authorization header with the authorization token obtained from Amazon Cognito. Add any additional request parameters or body content if needed.</p><p>d. Send the request and check the API’s response. Verify that the status code matches expectations and that the API functions correctly.</p><p>e. Postman also allows you to perform various tests, like sending different request types (e.g., GET, POST, PUT) and exploring response data. Repeat the testing process under different conditions to confirm that your API behaves as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aCq3jbdVssFg_OgBaaaeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cvfuiCQeJTCLzzwx95R7A.png" /></figure><p>By following these steps, you can seamlessly integrate Amazon Cognito with AWS Lambda to secure your APIs. This setup not only provides strong user access management but also leverages AWS’s powerful scalability, ensuring your application is resilient and prepared for growth. With your API now secure and scalable, you’re well-positioned to deliver a dynamic and protected user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f1c16c91834" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating AWS Resource Management with Cron Jobs]]></title>
            <link>https://medium.com/@nnirmalb10/automating-aws-resource-management-with-cron-jobs-566af31c0313?source=rss-2d57fd58e69a------2</link>
            <guid isPermaLink="false">https://medium.com/p/566af31c0313</guid>
            <dc:creator><![CDATA[Nirmal Bastakoti]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 20:00:00 GMT</pubDate>
            <atom:updated>2025-01-16T11:47:07.395Z</atom:updated>
            <content:encoded><![CDATA[<p>Automating AWS resource management is crucial for optimizing costs, ensuring scalability, and maintaining operational efficiency. In this guide, we’ll explore how to set up cron jobs using AWS services like Lambda, EventBridge, and SNS to automate Auto Scaling and Elastic IP association.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*wP7TZsda9BCSb96HMe5KJg.png" /></figure><h3><strong>Step 1: Define Cron Job Schedule</strong></h3><p>Define the cron expression for your desired schedule. In this case, the expression is 45 7,17 * MON-FRI, which corresponds to 8:30 AM and 6:30 PM NST.</p><h3><strong>Step 2: Create IAM Role for Lambda</strong></h3><h4>2.1. Open the IAM Console:</h4><ul><li>Navigate to the IAM Console</li><li>Create a New Role:</li><li>Click on “Roles” in the left navigation pane.</li><li>Click “Create role.”</li><li>Choose “Lambda” as the use case.</li><li>Attach the necessary policies (e.g., AWSLambdaBasicExecutionRole, AWSLambdaRole).</li><li>Give your role a name and description.</li><li>Click “Create role.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L7jrv2h_zwnXstyn.png" /></figure><h3>Step 3: Create Lambda Function for Auto Scaling</h3><h4>3.1. Open the Lambda Console:</h4><ul><li>Navigate to the Lambda Console.</li><li>Create a New Lambda Function</li><li>Click “Create function.”</li><li>Choose “Author from scratch.”</li><li>Name your function.</li><li>Choose the runtime (e.g., Python 3.9).</li><li>Choose the IAM role created in Step 2.</li><li>Click “Create function.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyoE8w3q653GoC0UuKdg6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDUXzoxTu1MmBpdU8I0Ztg.png" /></figure><h4>3.2. Configure the Lambda Function Code:</h4><ul><li>Copy and paste the provided code for the Auto Scaling Lambda function.</li><li>Click “Save.”</li></ul><pre>import boto3<br>from datetime import datetime, timezone<br>autoscaling_client = boto3.client(&quot;autoscaling&quot;)<br>ec2_client = boto3.client(&quot;ec2&quot;)<br>asgs = [{&quot;name&quot;: &quot;&lt;auto scaling group name&gt;&quot;}, {&quot;name&quot;: &quot;&lt;auto scaling group name&gt;&quot;}]<br><br>def _get_instance_id_from_asg(asg_name):<br> response = autoscaling_client.describe_auto_scaling_groups(<br> AutoScalingGroupNames=[asg_name], MaxRecords=1<br> )<br> return response[&quot;AutoScalingGroups&quot;][0][&quot;Instances&quot;][0][&quot;InstanceId&quot;]<br><br>def _terminate_ec2_instance(instance_id):<br> ec2_client.terminate_instances(<br> InstanceIds=[instance_id],<br> )<br><br>def _scale_asg(asg_name, min_size, max_size, desired_capacity):<br> autoscaling_client.update_auto_scaling_group(<br> AutoScalingGroupName=asg_name,<br> MinSize=min_size,<br> MaxSize=max_size,<br> DesiredCapacity=desired_capacity,<br> )<br><br>def lambda_handler(event, context):<br> current_time = datetime.now(timezone.utc)<br> for asg in asgs:<br> # Stop the resources at NST 6:30pm<br> if current_time.hour == 12:<br> instance_id = _get_instance_id_from_asg(asg[&quot;name&quot;])<br> _scale_asg(asg[&quot;name&quot;], 0, 0, 0)<br> _terminate_ec2_instance(instance_id)<br> # Start the resources at NST 8:30am<br> elif current_time.hour == 2:<br> _scale_asg(asg[&quot;name&quot;], 1, 1, 1)</pre><h4>3.3. Set Up EventBridge Trigger:</h4><ul><li>In the Lambda function configuration, add an EventBridge trigger.</li><li>Configure the rule to use your desired cron expression (45(minutes) 2,12(Hour) ? (Month) *(Year) MON-FRI(Days)).</li><li>Click “Add” and then “Save changes.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*2MAqrGmVzjiSlKUk84LU5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*i4JTExX9dyAg8Yy1GM0MkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*FbBzBeFI8IHPKA6m.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*VfNrTWQglWAI4ExzEpX9uw.png" /></figure><h3>Step 4: Create Lambda Function for Elastic IP Association</h3><p>4.1. Repeat the same process as above to create a Lambda function for elastic IP allocation Configure the Lambda Function Code:</p><ul><li>Copy and paste the provided code for the Elastic IP Association Lambda function.</li><li>Click “Save.”</li></ul><pre>import json<br>import boto3<br>ec2_client = boto3.client(&quot;ec2&quot;)<br>eip_allocation_id = &quot;eipalloc_id...&quot;<br>eip_allocation_id = &quot;eipalloc_id....&quot;<br><br>def lambda_handler(event, context):<br> topic_arn = event[&quot;Records&quot;][0][&quot;Sns&quot;][&quot;TopicArn&quot;]<br> message = event[&quot;Records&quot;][0][&quot;Sns&quot;][&quot;Message&quot;]<br> instance_id = json.loads(message).get(&quot;EC2InstanceId&quot;)<br> allocation_id = (<br> eip_allocation_id<br> if &quot;&lt;elastic-ip&gt;&quot; in topic_arn<br> else eip_allocation_id<br> )<br> ec2_client.associate_address(<br> AllocationId=allocation_id,<br> InstanceId=instance_id,<br> )</pre><h4>4.2. Set Up SNS Trigger:</h4><ul><li>In the Lambda function configuration, add an SNS trigger.</li><li>Select the SNS topic that publishes messages when a new EC2 instance is launched.</li><li>Click “Add” and then “Save changes.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*QhrVDEDR1bhQoj3BNnqaZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*3JNOC6Juu1T6RzYUf41mGg.png" /></figure><h3>Step 5: Create an Event notification for the autoscaling group</h3><h4>5.1. To trigger the SNS notification during the launch of the EC2 instance from the autoscaling group, an event notification should be added to the autoscaling group.</h4><ul><li>Go to the <strong>Activity</strong> tab under ASG and click on <strong>Create Notification.</strong></li><li>Select the SNS Topic that was created in <strong>Step 4</strong> and select only the <strong>Launch</strong> event type</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*xgz2ikedNcoxMz-JT6Lo0w.png" /></figure><p>5.2. Once the Event Notification is successfully created, you should see the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-sXrvlgkZxx0GV57QP_wA.png" /></figure><h3>Step 6: Testing</h3><h4>6.1. Monitor Lambda Function Execution:</h4><p>Check the Lambda function logs in the Lambda Console to ensure they are triggered at the specified times or by SNS.</p><h4>6.2. Monitor Auto Scaling Group:</h4><p>Monitor the Auto Scaling Group in the EC2 Console to verify the scaling actions.</p><h4>6.3. Validate Elastic IP Association:</h4><p>Confirm that Elastic IPs are associated with new EC2 instances.</p><h3><strong>Summary</strong></h3><p>This guide explains how to set up a Cron job in EC2. It uses Lambda functions to adjust resources, EventBridge rules for scheduling regular tasks, SNS topics to send quick notifications, and IAM roles for secure access. By integrating cron jobs with Lambda, EventBridge, and SNS, we can schedule the turning off and on of EC2 instances at specified times during off-peak hours.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=566af31c0313" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Well Architected Framework Review]]></title>
            <link>https://medium.com/@nnirmalb10/well-architected-framework-review-bd7fe942f0d3?source=rss-2d57fd58e69a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd7fe942f0d3</guid>
            <category><![CDATA[aws-well-architected-tool]]></category>
            <category><![CDATA[wellarchitectedframework]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nirmal Bastakoti]]></dc:creator>
            <pubDate>Fri, 10 May 2024 09:06:08 GMT</pubDate>
            <atom:updated>2024-05-10T09:06:08.833Z</atom:updated>
            <content:encoded><![CDATA[<p>In the context of cloud computing, performance, cost-effectiveness, and overall operational excellence can only be maximized by comprehending and managing workloads well. With so many resources accessible in cloud environments like Amazon Web Services (AWS), estimating workload and ensuring it corresponds with best practices requires a systematic approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-euoIVq1Q3dbv6TS-EpRzg.jpeg" /></figure><h4>Analyzing Workload Resources</h4><p>Workload determination commences with a comprehensive analysis of the resources in use. This involves identifying the types of resources utilized for production workloads. Anything that delivers business value to a customer or collection of resource and code that delivers business value to a customer is considered as a workload. Analyzing resource consumption trends makes it feasible to comprehend the nature of the task and its requirements with clarity.</p><h4>Phase I: Defining Workload with Well-Architected Tool Service</h4><p>To define and validate the workload within AWS, the Well-Architected Tool service becomes instrumental. Accessible through the AWS Console, this service offers a structured approach to define workloads. Navigating to the AWS Well Architected tool and clicking on the ‘Define Workload’ and filling out the necessary details will create a workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZvz1YYzfkcE0-Il4nuOtg.png" /></figure><p>Once the workload is created different best practices question is generated based on the six pillars of the Well-Architected Framework:</p><p>Operational Excellence<br>Security<br>Reliability<br>Performance Efficiency<br>Cost Optimization<br>Sustainability</p><p>Answering Well-Architected Questions:</p><p>Upon accessing the Well-Architected Tool, the process involves answering a series of questions structured around these pillars. Each question provides various options that users can select, reflecting their workload’s configuration, usage patterns, and architectural decisions. These questions are designed to evaluate and guide users towards best practices aligned with the pillars.</p><p>In this phase of review, We go through the client’s account with the readonly access and all the used services are analyzed. The process involves answering a series of questions structured around these pillars based on the analysis of the services used and the best practices implemented within.</p><p><strong>Deriving Risk Assessment</strong></p><p>Once all basic questions have been answered, the Well-Architected Tool delivers a full assessment. Based on the responses received, this assessment gives a breakdown of the workload’s High-Risk and Medium-Risk regions. These risk assessments serve as valuable insights, pinpointing areas where improvements or optimizations may be necessary to enhance the workload’s performance, security, cost-effectiveness, and overall efficiency.</p><h4>Phase II: Second Review</h4><p>In this phase of review, a set of questions is sent to the client. This set includes questions related to the architecture of the client’s system. Different questions related to all of the security controls that have been put in place for AWS services like: Are instances of EC2 encrypted? Are there reliable alarms and notifications in place to identify and address possible threats?, questions related to any third party services being used are only a few of the many important queries that are mention in the question set that has been sent to the client.</p><p>Once the client have answered these question we start the second review of the workload. In this process, based on the answer given by the client we start answering the Well Architected Review best practices question left after the initial review and try to mitigate the risk within the workload. After the second review, there is certain differences in the number of risk with the post initial review risk.</p><h4>Phase III : Final Review</h4><p>After the second stage is completed number of High Risk and Medium Risk is generated based on the questions answered. Following the generated risk allocations, next step includes the remediations steps where we implement the required actions suggested by AWS to mitigate these risks.</p><p>Once we implement all the required best practices based on the nature of the workload we move to the next and final stage of the Well Architected Framework review. In this, we start answering all the remaining WAFR questions.</p><p>In conclusion, the process of workload determination and assessment within AWS involves a meticulous examination of resources, followed by an evaluation using the Well-Architected Tool. This systematic approach not only assists in defining workloads but also provides actionable insights to mitigate risks and optimize cloud environments for better performance and adherence to best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd7fe942f0d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>