<?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 Vipul Munot on Medium]]></title>
        <description><![CDATA[Stories by Vipul Munot on Medium]]></description>
        <link>https://medium.com/@vipmunot?source=rss-c298a9db6ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JUTSBPU4dgqFsSEreEc8mg@2x.jpeg</url>
            <title>Stories by Vipul Munot on Medium</title>
            <link>https://medium.com/@vipmunot?source=rss-c298a9db6ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:59:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vipmunot/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[Building a Text-to-SQL Knowledge Base with AWS Bedrock]]></title>
            <link>https://vipmunot.medium.com/building-a-text-to-sql-knowledge-base-with-aws-bedrock-8a0eb37491de?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a0eb37491de</guid>
            <category><![CDATA[bedrock-knowledge-bases]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 13:00:49 GMT</pubDate>
            <atom:updated>2025-09-05T13:07:20.965Z</atom:updated>
            <content:encoded><![CDATA[<p>Unlock the power of natural language to query your data warehouse — no SQL expertise required. This guide walks you through how to use AWS Bedrock, Amazon Redshift, and AWS CDK to build a secure, performant Text‑to‑SQL knowledge base.</p><h3>Why It Matters</h3><ul><li><strong>Business Accessibility:</strong> Empower non-technical users to explore data using plain English.</li><li><strong>Security First:</strong> Fine‑grained IAM permissions ensure safe data access.</li><li><strong>Governance Built-In:</strong> Execution timeouts and context control prevent runaway queries.</li><li><strong>Infrastructure as Code:</strong> Codify and version your entire setup with AWS CDK.</li></ul><h3><strong>What is Text-to-SQL?</strong></h3><p>Text-to-SQL is an AI capability that translates natural language questions into executable SQL queries. Instead of writing `SELECT COUNT(*) FROM employees`, users can simply ask “How many employees do we have?”</p><h3><strong>Architecture Overview</strong></h3><p>This solution leverages:</p><p>- <strong>AWS Bedrock Knowledge Base:</strong> Core AI service for natural language processing</p><p>- <strong>Amazon Redshift:</strong> Data warehouse for storing and querying data</p><p>- <strong>AWS CDK:</strong> Infrastructure as Code for deployment</p><p>- <strong>IAM Roles:</strong> Secure access management</p><h3><strong>Prerequisites</strong></h3><p>Before starting, ensure you have:</p><p>- AWS CLI configured with appropriate permissions</p><p>- Node.js and AWS CDK installed</p><p>- Access to an Amazon Redshift cluster</p><p>- Basic understanding of SQL and database schemas</p><h3><strong>Step 1: Setting Up the Database Schema</strong></h3><p>First, define your database structure with clear, descriptive table and column names:</p><pre>```sql<br> - Example employee table<br>CREATE TABLE quasar.public.employees (<br>employee_id INT PRIMARY KEY,<br>first_name VARCHAR(50),<br>last_name VARCHAR(50),<br>email VARCHAR(100),<br>hire_date DATE,<br>department_id INT<br>);<br>```</pre><h3><strong>Step 2: Creating IAM Roles and Permissions</strong></h3><p>The Knowledge Base requires specific permissions to interact with Redshift:</p><pre>const knowledgeBaseRole = new iam.Role(this, &#39;BedrockKnowledgeBaseRole&#39;, {<br>assumedBy: new iam.ServicePrincipal(&#39;bedrock.amazonaws.com&#39;),<br>});<br>// Redshift Data API permissions<br>knowledgeBaseRole.addToPolicy(new iam.PolicyStatement({<br>actions: [<br>&#39;redshift-data:GetStatementResult&#39;,<br>&#39;redshift-data:DescribeStatement&#39;,<br>&#39;redshift-data:ExecuteStatement&#39;<br>],<br>resources: [&#39;*&#39;]<br>}));<br>// SQL Workbench access for query generation<br>knowledgeBaseRole.addToPolicy(new iam.PolicyStatement({<br>actions: [<br>&#39;sqlworkbench:GetSqlRecommendations&#39;,<br>&#39;sqlworkbench:PutSqlGenerationContext&#39;<br>],<br>resources: [&#39;*&#39;]<br>}));<br></pre><h3><strong>Step 3: Defining Table Metadata</strong></h3><p>Provide detailed descriptions for tables and columns to improve query accuracy:</p><pre>const tables = [<br>    {<br>        name: &#39;quasar.public.employees&#39;,<br>        inclusion: &#39;INCLUDE&#39;,<br>        description: &#39;Employee information and details&#39;,<br>        columns: [<br>            { <br>                name: &#39;employee_id&#39;, <br>                description: &#39;Unique identifier for each employee&#39; <br>            },<br>            { <br>                name: &#39;first_name&#39;, <br>                description: &#39;Employee first name&#39; <br>            },<br>            { <br>                name: &#39;last_name&#39;, <br>                description: &#39;Employee last name&#39; <br>            },<br>            { <br>                name: &#39;email&#39;, <br>                description: &#39;Employee email address&#39; <br>            },<br>            { <br>                name: &#39;hire_date&#39;, <br>                description: &#39;Date when employee was hired (YYYY-MM-DD format)&#39; <br>            }<br>        ]<br>    }<br>];</pre><h3><strong>Step 4: Creating Curated Queries</strong></h3><p>Provide example natural language to SQL mappings to train the model:</p><pre>const curatedQueries = [<br>    {<br>        naturalLanguage: &#39;How many employees do we have?&#39;,<br>        sql: &quot;SELECT COUNT(DISTINCT employee_id) FROM quasar.public.employees;&quot;<br>    },<br>    {<br>        naturalLanguage: &#39;Show me employees hired in 2023&#39;,<br>        sql: &quot;SELECT first_name, last_name, hire_date FROM quasar.public.employees WHERE EXTRACT(YEAR FROM hire_date) = 2023;&quot;<br>    },<br>    {<br>        naturalLanguage: &#39;What are the most common first names?&#39;,<br>        sql: &quot;SELECT first_name, COUNT(*) as count FROM quasar.public.employees GROUP BY first_name ORDER BY count DESC LIMIT 10;&quot;<br>    }<br>];</pre><h3><strong>Step 5: Configuring the Knowledge Base</strong></h3><p>Create the Bedrock Knowledge Base with SQL configuration:</p><pre>const sqlKnowledgeBase = new bedrock.CfnKnowledgeBase(this, &#39;SQLKnowledgeBase&#39;, {<br>    name: &#39;TextToSQLKnowledgeBase&#39;,<br>    roleArn: knowledgeBaseRole.roleArn,<br>    knowledgeBaseConfiguration: {<br>        type: &#39;SQL&#39;,<br>        sqlKnowledgeBaseConfiguration: {<br>            type: &#39;REDSHIFT&#39;,<br>            redshiftConfiguration: {<br>                queryEngineConfiguration: {<br>                    type: &#39;PROVISIONED&#39;,<br>                    provisionedConfiguration: {<br>                        authConfiguration: { type: &#39;IAM&#39; },<br>                        clusterIdentifier: &#39;your-cluster-name&#39;<br>                    }<br>                },<br>                queryGenerationConfiguration: {<br>                    executionTimeoutSeconds: 200,<br>                    generationContext: { <br>                        curatedQueries, <br>                        tables <br>                    }<br>                },<br>                storageConfigurations: [{<br>                    type: &#39;REDSHIFT&#39;,<br>                    redshiftConfiguration: { <br>                        databaseName: &#39;your-database-name&#39; <br>                    }<br>                }]<br>            }<br>        }<br>    },<br>    description: &#39;Knowledge Base for converting natural language to SQL queries&#39;<br>});</pre><h3><strong>Step 6: Setting Up Database Permissions</strong></h3><pre>CREATE USER &quot;IAMR:${service-role}&quot; WITH PASSWORD DISABLE;<br>GRANT SELECT ON ${schemaName}.${tableName} TO &quot;IAMR:${serviceRole}&quot;;<br>GRANT USAGE ON SCHEMA ${schemaName} TO &quot;IAMR:${serviceRole}&quot;;</pre><p><strong>Reference Documentation</strong>: <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base-prereq-structured.html">AWS Bedrock Knowledge Base Prerequisites for Structured Data</a></p><h3><strong>Best Practices</strong></h3><p>When building a Text-to-SQL Knowledge Base, descriptive naming is crucial for accuracy. Use clear, business-friendly names for tables and columns such as `customer_acquisition_date` instead of abbreviated forms like `cust_acq_dt`, and `total_revenue` rather than `tot_rev`. This clarity helps the AI model better understand the data context and generate more accurate queries.</p><p>Comprehensive metadata forms the foundation of effective query generation. Provide detailed descriptions that include data types and formats, business context and meaning, relationships between tables, and common use cases. This rich metadata enables the model to understand not just what the data is, but how it’s typically used in business scenarios.</p><p>Quality curated queries serve as training examples for the AI model. Create diverse examples that cover simple aggregations like COUNT, SUM, and AVG operations, filtering and sorting scenarios, date range queries, multi-table joins, and complex business logic. These examples teach the model common patterns and help it handle similar requests from users.</p><p>Security considerations must be built into the system from the ground up. Use IAM roles with least privilege access, implement row-level security where needed to protect sensitive data, monitor query execution and results for unusual patterns, and set appropriate timeout limits to prevent resource abuse. These measures ensure that democratizing data access doesn’t compromise data security or system performance.</p><h3>Full Code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2f69daa31cbb96031a3b6b703d7331/href">https://medium.com/media/cd2f69daa31cbb96031a3b6b703d7331/href</a></iframe><h3><strong>Conclusion</strong></h3><p>A well-configured Text-to-SQL Knowledge Base democratizes data access, enabling business users to get insights without SQL expertise. Success depends on thorough metadata, quality curated queries, and continuous refinement based on user needs.</p><p>The investment in setup pays dividends through increased data accessibility, faster insights, and reduced burden on technical teams. Start with a focused dataset, iterate based on feedback, and gradually expand coverage as confidence grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a0eb37491de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Knowledge Base with AWS CDK and OpenSearch Serverless]]></title>
            <link>https://vipmunot.medium.com/building-a-knowledge-base-with-aws-cdk-and-opensearch-serverless-53ddef92cb0d?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ddef92cb0d</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[aws-cdk-tutorial]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 00:50:56 GMT</pubDate>
            <atom:updated>2024-08-07T18:50:02.186Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’ll explore how to create a knowledge base using AWS Cloud Development Kit (CDK) and the OpenSearch Serverless service. The code provided sets up the necessary infrastructure, including an OpenSearch collection, encryption and network policies, and a Lambda function to create the index.</p><h3>Setting the Stage</h3><p>The code begins by creating an IAM role <em>(CreateIndexExecutionRole)</em> with the <em>AWSLambdaBasicExecutionRole</em> managed policy attached. This role will be assumed by the Lambda function responsible for creating the knowledge base index.</p><h3>Provisioning the OpenSearch Collection</h3><p>Next, an OpenSearch Serverless collection is created using the <em>CfnCollection</em> resource. This collection is of type <em>VECTORSEARCH</em>, which is specifically designed for vector similarity search use cases, making it ideal for knowledge base applications.</p><h3>Securing the Collection</h3><p>To secure the OpenSearch collection, the code provisions several security policies:</p><p><strong>Encryption Policy:</strong> A KMS key is created (<em>OpenSearchKMSKey</em>), and an encryption policy (<em>OpenSearchCollectionSecurityPolicy</em>) is defined. This policy specifies how the collection data will be encrypted using the created KMS key.</p><p><strong>Network Policy:</strong> A network policy (<em>OpenSearchNetworkPolicy</em>) is created to control access to the collection. This policy can be configured to allow public access or restrict access to specific VPC endpoints.</p><p><strong>Access Policy:</strong> An access policy (<em>OpenSearchCollectionAccessPolicy</em>) is defined to grant permissions to the specified principal ARNs (including the current account and the Lambda execution role) to perform various operations on the collection and its indexes.</p><p>These security policies ensure that the knowledge base data is encrypted at rest, network access is controlled, and only authorized entities can interact with the collection and its indexes.</p><h3>Preparing for Index Creation</h3><p>While the provided code snippet doesn’t include the implementation details of the <em>CreateIndexFunction</em>, it sets the stage for this Lambda function to create the knowledge base index within the provisioned OpenSearch collection.</p><p>The <em>CreateIndexFunction</em> would use the <em>opensearch-py</em> library to interact with the OpenSearch API and define the index mapping, settings, and other configurations specific to the knowledge base use case.</p><h3>Deploying the Knowledge Base Infrastructure</h3><p>To deploy the knowledge base infrastructure, including the OpenSearch collection and the Lambda function for index creation, you would use the AWS CDK to synthesize the CloudFormation template and deploy the stack. The CDK allows you to define and provision cloud resources using familiar programming languages like Python.</p><h3>Conclusion</h3><p>This blog post explored the process of creating a knowledge base index using AWS Lambda and OpenSearch Serverless. The provided code sets up the necessary infrastructure, including an OpenSearch collection, encryption and network policies, and an IAM role for the Lambda function responsible for index creation.</p><p>By leveraging OpenSearch Serverless and its vector similarity search capabilities, you can build powerful knowledge base applications that provide fast and accurate search results. The combination of AWS Lambda and OpenSearch Serverless allows for a serverless and scalable architecture, reducing operational overhead and enabling you to focus on building innovative knowledge base solutions.</p><h3>CDK Code</h3><pre>import os, re, json<br>from aws_cdk import (<br>    aws_lambda as lambda_,<br>    CustomResource,<br>    aws_iam as iam,<br>    aws_kms as kms,<br>    aws_sns as sns,<br>    aws_logs as logs,<br>    aws_stepfunctions as sfn,<br>    aws_events as ev,<br>    aws_events_targets as evt,<br>    Size,<br>    Duration,<br>    custom_resources as cr,<br>    Stack,<br>    RemovalPolicy,<br>    BundlingOptions,<br>    aws_scheduler as sc,<br>    aws_bedrock as bedrock,<br>    aws_opensearchserverless as opensearchserverless,<br>)<br>from constructs import Construct<br>from typing import Any, Dict, List, Optional<br><br><br>def getBundlingCommand(package_name):<br><br>        return [<br>            &quot;bash&quot;,<br>            &quot;-c&quot;,<br>            &quot; &amp;&amp; &quot;.join(<br>                [<br>                    &quot;mkdir /asset-output/python&quot;,<br>                    (&quot;pip install --no-cache -t /asset-output/python -I {}&quot;).format(<br>                        package_name<br>                    ),<br>                    &quot;cp -au . /asset-output/python&quot;,<br>                ]<br>            ),<br>        ]<br><br><br><br>def get_access_policy(collection_name: str, principal_arns: List[str]) -&gt; str:<br>    policy = [<br>        {<br>            &quot;Rules&quot;: [<br>                {<br>                    &quot;ResourceType&quot;: &quot;index&quot;,<br>                    &quot;Resource&quot;: [<br>                        f&quot;index/{collection_name}/*&quot;,<br>                    ],<br>                    &quot;Permission&quot;: [<br>                        &quot;aoss:UpdateIndex&quot;,<br>                        &quot;aoss:DescribeIndex&quot;,<br>                        &quot;aoss:ReadDocument&quot;,<br>                        &quot;aoss:WriteDocument&quot;,<br>                        &quot;aoss:CreateIndex&quot;,<br>                    ],<br>                },<br>                {<br>                    &quot;ResourceType&quot;: &quot;collection&quot;,<br>                    &quot;Resource&quot;: [<br>                        f&quot;collection/{collection_name}&quot;,<br>                    ],<br>                    &quot;Permission&quot;: [<br>                        &quot;aoss:DescribeCollectionItems&quot;,<br>                        &quot;aoss:CreateCollectionItems&quot;,<br>                        &quot;aoss:UpdateCollectionItems&quot;,<br>                    ],<br>                },<br>            ],<br>            &quot;Principal&quot;: principal_arns,<br>        }<br>    ]<br>    return json.dumps(policy)<br><br><br>def get_encryption_policy(<br>    collection_name: str, kms_key_arn: Optional[str] = None<br>) -&gt; str:<br>    policy: Dict[str, Any] = {<br>        &quot;Rules&quot;: [<br>            {<br>                &quot;ResourceType&quot;: &quot;collection&quot;,<br>                &quot;Resource&quot;: [<br>                    f&quot;collection/{collection_name}&quot;,<br>                ],<br>            }<br>        ],<br>    }<br>    if kms_key_arn:<br>        policy[&quot;KmsARN&quot;] = kms_key_arn<br>    else:<br>        policy[&quot;AWSOwnedKey&quot;] = True<br>    return json.dumps(policy)<br><br><br>def get_network_policy(<br>    collection_name: str, vpc_endpoints: Optional[List[str]] = None<br>) -&gt; str:<br>    policy: List[Dict[str, Any]] = [<br>        {<br>            &quot;Rules&quot;: [<br>                {<br>                    &quot;ResourceType&quot;: &quot;dashboard&quot;,<br>                    &quot;Resource&quot;: [<br>                        f&quot;collection/{collection_name}&quot;,<br>                    ],<br>                },<br>                {<br>                    &quot;ResourceType&quot;: &quot;collection&quot;,<br>                    &quot;Resource&quot;: [<br>                        f&quot;collection/{collection_name}&quot;,<br>                    ],<br>                },<br>            ],<br>        }<br>    ]<br>    if vpc_endpoints:<br>        policy[0][&quot;SourceVPCEs&quot;] = vpc_endpoints<br>    else:<br>        policy[0][&quot;AllowFromPublic&quot;] = True<br>    return json.dumps(policy)<br><br><br>class KnowledgeBaseConstruct(Construct):<br><br>    def __init__(<br>        self,<br>        scope: Construct,<br>        id: str,<br>        stage: str,<br>        application_name: str,<br>        **kwargs,<br>    ) -&gt; None:<br>        super().__init__(scope, id, **kwargs)<br><br>        LayerVersion_awsauth_latest = lambda_.LayerVersion(<br>            scope=self,<br>            id=&quot;LayerVersion_awsauth_latest&quot;,<br>            layer_version_name=f&quot;{application_name}-awsauth-python-layer&quot;,<br>            description=&quot;awsauth-python-layer&quot;,<br>            compatible_architectures=[lambda_.Architecture.X86_64],<br>            compatible_runtimes=[lambda_.Runtime.PYTHON_3_12],<br>            code=lambda_.Code.from_asset(<br>                path=os.path.join(os.path.dirname(__file__), &quot;EmptyBundle&quot;),<br>                bundling=BundlingOptions(<br>                    image=lambda_.Runtime.PYTHON_3_12.bundling_image,<br>                    command=getBundlingCommand(<br>                  <br>                        &quot;requests-aws4auth&quot;,<br>                    ),<br>                ),<br>            ),<br>        )<br>        LayerVersion_opensearch_py_latest = lambda_.LayerVersion(<br>            scope=self,<br>            id=&quot;LayerVersion_opensearch-py_latest&quot;,<br>            layer_version_name=f&quot;{application_name}-opensearch-py-python-layer&quot;,<br>            description=&quot;opensearch-py-python-layer&quot;,<br>            compatible_architectures=[lambda_.Architecture.X86_64],<br>            compatible_runtimes=[lambda_.Runtime.PYTHON_3_12],<br>            code=lambda_.Code.from_asset(<br>                path=os.path.join(os.path.dirname(__file__), &quot;EmptyBundle&quot;),<br>                bundling=BundlingOptions(<br>                    image=lambda_.Runtime.PYTHON_3_12.bundling_image,<br>                    command=getBundlingCommand(<br>                    <br>                        &quot;opensearch-py&quot;,<br>                    ),<br>                ),<br>            ),<br>        )<br><br>        create_index_lambda_execution_role = iam.Role(<br>            self,<br>            &quot;CreateIndexExecutionRole&quot;,<br>            assumed_by=iam.ServicePrincipal(&quot;lambda.amazonaws.com&quot;),<br>            description=&quot;Managed by CDK - {}&quot;.format(application_name),<br>            managed_policies=[<br>                iam.ManagedPolicy.from_aws_managed_policy_name(<br>                    &quot;service-role/AWSLambdaBasicExecutionRole&quot;<br>                )<br>            ],<br>        )<br><br>        open_search_collection = opensearchserverless.CfnCollection(<br>            self,<br>            &quot;OpenSearchCollection&quot;,<br>            name=f&quot;{application_name}-{stage}-collection&quot;.lower(),<br>            description=&quot;Managed by CDK - {}&quot;.format(application_name),<br>            type=&quot;VECTORSEARCH&quot;,<br>        )<br>        key = kms.Key(<br>            self,<br>            &quot;OpenSearchKMSKey&quot;,<br>            alias=f&quot;{application_name}-{stage}-opensearch-serverless&quot;,<br>            enable_key_rotation=True,<br>        )<br><br>        cfn_encryption_policy = opensearchserverless.CfnSecurityPolicy(<br>            self,<br>            &quot;OpenSearchCollectionSecurityPolicy&quot;,<br>            name=f&quot;{application_name}-{stage}-security-policy&quot;.lower(),<br>            type=&quot;encryption&quot;,<br>            description=&quot;Managed by CDK - {}&quot;.format(application_name),<br>            policy=get_encryption_policy(<br>                collection_name=open_search_collection.name,<br>                kms_key_arn=key.key_arn,<br>            ),<br>        )<br>        cfn_network_policy = opensearchserverless.CfnSecurityPolicy(<br>            self,<br>            &quot;OpenSearchNetworkPolicy&quot;,<br>            name=f&quot;{application_name}-{stage}-network-policy&quot;.lower(),<br>            description=&quot;Managed by CDK - {}&quot;.format(application_name),<br>            type=&quot;network&quot;,<br>            policy=get_network_policy(<br>                collection_name=open_search_collection.name,<br>            ),<br>        )<br>        ## Add Bedrock KB Role for OpenSearch access<br>        principal_arns = [<br>            iam.AccountPrincipal(Stack.of(self).account).arn,<br>            create_index_lambda_execution_role.role_arn,<br>        ]<br>        cfn_access_policy = opensearchserverless.CfnAccessPolicy(<br>            self,<br>            f&quot;OpenSearchCollectionAccessPolicy&quot;,<br>            name=f&quot;{application_name}-{stage}-access-policy&quot;.lower(),<br>            description=&quot;Managed by CDK - {}&quot;.format(application_name),<br>            type=&quot;data&quot;,<br>            policy=get_access_policy(<br>                collection_name=open_search_collection.name,<br>                principal_arns=principal_arns,<br>            ),<br>        )<br>        open_search_collection.add_dependency(cfn_encryption_policy)<br>        open_search_collection.add_dependency(cfn_network_policy)<br>        open_search_collection.add_dependency(cfn_access_policy)<br><br>        vector_index_name = &quot;bedrock-knowledgebase-index&quot;<br>        vector_field_name = &quot;bedrock-knowledge-base-default-vector&quot;<br><br>        create_index_function = lambda_.Function(<br>            self,<br>            &quot;CreateIndexFunction&quot;,<br>            runtime=lambda_.Runtime.PYTHON_3_12,<br>            handler=&quot;lambda_function.lambda_handler&quot;,<br>            description=&quot;Managed by CDK - {}&quot;.format(application_name),<br>            code=lambda_.Code.from_asset(<br>                os.path.join(<br>                    os.path.dirname(__file__),<br>                    &quot;lambdas/create_index&quot;,<br>                )<br>            ),<br>            role=create_index_lambda_execution_role,<br>            layers=[LayerVersion_awsauth_latest, LayerVersion_opensearch_py_latest],<br>            environment={<br>                &quot;REGION_NAME&quot;: Stack.of(self).region,<br>                &quot;COLLECTION_HOST&quot;: open_search_collection.attr_collection_endpoint,<br>                &quot;VECTOR_INDEX_NAME&quot;: vector_index_name,<br>                &quot;VECTOR_FIELD_NAME&quot;: vector_field_name,<br>            },<br>            timeout=Duration.seconds(900),<br>            tracing=lambda_.Tracing.ACTIVE,<br>        )<br>        create_index_lambda_execution_role.add_to_policy(<br>            iam.PolicyStatement(<br>                effect=iam.Effect.ALLOW,<br>                actions=[&quot;aoss:APIAccessAll&quot;],<br>                resources=[<br>                    f&quot;arn:aws:aoss:{Stack.of(self).region}:{Stack.of(self).account}:collection/{open_search_collection.attr_id}&quot;<br>                ],<br>            )<br>        )<br>        lambda_provider = cr.Provider(<br>            self,<br>            &quot;LambdaCreateIndexCustomProvider&quot;,<br>            on_event_handler=create_index_function,<br>        )<br><br>        lambda_cr = CustomResource(<br>            self,<br>            &quot;LambdaCreateIndexCustomResource&quot;,<br>            service_token=lambda_provider.service_token,<br>        )<br><br>        kb_name = &quot;BedrockKnowledgeBase&quot;<br>        text_field = &quot;AMAZON_BEDROCK_TEXT_CHUNK&quot;<br>        metadata_field = &quot;AMAZON_BEDROCK_METADATA&quot;<br><br>        embedding_model_arn = f&quot;arn:aws:bedrock:{Stack.of(self).region}::foundation-model/amazon.titan-embed-text-v1&quot;<br>        # Create an execution role for the knowledge base<br>        model_policy = iam.ManagedPolicy(<br>            self,<br>            f&quot;AmazonBedrockFoundationModelPolicyForKnowledgeBase_{kb_name}&quot;,<br>            statements=[<br>                iam.PolicyStatement(<br>                    effect=iam.Effect.ALLOW,<br>                    actions=[&quot;bedrock:InvokeModel&quot;],<br>                    resources=[embedding_model_arn],<br>                )<br>            ],<br>        )<br><br>        aoss_policy = iam.ManagedPolicy(<br>            self,<br>            f&quot;AmazonBedrockOSSPolicyForKnowledgeBase_{kb_name}&quot;,<br>            statements=[<br>                iam.PolicyStatement(<br>                    effect=iam.Effect.ALLOW,<br>                    actions=[&quot;aoss:APIAccessAll&quot;],<br>                    resources=[<br>                        f&quot;arn:aws:aoss:{Stack.of(self).region}:{Stack.of(self).account}:collection/{open_search_collection.attr_id}&quot;<br>                    ],<br>                )<br>            ],<br>        )<br><br>        kb_role = iam.Role(<br>            self,<br>            &quot;KnowledgeBaseRole&quot;,<br>            assumed_by=iam.ServicePrincipal(&quot;bedrock.amazonaws.com&quot;),<br>            managed_policies=[model_policy, aoss_policy],<br>        )<br>        knowledge_base = bedrock.CfnKnowledgeBase(<br>            self,<br>            &quot;KnowledgeBase&quot;,<br>            role_arn=kb_role.role_arn,<br>            name=kb_name,<br>            description=&quot;Managed by CDK - {}&quot;.format(application_name),<br>            knowledge_base_configuration=bedrock.CfnKnowledgeBase.KnowledgeBaseConfigurationProperty(<br>                type=&quot;VECTOR&quot;,<br>                vector_knowledge_base_configuration=bedrock.CfnKnowledgeBase.VectorKnowledgeBaseConfigurationProperty(<br>                    embedding_model_arn=embedding_model_arn<br>                ),<br>            ),<br>            storage_configuration=bedrock.CfnKnowledgeBase.StorageConfigurationProperty(<br>                type=&quot;OPENSEARCH_SERVERLESS&quot;,<br>                opensearch_serverless_configuration=bedrock.CfnKnowledgeBase.OpenSearchServerlessConfigurationProperty(<br>                    collection_arn=open_search_collection.attr_arn,<br>                    field_mapping=bedrock.CfnKnowledgeBase.OpenSearchServerlessFieldMappingProperty(<br>                        metadata_field=metadata_field,<br>                        text_field=text_field,<br>                        vector_field=vector_field_name,<br>                    ),<br>                    vector_index_name=vector_index_name,<br>                ),<br>            ),<br>        )<br>        knowledge_base.add_dependency(open_search_collection)<br>        knowledge_base.node.add_dependency(lambda_cr)<br>        s3_data_source = bedrock.CfnDataSource(<br>            self,<br>            &quot;MyCfnDataSource&quot;,<br>            knowledge_base_id=knowledge_base.attr_knowledge_base_id,<br>            name=f&quot;{application_name}_s3_source&quot;,<br>            description=&quot;Managed by CDK - {}&quot;.format(application_name),<br>            server_side_encryption_configuration=bedrock.CfnDataSource.ServerSideEncryptionConfigurationProperty(<br>                kms_key_arn=key.key_arn<br>            ),<br>            data_deletion_policy=&quot;RETAIN&quot;,<br>            data_source_configuration=bedrock.CfnDataSource.DataSourceConfigurationProperty(<br>                s3_configuration=bedrock.CfnDataSource.S3DataSourceConfigurationProperty(<br>                    bucket_arn=f&quot;arn:aws:s3:::{genai_bucket}&quot;,<br>                    # the properties below are optional<br>                    inclusion_prefixes=[&quot;genai_folder/&quot;],<br>                ),<br>                type=&quot;S3&quot;,<br>            ),<br>        )<br>        s3_data_source.add_dependency(knowledge_base)</pre><h3>CreateIndexFunction</h3><p>This lambda function has two files:</p><p><em>lambda_function.py</em></p><pre>from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth<br>import os<br>import boto3<br>import json<br>import logging<br>import cfnresponse<br>import time<br><br>HOST = os.environ.get(&quot;COLLECTION_HOST&quot;)<br>VECTOR_INDEX_NAME = os.environ.get(&quot;VECTOR_INDEX_NAME&quot;)<br>VECTOR_FIELD_NAME = os.environ.get(&quot;VECTOR_FIELD_NAME&quot;)<br>REGION_NAME = os.environ.get(&quot;REGION_NAME&quot;)<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br><br>def log(message):<br>    logger.info(message)<br><br><br>def lambda_handler(event, context):<br>    &quot;&quot;&quot;<br>    Lambda handler to create OpenSearch Index<br>    &quot;&quot;&quot;<br>    log(f&quot;Event: {json.dumps(event)}&quot;)<br><br>    session = boto3.Session()<br><br>    # Get STS client from session<br>    sts_client = session.client(&quot;sts&quot;)<br><br>    # Get caller identity<br>    caller_identity = sts_client.get_caller_identity()<br><br>    # Print the caller identity information<br>    log(f&quot;Caller Identity: {caller_identity}&quot;)<br><br>    # Specifically, print the ARN of the caller<br>    log(f&quot;ARN: {caller_identity[&#39;Arn&#39;]}&quot;)<br><br>    creds = session.get_credentials()<br><br>    # Get STS client from session<br>    sts_client = session.client(&quot;sts&quot;)<br><br>    # Get caller identity<br>    caller_identity = sts_client.get_caller_identity()<br><br>    # Print the caller identity information<br>    log(f&quot;Caller Identity: {caller_identity}&quot;)<br><br>    # Specifically, print the ARN of the caller<br>    log(f&quot;ARN: {caller_identity[&#39;Arn&#39;]}&quot;)<br><br>    log(f&quot;HOST: {HOST}&quot;)<br>    host = HOST.split(&quot;//&quot;)[1]<br><br>    region = REGION_NAME<br>    service = &quot;aoss&quot;<br>    status = cfnresponse.SUCCESS<br>    response = {}<br><br>    try:<br>        auth = AWSV4SignerAuth(creds, region, service)<br><br>        client = OpenSearch(<br>            hosts=[{&quot;host&quot;: host, &quot;port&quot;: 443}],<br>            http_auth=auth,<br>            use_ssl=True,<br>            verify_certs=True,<br>            connection_class=RequestsHttpConnection,<br>            pool_maxsize=20,<br>        )<br>        index_name = VECTOR_INDEX_NAME<br><br>        if event[&quot;RequestType&quot;] == &quot;Create&quot;:<br>            log(f&quot;Creating index: {index_name}&quot;)<br><br>            index_body = {<br>                &quot;settings&quot;: {<br>                    &quot;index.knn&quot;: True,<br>                    &quot;index.knn.algo_param.ef_search&quot;: 512,<br>                },<br>                &quot;mappings&quot;: {<br>                    &quot;properties&quot;: {  <br>                        VECTOR_FIELD_NAME: {  <br>                            &quot;type&quot;: &quot;knn_vector&quot;,<br>                            &quot;dimension&quot;: 1536,<br>                            &quot;method&quot;: {  <br>                                &quot;space_type&quot;: &quot;innerproduct&quot;,<br>                                &quot;engine&quot;: &quot;FAISS&quot;,<br>                                &quot;name&quot;: &quot;hnsw&quot;,<br>                                &quot;parameters&quot;: {<br>                                    &quot;m&quot;: 16,<br>                                    &quot;ef_construction&quot;: 512,<br>                                },<br>                            },<br>                        },<br>                        &quot;AMAZON_BEDROCK_METADATA&quot;: {&quot;type&quot;: &quot;text&quot;, &quot;index&quot;: False},<br>                        &quot;AMAZON_BEDROCK_TEXT_CHUNK&quot;: {&quot;type&quot;: &quot;text&quot;},<br>                        &quot;id&quot;: {&quot;type&quot;: &quot;text&quot;},<br>                    }<br>                },<br>            }<br><br>            response = client.indices.create(index_name, body=index_body)<br><br>            log(f&quot;Response: {response}&quot;)<br><br>            log(&quot;Sleeping for 1 minutes to let index create.&quot;)<br>            time.sleep(60)  <br><br>        elif event[&quot;RequestType&quot;] == &quot;Delete&quot;:<br>            log(f&quot;Deleting index: {index_name}&quot;)<br>            response = client.indices.delete(index_name)<br>            log(f&quot;Response: {response}&quot;)<br>        else:<br>            log(&quot;Continuing without action.&quot;)<br><br>    except Exception as e:<br>        logging.error(&quot;Exception: %s&quot; % e, exc_info=True)<br>        status = cfnresponse.FAILED<br><br>    finally:<br>        cfnresponse.send(event, context, status, response)<br><br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: json.dumps(&quot;Create index lambda ran successfully.&quot;),<br>    }</pre><p><em>cfnresponse.py</em></p><pre># © 2023 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.<br>#<br># This AWS Content is provided subject to the terms of the AWS Customer Agreement<br># available at http://aws.amazon.com/agreement or other written agreement between<br># Customer and either Amazon Web Services, Inc. or Amazon Web Services EMEA SARL or both.<br><br># # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.<br># SPDX-License-Identifier: MIT-0<br><br>from __future__ import print_function<br>import urllib3<br>import json<br>import logging<br><br># Set up logging<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br>SUCCESS = &quot;SUCCESS&quot;<br>FAILED = &quot;FAILED&quot;<br><br>http = urllib3.PoolManager()<br><br><br>def send(<br>    event,<br>    context,<br>    responseStatus,<br>    responseData,<br>    physicalResourceId=None,<br>    noEcho=False,<br>    reason=None,<br>):<br>    responseUrl = event[&quot;ResponseURL&quot;]<br><br>    logger.info(f&quot;ResponseURL: {responseUrl}&quot;)<br><br>    responseBody = {<br>        &quot;Status&quot;: responseStatus,<br>        &quot;Reason&quot;: reason<br>        or &quot;See the details in CloudWatch Log Stream: {}&quot;.format(<br>            context.log_stream_name<br>        ),<br>        &quot;PhysicalResourceId&quot;: physicalResourceId or context.log_stream_name,<br>        &quot;StackId&quot;: event[&quot;StackId&quot;],<br>        &quot;RequestId&quot;: event[&quot;RequestId&quot;],<br>        &quot;LogicalResourceId&quot;: event[&quot;LogicalResourceId&quot;],<br>        &quot;NoEcho&quot;: noEcho,<br>        &quot;Data&quot;: responseData,<br>    }<br><br>    json_responseBody = json.dumps(responseBody)<br><br>    logger.info(&quot;Response body:&quot;)<br>    logger.info(json_responseBody)<br><br>    headers = {&quot;content-type&quot;: &quot;&quot;, &quot;content-length&quot;: str(len(json_responseBody))}<br><br>    try:<br>        response = http.request(<br>            &quot;PUT&quot;, responseUrl, headers=headers, body=json_responseBody<br>        )<br>        logger.info(f&quot;Status code: {response.status}&quot;)<br>    except Exception as e:<br><br>        logger.info(f&quot;send(..) failed executing http.request(..): {e}&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ddef92cb0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating enabling termination Protection for AWS Cloudformation]]></title>
            <link>https://vipmunot.medium.com/automating-enabling-termination-protection-for-aws-cloudformation-b41cc01119f1?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/b41cc01119f1</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 19:09:12 GMT</pubDate>
            <atom:updated>2024-01-04T19:09:12.100Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS Cloudformation has evolved as one of integral part of devops architecture of any team. It is good practice to enable termination protection. You can automate the process by using EventBrige Rules -&gt; Lambda Setup to automate this process.</p><h3><strong>Steps</strong></h3><ol><li>Create a Lambda function with Python Run time. Add the following code in the code editor</li></ol><pre>import boto3<br>import logging<br><br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br>client = boto3.client(&quot;cloudformation&quot;)<br><br><br>def lambda_handler(event, context):<br>    paginator = client.get_paginator(&quot;describe_stacks&quot;)<br>    response_iterator = paginator.paginate()<br>    for page in response_iterator:<br>        for objects in page[&quot;Stacks&quot;]:<br>            if &quot;ParentId&quot; in objects:<br>                logger.info(&quot;Skipping %s as it is a Nested Stack&quot;, objects[&quot;StackName&quot;])<br>            else:<br>                response = client.update_termination_protection(<br>                    EnableTerminationProtection=True, StackName=objects[&quot;StackName&quot;]<br>                )<br>                logger.info(&quot;%s response %s&quot;, objects[&quot;StackName&quot;], response)<br><br>    return {&quot;status&quot;: 200}</pre><p>2. Add policy to Lambda function so it can update the CFN</p><p>3. Add an Event Bridge trigger using AWS Lambda Console with Schedule expression: <strong>cron(0 18 ? * FRI *) </strong>and<strong> </strong>Event bus: <strong>default</strong></p><p>This will trigger lambda every Friday at 6pm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b41cc01119f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda Example using AWS CDK]]></title>
            <link>https://vipmunot.medium.com/lambda-example-using-aws-cdk-cac648d3c72a?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/cac648d3c72a</guid>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 17:12:41 GMT</pubDate>
            <atom:updated>2022-08-10T17:12:41.611Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we are going to cover some of the most common properties we use to create and configure an lambda in AWS CDK.</p><p>At the time of writing I was using <strong>CDK version: </strong>2.34.2</p><h4>Importing Dependencies</h4><pre><strong>from</strong> aws_cdk <strong>import</strong> ( aws_iam <strong>as</strong> iam,aws_lambda <strong>as</strong> lambda_,     aws_lambda_destinations <strong>as</strong> destinations, )</pre><h4>Lambda Role</h4><pre>lambda_role = iam.Role(<br>            self,<br>            &quot;lambda-role&quot;,<br>            assumed_by=iam.CompositePrincipal(<br>                iam.ServicePrincipal(&quot;lambda.amazonaws.com&quot;),<br>            ),<br>        )<br><br>        lambda_role.add_to_policy(<br>            iam.PolicyStatement(actions=[&quot;sns:Publish&quot;], resources=[snstopic])<br>        )<br><br>        )<br>        lambda_role.add_managed_policy(<br>            iam.ManagedPolicy.from_aws_managed_policy_name(<br>                &quot;service-role/AWSLambdaBasicExecutionRole&quot;<br>            )<br>        )</pre><h4>Create Lambda</h4><pre>snstopic = &quot;&lt;SNS_TOPIC_ARN&gt;&quot;<br>lambda_.Function(<br>            self,<br>            &quot;lambda-function&quot;,<br>            runtime=lambda_.Runtime.PYTHON_3_9,<br>            code=lambda_.Code.from_asset(&quot;resources/lambda&quot;),<br>            role=lambda_role,<br>            handler=&quot;lambda_function.lambda_handler&quot;,<br>            timeout=Duration.seconds(600),<br>            environment={&quot;snstopic&quot;: snstopic},<br>            on_failure=destinations.SnsDestination(<br>                sns.Topic.from_topic_arn(self, &quot;LambdaSNSTopic&quot;, snstopic)<br>            ),<br>        )</pre><h4>Create Layer</h4><pre>        model_layer = lambda_.LayerVersion(<br>            self,<br>            &quot;model-layer&quot;,<br>            code=lambda_.Code.from_asset(&quot;resources/model-layer&quot;),<br>            compatible_runtimes=[lambda_.Runtime.PYTHON_3_9],<br>           <br>        )</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cac648d3c72a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sagemaker Notebook Example using AWS CDK]]></title>
            <link>https://vipmunot.medium.com/sagemaker-notebook-example-using-aws-cdk-9a3d86cbcd65?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a3d86cbcd65</guid>
            <category><![CDATA[amazon-sagemaker]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 16:09:40 GMT</pubDate>
            <atom:updated>2022-08-09T16:09:40.388Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we are going to cover some of the most common properties we use to create and configure an Sagemaker notebook in AWS CDK.</p><p>At the time of writing I was using <strong>CDK version: </strong>2.34.2</p><h4>Importing Dependencies</h4><pre><strong>from</strong> aws_cdk <strong>import</strong> (aws_sagemaker <strong>as</strong> sagemaker,)<br><strong>import</strong> base64<br><strong>import</strong> json</pre><h4>Notebook Instance LifecycleConfig</h4><ul><li>The script needs to be encoded</li><li>Limitation from the CDK — hence need to use CFN</li></ul><pre>with open(<br>                &quot;resources/startup.sh&quot;, &quot;r&quot;<br>            ) as fp:<br>                script = fp.read()<br>            lifecycle_config = sagemaker.CfnNotebookInstanceLifecycleConfig(<br>                self,<br>                &quot;InstanceLifeCycleConfig&quot;,<br>                notebook_instance_lifecycle_config_name=&quot;InstanceLifeCycleConfig&quot;,<br>                on_start=[<br>                    sagemaker.CfnNotebookInstanceLifecycleConfig.NotebookInstanceLifecycleHookProperty(<br>                        content=base64.b64encode(script.encode(&quot;utf-8&quot;)).decode(&quot;utf-8&quot;)<br>                    )<br>                ],<br>            )</pre><h4>Notebook Instance</h4><pre>notebook = sagemaker.CfnNotebookInstance(<br>            self,<br>            &quot;NotebookInstance&quot;,<br>            instance_type=&quot;ml.t3.medium&quot;,<br>                   lifecycle_config_name=lifecycle_config.notebook_instance_lifecycle_config_name,<br>            platform_identifier=&quot;notebook-al2-v1&quot;,<br>            notebook_instance_name=&quot;Notebook-Instance&quot;,<br>            volume_size_in_gb=25,<br>        )</pre><p>In case you are not going to use lifecycle config while creating notebook instance you can comment out that part.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a3d86cbcd65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Resource policy for AWS API Gateway using Cloudformation]]></title>
            <link>https://vipmunot.medium.com/add-resource-policy-for-aws-api-gateway-using-cloudformation-72d7a2cea193?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/72d7a2cea193</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws-cloudformation]]></category>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 14:12:23 GMT</pubDate>
            <atom:updated>2022-03-03T14:12:23.909Z</atom:updated>
            <content:encoded><![CDATA[<p>Following is the example for adding resource policy for AWS API Gateway using Cloudformation</p><pre>AWSTemplateFormatVersion: 2010-09-09</pre><pre>Description: &gt;-</pre><pre>AWS CloudFormation sample template that adds resource policy for AWS API Gateway</pre><pre>Resources:</pre><pre>GreetingsAPI:</pre><pre>Type: AWS::ApiGateway::RestApi</pre><pre>Properties:</pre><pre>Name: greetings-api-internal</pre><pre>Parameters:</pre><pre>endpointConfigurationTypes: REGIONAL</pre><pre>Policy:</pre><pre>Version: &#39;2012-10-17&#39;</pre><pre>Statement:</pre><pre>- Effect: Allow</pre><pre>Principal: &quot;*&quot;</pre><pre>Action: execute-api:Invoke</pre><pre>Resource:</pre><pre>- arn:aws:execute-api:{region}:{aws-account}:{api-id}/*/*/*</pre><pre>Condition:</pre><pre>IpAddress:</pre><pre>aws:SourceIp:</pre><pre>- 10.0.0.1/22</pre><pre>- 13.210.8.0/32</pre><pre>- 0.0.0.0/0</pre><pre>- Effect: Deny</pre><pre>Principal: &quot;*&quot;</pre><pre>Action: execute-api:Invoke</pre><pre>Resource:</pre><pre>- arn:aws:execute-api:{region}:{aws-account}:{api-id}/*/*/*</pre><pre>Condition:</pre><pre>IpAddress:</pre><pre>aws:SourceIp:</pre><pre>- 10.0.0.2/22</pre><pre>- 13.200.8.0/32</pre><p>When you deploy it using Cloudformation console. It will show up in the resource policy of the API as shown below.</p><figure><img alt="resource policy added" src="https://cdn-images-1.medium.com/max/1024/1*rhGg18sw9N3mxAmHvjJllQ.png" /></figure><p><em>Please note: The above cloudformation just creates the API and adds the resource policy, you will need to add the method, responses, deployment, stages, etc to complete the cloudformation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72d7a2cea193" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating producer and consumer using AWS Lambda for AWS MSK Cluster]]></title>
            <link>https://vipmunot.medium.com/creating-msk-producer-and-consumer-using-aws-lambda-f8477c55f78?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8477c55f78</guid>
            <category><![CDATA[msk]]></category>
            <category><![CDATA[aws-msk]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 17:00:54 GMT</pubDate>
            <atom:updated>2022-02-20T17:52:46.131Z</atom:updated>
            <content:encoded><![CDATA[<h3>Use case</h3><p>The official AWS documentation does not provide steps to create producer using Lambda. So this setup provides you detailed information how to do setup producer and consumer for AWS MSK cluster.</p><h3>Steps</h3><p>1. Create a VPC in Account A- 3 private subnet and 1 public subnet</p><p>2. Create Security Group for the VPC with inbound rule of All traffic to 0.0.0.0/0</p><p>3. Create MSK Cluster 2 brokers using 2 private subnet and security group with default MSK configuration and SSL/SCRAM authentication</p><p>4. Create Secret Manager as mentioned in article[1]</p><blockquote>[1] Username and password authentication with AWS Secrets Manager — Setting up SASL/SCRAM authentication for an Amazon MSK Cluster — <a href="https://docs.aws.amazon.com/msk/latest/developerguide/msk-password.html#msk-password-tutorial">https://docs.aws.amazon.com/msk/latest/developerguide/msk-password.html#msk-password-tutorial</a></blockquote><p>5. Create Custom KMS Key using following policy:</p><pre>{</pre><pre>“Id”: “key-consolepolicy-3”,</pre><pre>“Version”: “2012–10–17”,</pre><pre>“Statement”: [</pre><pre>{</pre><pre>“Sid”: “Enable IAM User Permissions”,</pre><pre>“Effect”: “Allow”,</pre><pre>“Principal”: {</pre><pre>“AWS”: “&lt;ACCOUNT_ID&gt;”</pre><pre>},</pre><pre>“Action”: “kms:*”,</pre><pre>“Resource”: “*”</pre><pre>},</pre><pre>{</pre><pre>“Sid”: “Allow access for Key Administrators”,</pre><pre>“Effect”: “Allow”,</pre><pre>“Principal”: {</pre><pre>“AWS”: “arn:aws:iam::ACCOUNT_ID:role/Administrator”</pre><pre>},</pre><pre>“Action”: [</pre><pre>“kms:Create*”,</pre><pre>“kms:Describe*”,</pre><pre>“kms:Enable*”,</pre><pre>“kms:List*”,</pre><pre>“kms:Put*”,</pre><pre>“kms:Update*”,</pre><pre>“kms:Revoke*”,</pre><pre>“kms:Disable*”,</pre><pre>“kms:Get*”,</pre><pre>“kms:Delete*”,</pre><pre>“kms:TagResource”,</pre><pre>“kms:UntagResource”,</pre><pre>“kms:ScheduleKeyDeletion”,</pre><pre>“kms:CancelKeyDeletion”</pre><pre>],</pre><pre>“Resource”: “*”</pre><pre>},</pre><pre>{</pre><pre>“Sid”: “Allow use of the key”,</pre><pre>“Effect”: “Allow”,</pre><pre>“Principal”: {</pre><pre>“AWS”: [</pre><pre>“&lt;Lambda-Consumer ROle&gt;”</pre><pre>]</pre><pre>},</pre><pre>“Action”: [</pre><pre>“kms:Encrypt”,</pre><pre>“kms:Decrypt”,</pre><pre>“kms:ReEncrypt*”,</pre><pre>“kms:GenerateDataKey*”,</pre><pre>“kms:DescribeKey”</pre><pre>],</pre><pre>“Resource”: “*”</pre><pre>},</pre><pre>{</pre><pre>“Sid”: “Allow attachment of persistent resources”,</pre><pre>“Effect”: “Allow”,</pre><pre>“Principal”: {</pre><pre>“AWS”: [</pre><pre>“&lt;Lambda-Consumer ROle&gt;”</pre><pre>]</pre><pre>},</pre><pre>“Action”: [</pre><pre>“kms:CreateGrant”,</pre><pre>“kms:ListGrants”,</pre><pre>“kms:RevokeGrant”</pre><pre>],</pre><pre>“Resource”: “*”,</pre><pre>“Condition”: {</pre><pre>“Bool”: {</pre><pre>“kms:GrantIsForAWSResource”: “true”</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>]</pre><pre>}</pre><p>6. Created Lambda function(kafka-Consumer) with following code:</p><pre>exports.handler = async (event) =&gt; {</pre><pre>// Iterate through keys</pre><pre>for (let key in event.records) {</pre><pre>console.log(‘Key: ‘, key)</pre><pre>// Iterate through records</pre><pre>event.records[key].map((record) =&gt; {</pre><pre>console.log(‘Record: ‘, record)</pre><pre>// Decode base64</pre><pre>const msg = Buffer.from(record.value, ‘base64’).toString()</pre><pre>console.log(‘Message:’, msg)</pre><pre>})</pre><pre>}</pre><pre>}</pre><p>6. Created Lambda function(kafka-Producer) with following code:</p><pre>import json<br>from time import time<br>import boto3<br>import base64<br>from botocore.exceptions import ClientError<br>from kafka import KafkaProducer, KafkaConsumer</pre><pre>secret_name = &quot;&lt;SECRET-MANAGER-ARN&quot;</pre><pre># Create a Secrets Manager client<br>session = boto3.session.Session()<br>client = session.client(service_name=&#39;secretsmanager&#39;,region_name=region_name)<br>get_secret_value_response = client.get_secret_value(SecretId=secret_name)<br>secerts = json.loads(get_secret_value_response[&#39;SecretString&#39;])<br>print(secerts)    <br>KAFKA_BROKER = &#39;&lt;KAFKA-BROKER&gt;:9096,&lt;KAFKA-BROKER&gt;:9096&#39;<br>KAFKA_TOPIC = &#39;MSKTutorialTopic&#39;</pre><pre>def lambda_handler(event, context):<br>    producer = KafkaProducer(bootstrap_servers=KAFKA_BROKER,security_protocol=&#39;SASL_SSL&#39;,sasl_mechanism=&#39;SCRAM-SHA-512&#39;,<br>    sasl_plain_username=secerts[&#39;username&#39;],sasl_plain_password=secerts[&#39;password&#39;],<br>    value_serializer=lambda x: json.dumps(x).encode(&#39;utf-8&#39;))<br>    # producer.send(KAFKA_TOPIC, b&quot;test for hw08-solution02&quot;) <br>    for e in range(5):<br>        data = {&#39;number&#39; : e}<br>        producer.send(KAFKA_TOPIC, data)<br>    producer.flush()</pre><p>7. Added the VPC Config same as MSK Cluster</p><p>8. Add MSK Trigger with SASL_SCRAM_512_AUTH pointing to Secret Manager to lambda function kafka-Consumer.</p><p>9. The Lambda execution role had default policy, arn:aws:iam::aws:policy/SecretsManagerReadWrite, arn:aws:iam::aws:policy/AmazonMSKFullAccess, arn:aws:iam::aws:policy/service-role/AWSLambdaMSKExecutionRole</p><p>Once the setup is complete, test it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8477c55f78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring same Slack channel for more than one AWS chatbot]]></title>
            <link>https://vipmunot.medium.com/configuring-same-slack-channel-for-more-than-one-aws-chatbot-c12e5fa067dd?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12e5fa067dd</guid>
            <category><![CDATA[aws-chatbot]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Thu, 05 Nov 2020 18:07:23 GMT</pubDate>
            <atom:updated>2020-11-05T18:07:23.141Z</atom:updated>
            <content:encoded><![CDATA[<p>You can follow the official documentation for configuring AWS Chatbot with the slack channel using the link <a href="https://docs.aws.amazon.com/chatbot/latest/adminguide/setting-up.html">https://docs.aws.amazon.com/chatbot/latest/adminguide/setting-up.html</a></p><p>You can use following command to choose before running aws commands via slack.</p><pre>@aws set default-account &lt;ACCOUNT_ID_1|ACCOUNT_ID_2&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12e5fa067dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating the AWS CloudWatch logs retention period for all log groups]]></title>
            <link>https://vipmunot.medium.com/automating-the-aws-cloudwatch-logs-retention-period-for-all-log-groups-be47da1970a7?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/be47da1970a7</guid>
            <category><![CDATA[aws-eventbridge]]></category>
            <category><![CDATA[aws-cloudwatch]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 21:18:13 GMT</pubDate>
            <atom:updated>2024-01-04T13:53:19.436Z</atom:updated>
            <content:encoded><![CDATA[<p>CloudWatch logs cost a lot if you keep them forever. You have option of dumping them to S3 for further use. Still it may the case you don’t want to keep logs after certain amount of time. You can achieve it by individually changing the retention period of each log groups.</p><p><strong>Workaround</strong></p><p>You can use EventBrige Rules -&gt; Lambda Setup to automate this process.</p><p><strong>Steps:</strong></p><ol><li>Create a Lambda function with Python Run time. Add the following code in the code editor</li></ol><pre>import json<br>import logging<br><br>import boto3<br><br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br><br>def lambda_handler(event, context):<br>    client = boto3.client(&quot;logs&quot;)<br>    paginator = client.get_paginator(&quot;describe_log_groups&quot;)<br>    response_iterator = paginator.paginate()<br>    for page in response_iterator:<br>        for objects in page[&quot;logGroups&quot;]:<br>            # print(objects)<br>            logs = objects[&quot;logGroupName&quot;]<br>            retentionInDays = (<br>                objects[&quot;retentionInDays&quot;] if &quot;retentionInDays&quot; in objects else &quot;NA&quot;<br>            )<br>            update_status = None<br>            if str(retentionInDays) not in [&quot;3653&quot;]:<br>                response = client.put_retention_policy(<br>                    logGroupName=logs, retentionInDays=3653<br>                )<br>                if response[&quot;ResponseMetadata&quot;][&quot;HTTPStatusCode&quot;] == 200:<br>                    update_status = &quot;Success&quot;<br>                else:<br>                    update_status = &quot;Failed&quot;<br>                logger.info(<br>                    f&quot;log group: {logs} old retention: {retentionInDays} response: {update_status}&quot;<br>                )<br>            else:<br>                logger.info(f&quot;log group: {logs}  retention: {retentionInDays}&quot;)<br>    # TODO implement<br>    return {&quot;statusCode&quot;: 200, &quot;body&quot;: json.dumps(&quot;Hello from Lambda!&quot;)}</pre><p>2. Add arn:aws:iam::aws:policy/CloudWatchFullAccess Policy to your Lambda Execution Role</p><p>3. Add an Event Bridge trigger using AWS Lambda Console with Schedule expression: <strong>cron(0 18 ? * FRI *) </strong>and<strong> </strong>Event bus: <strong>default</strong></p><p>This will trigger lambda every Friday at 6pm.</p><p><strong>Limitations</strong></p><p>The above code is region specific. If you want it to be updating all regions in your account then:</p><ol><li>create a string array of all regions and pass it to <em>boto3.client(‘logs’)</em></li></ol><pre>from boto3.session import Session<br>s = Session()<br>logs_regions = s.get_available_regions(&#39;logs&#39;)</pre><ol><li>Create a loop over the function as well as the string array and pass the region to the boto3 so it will able to update the retention period in all regions</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be47da1970a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Testing using Kubernetes and AWS SQS]]></title>
            <link>https://vipmunot.medium.com/load-testing-using-kubernetes-and-aws-sqs-b1ea8a584d16?source=rss-c298a9db6ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1ea8a584d16</guid>
            <category><![CDATA[kuberntes]]></category>
            <category><![CDATA[aws-sqs]]></category>
            <dc:creator><![CDATA[Vipul Munot]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 03:59:08 GMT</pubDate>
            <atom:updated>2020-04-22T03:59:08.521Z</atom:updated>
            <content:encoded><![CDATA[<p>I wanted to perform a load test of AWS SQS and my application. So, I created a sample python program which will publish a message to SQS and check when the AWS SQS fails.</p><h3><strong>Prerequisites</strong></h3><ul><li>Docker</li><li>Kubernetes</li><li>SQS Queue</li></ul><p><strong>Step 1: Code</strong></p><pre>sqs-script.py</pre><pre>import json</pre><pre>import boto3</pre><pre>import time</pre><pre>num = 1</pre><pre>while (num &lt;= 5):</pre><pre>try:</pre><pre>sqs = boto3.client(&#39;sqs&#39;, region_name=&#39;us-east-1&#39;, aws_access_key_id=&quot;&lt;ACCESS_KEY&gt;&quot;,aws_secret_access_key=&quot;&lt;SECRET_KEY&quot;)</pre><pre>response = sqs.send_message(QueueUrl=&quot;QUEUE_URL&quot;,MessageBody=&quot;Hello&quot;)</pre><pre>print(response)</pre><pre>num = num + 1</pre><pre>except Exception as error:</pre><pre>print (error)</pre><pre>time.sleep(3600)</pre><p><strong>Step 2: Creating requirements.txt</strong></p><pre>requirements.txt</pre><pre>boto3==1.10.5</pre><p><strong>Step 3: Creating Dockerfile</strong></p><pre>FROM python:3</pre><pre>WORKDIR /usr/src/app</pre><pre>COPY requirements.txt ./<br>RUN pip install --no-cache-dir -r requirements.txt</pre><pre>COPY . .</pre><pre>CMD [ &quot;python&quot;, &quot;./sqs-script.py&quot; ]</pre><p><strong>Step 4: Create Docker Image</strong></p><pre>docker build -t my-python-app .</pre><pre>docker run -d -p 5000:5000 --restart=always --name registry registry:2</pre><pre>docker tag my-python-app:latest localhost:5000/my-python-app</pre><pre>docker push localhost:5000/my-python-app</pre><p>The above commands create a local registry and uploads the image to that registry and the Kubernetes yaml file use this image to start the containers. You can use DockerHub, your own repository such as nexus repo, etc. Please make the necessary changes in the yaml file.</p><p><strong>Step 5: Create Kubernetes yaml file</strong></p><pre>apiVersion: apps/v1</pre><pre>kind: Deployment</pre><pre>metadata:</pre><pre>name: my-running-app</pre><pre>namespace: default</pre><pre>spec:</pre><pre>replicas: 50</pre><pre>selector:</pre><pre>matchLabels:</pre><pre>bb: my-running-app</pre><pre>template:</pre><pre>metadata:</pre><pre>labels:</pre><pre>bb: my-running-app</pre><pre>spec:</pre><pre>containers:</pre><pre>- name: my-running-app</pre><pre>image: localhost:5000/my-python-app</pre><pre>imagePullPolicy: IfNotPresent</pre><p><strong>Step 6: Deploy the yaml file</strong></p><pre>kubectl apply -f load-test.yaml</pre><p>This start 50 containers of the application and publish 250 messages to the SQS queue. I have tested it for 50 ,75, 100 containers in my local environment. After that my local environment gave up as all the memory was utilized. If you have development Kubernetes cluster then you can do a load test on larger scale to replicate real life scenarios and mitigate the issues such as throttling, rate exceeded limit, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1ea8a584d16" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>