<?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 Sergio Esteban on Medium]]></title>
        <description><![CDATA[Stories by Sergio Esteban on Medium]]></description>
        <link>https://medium.com/@sergioestebance?source=rss-4f077c6eb02a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6O3q2fDckfqYBx_r057wwg.jpeg</url>
            <title>Stories by Sergio Esteban on Medium</title>
            <link>https://medium.com/@sergioestebance?source=rss-4f077c6eb02a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:12:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergioestebance/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[Launching your RAG system on AWS: Cloudfront, Lambda, Bedrock & S3 Vectors]]></title>
            <link>https://medium.com/warike/launching-your-rag-system-on-aws-aba55bc56641?source=rss-4f077c6eb02a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aba55bc56641</guid>
            <dc:creator><![CDATA[Sergio Esteban]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 13:47:32 GMT</pubDate>
            <atom:updated>2025-11-24T19:41:10.371Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step by step guide with AI SDK, AWS and Terraform</h4><h3>Introduction</h3><p>In this post I revisit the <a href="https://medium.com/warike/launching-your-ai-agent-on-aws-bedrock-lambda-api-gateway-bd0934f3697b">implementation</a> of an AI Agent, this time adding the ability to return responses tied to a specific context.</p><h3>TLDRS</h3><p>All code used in this article is available in the <a href="https://github.com/warike/aws-lambda-cloudfront-stream">repository</a>.</p><h3>Context</h3><p>As usual, I rely on AWS Serverless services to launch the experiment quickly. With the new capabilities AWS is rolling out, the agent will stream responses in real time as they are generated.</p><p>Below is a high level diagram representing the target architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*huLTDL5f3EvDwoFuYzP9tQ.png" /></figure><p>With that lets define a bit the scope that we are going to work on.</p><h3>Scope</h3><p>For this project I will implement a RAG system using serverless services.</p><p>We can outline the following requirements for a low volume of 1000 requests per month.</p><h4>Functional requirements</h4><ul><li>The system should allow sending messages and receiving a response in real time as it is generated.</li><li>The system should restrict access only through the predefined domain.</li><li>The system should respond only when the question is related to the provided content.</li></ul><h4>Non functional requirements</h4><p>As usual we can rely on serverless capabilities, and add a few additional characteristics.</p><ul><li>The system should be highly available.</li><li>The system should scale automatically to handle variable traffic patterns.</li><li>The system should remain secure with domain level access control and encrypted traffic.</li></ul><h3>Out of Scope</h3><p>This article <strong>does not cover data ingestion</strong> for the context that the system will use when answering.</p><p>However, notebooks are available to do so for testing.</p><p><strong>It is also worth mentioning that being possible does not mean this is the ideal way to expose an Agent.</strong></p><p>With that out of the way, let’s move on.</p><h3>Cost breakdown</h3><p>Considering a volume of 1k requests per month, we are running a serverless RAG application with the following components.</p><h4>Bedrock API Calls</h4><p>We will use the most cost effective models, Nova Micro and Titan Embed v2, for language inference and embeddings.</p><ul><li><strong>Nova Micro</strong> input (500K tokens × 0.00035 USD) plus output (500K tokens × 0.0014 USD)</li><li><strong>Titan Embed v2 </strong>(500K tokens × 0.0001 USD) plus vector search operations</li></ul><p>This gives us an approximate total of 1.05 USD per month.</p><h4>AWS Lambda</h4><p>We will configure a function with 512 MB and a 60 second timeout. This results in roughly 0.20 USD per month.</p><h4>CloudFront</h4><p>We will use PriceClass_100 (US and Europe) assuming minimal data transfer and HTTPS requests.</p><p>This results in about 0.085 USD per month.</p><h4>Container Registry</h4><p>For storing the Lambda function image, estimating (max) 1 GB for the Docker image, and handling all traffic within the same region.</p><p>This results in about 0.10 USD per month.</p><h4>Route53</h4><p>We will use a hosted zone regardless of traffic.<br>This results in about 0.50 USD per month.</p><h4>CloudWatch</h4><p>For logging with seven day retention.<br>This results in about 0.01 USD per month.</p><h4>Total estimated cost</h4><p>This brings us to a total of approximately 1.95 USD per month. This aligns with the low requirements we defined for model responses.</p><p>Let’s continue.</p><h3>Implementation</h3><p>First off, Terraform does not currently support S3 Vector resources, so everything must be created using the AWS CLI.</p><h4>S3 Vector</h4><p>First, create the bucket.</p><pre>aws s3vectors create-vector-bucket \\      <br>  --vector-bucket-name &quot;$VECTOR_BUCKET_NAME&quot; \\<br>  --region &quot;$REGION&quot; \\<br>  --profile &quot;$PROFILE&quot;</pre><p>Next, we will create the Index inside the bucket.</p><pre>aws s3vectors create-index \\<br>  --vector-bucket-name &quot;$VECTOR_BUCKET_NAME&quot; \\<br>  --index-name &quot;$VECTOR_BUCKET_NAME&quot; \\<br>  --data-type float32 \\<br>  --dimension 1024 \\<br>  --distance-metric cosine \\<br>  --metadata-configuration nonFilterableMetadataKeys=id,chunk \\<br>  --region &quot;$REGION&quot; \\<br>  --profile &quot;$PROFILE&quot;</pre><p>To continue, we will need the ARN.</p><pre>aws s3vectors list-indexes \\<br>    --vector-bucket-name &quot;$VECTOR_BUCKET_NAME&quot; \\<br>    --region &quot;$REGION&quot; \\<br>    --profile &quot;$PROFILE&quot; \\<br>    --query &quot;Indexes[?IndexName==&#39;$INDEX_NAME&#39;].IndexArn&quot; \\<br>    --output text 2&gt;/dev/null || echo &quot;Unable to retrieve ARN&quot;</pre><p>With these resources in place we can move forward using Terraform.</p><h4>Lambda creation</h4><p>To support streamed responses we need to use streamText together with @types/aws-lambda.</p><p>The following is the final result.</p><pre>import { pipeline } from &#39;node:stream/promises&#39;;<br>import { config } from &quot;./bedrock/config&quot;;<br>import { streamText } from &#39;ai&#39;;<br>import { bedrock } from &#39;./bedrock/model&#39;;<br>import { findRelevantContent } from &#39;./bedrock/query-vector&#39;;<br>import type { APIGatewayProxyEventV2 } from &#39;aws-lambda&#39;;<br>exports.handler = awslambda.streamifyResponse&lt;APIGatewayProxyEventV2&gt;(<br>    async (event, responseStream, _context) =&gt; {<br>        try {<br>            responseStream.setContentType(&#39;text/plain; charset=utf-8&#39;);<br>            let prompt = &#39;&#39;;<br>            if (event.body) {<br>                try {<br>                    const body = JSON.parse(event.body);<br>                    if (body.prompt) prompt = body.prompt;<br>                } catch (e) {<br>                    console.warn(&#39;Failed to parse request body:&#39;, e);<br>                }<br>            }<br>            if (!prompt) {<br>                responseStream.write(&#39;Error: No prompt provided&#39;);<br>                responseStream.end();<br>                return;<br>            }<br>            const { modelId } = config({});<br>            const similarDocuments = await findRelevantContent(prompt);<br>            const context = similarDocuments.map(doc =&gt; doc.chunk).join(&#39;\\n\\n&#39;);<br>            const systemPrompt = `You are a helpful assistant. Answer the user&#39;s question using ONLY the context provided below. <br>            If the answer is not in the context, say &quot;I don&#39;t know&quot; or &quot;The provided context does not contain the answer.&quot;<br>            Do not hallucinate or use outside knowledge.<br>            Context:<br>            ${context}`;<br>            const result = await streamText({<br>                model: bedrock(modelId),<br>                system: systemPrompt,<br>                messages: [<br>                    { role: &quot;user&quot;, content: prompt },<br>                ],<br>            });<br>            await pipeline(result.textStream, responseStream);<br>            return;<br>        } catch (error) {<br>            console.error(&quot;Error in handler:&quot;, error);<br>            responseStream.write(&#39;Error&#39;);<br>            responseStream.end();<br>        }<br>    }<br>);</pre><p>With the general logic ready, we can move on to implementing semantic search inside our Vector Index.</p><h4>Semantic search using Vector S3</h4><p>We need to take the user message and generate embeddings using the amazon.titan-embed-text-v2:0 model.</p><p>Once we get the model response, we parse the result according to our needs. In this case we know each chunk contains the raw text we will use to look for relevant content.</p><p>With this simple flow we return additional context to the model so it can produce a response.</p><pre>import { embed } from &quot;ai&quot;;<br>import { bedrock } from &quot;./model&quot;;<br>import { env } from &quot;../env&quot;;<br>import { QueryVectorsCommand, S3VectorsClient } from &#39;@aws-sdk/client-s3vectors&#39;<br>import { config } from &quot;./config&quot;;<br><br>export interface VectorMetadata {<br>    id: string<br>    chunk: string<br>}<br>const s3Vectors = new S3VectorsClient({})<br>export const findRelevantContent = async (query: string) =&gt; {<br>    const text = query.replaceAll(&#39;\\\\n&#39;, &#39; &#39;);<br>    const { modelId } = config({ modelId: &#39;amazon.titan-embed-text-v2:0&#39; })<br>    const { embedding: userQueryEmbedded } = await embed({<br>        model: bedrock.textEmbeddingModel(modelId),<br>        value: text,<br>        providerOptions: {<br>            bedrock: {<br>                normalize: true<br>            }<br>        },<br>    });<br>    const input = {<br>        indexArn: env.AWS_VECTOR_BUCKET_INDEX_ARN!,<br>        queryVector: {<br>            float32: userQueryEmbedded,<br>        },<br>        topK: 5,<br>        returnMetadata: true,<br>        returnDistance: true,<br>    }<br>    const result = await s3Vectors.send(new QueryVectorsCommand(input));<br>    if (!result.vectors || result.vectors.length === 0) {<br>        console.log(&#39;No vectors found for the query&#39;)<br>        return []<br>    }<br>    return result.vectors.map(v =&gt; {<br>        const metadata = v.metadata as VectorMetadata | undefined<br>        if (!metadata) {<br>            throw new Error(&#39;Metadata is required in the vector response&#39;)<br>        }<br>        if (!metadata.id || !metadata.chunk) {<br>            throw new Error(&#39;Vector metadata must contain id and chunk fields&#39;)<br>        }<br>        return {<br>            id: metadata.id,<br>            chunk: metadata.chunk,<br>            key: v.key,<br>            distance: v.distance,<br>        }<br>    })<br>}</pre><p>It is important to note that the retrieved results do not always represent the right context. To get higher quality responses we need to spend more time preparing the data we process.</p><h3>Docker</h3><p>To package our solution we define the Lambda.</p><pre># ---- Build Stage ----<br>FROM public.ecr.aws/lambda/nodejs:22 AS builder<br>WORKDIR /usr/src/app<br>RUN corepack enable<br>COPY package.json pnpm-lock.yaml* ./<br>RUN pnpm install --frozen-lockfile<br>COPY . .<br>RUN pnpm run build<br># ---- Runtime Stage ----<br>FROM public.ecr.aws/lambda/nodejs:22<br>WORKDIR ${LAMBDA_TASK_ROOT}<br>COPY --from=builder /usr/src/app/dist/ ./<br>COPY --from=builder /usr/src/app/node_modules ./node_modules<br>ENTRYPOINT [ &quot;/lambda-entrypoint.sh&quot;, &quot;index.handler&quot; ]</pre><h3>Infrastructure</h3><p>With this in place we can move on to creating the cloud resources.</p><h4>Container registry</h4><p>We need a centralized location to host our Docker images.</p><pre>resource &quot;aws_ecr_repository&quot; &quot;warike_development_ecr&quot; {<br>  name                 = &quot;ecr-${local.project_name}&quot;<br>  image_tag_mutability = &quot;IMMUTABLE_WITH_EXCLUSION&quot;<br>  encryption_configuration {<br>    encryption_type = &quot;AES256&quot;<br>  }<br>  image_scanning_configuration {<br>    scan_on_push = true<br>  }<br>  image_tag_mutability_exclusion_filter {<br>    filter      = &quot;*latest&quot;<br>    filter_type = &quot;WILDCARD&quot;<br>  }<br>  force_delete = true<br>}</pre><h4>Lambda module</h4><p>For deploying our Lambda function using Docker we need to set the invocation mode to RESPONSE_STREAM, enable create_lambda_function_url, and use AWS_IAM as the authorization type.</p><pre>locals {<br>  lambda_chat = {<br>    name        = &quot;chat-${basename(path.cwd)}&quot;<br>    image       = &quot;${aws_ecr_repository.warike_development_ecr.repository_url}:chat-latest&quot;<br>    description = &quot;Lambda chat function for ${local.project_name}&quot;<br>    memory_size = 512<br>    timeout     = 60<br>    env_vars = {<br>      AWS_BEARER_TOKEN_BEDROCK    = var.aws_bearer_token_bedrock<br>      AWS_BEDROCK_MODEL           = var.aws_bedrock_model<br>      AWS_VECTOR_BUCKET_INDEX_ARN = var.vector_bucket_index_arn<br>      AWS_BEDROCK_MODEL_EMBEDDING = var.aws_bedrock_model_embedding<br>    }<br>  }<br>}<br>## Lambda Chat<br>module &quot;warike_development_lambda_chat&quot; {<br>  source  = &quot;terraform-aws-modules/lambda/aws&quot;<br>  version = &quot;~&gt; 8.1.2&quot;<br>  ## Configuration<br>  function_name = local.lambda_chat.name<br>  description   = local.lambda_chat.description<br>  memory_size   = local.lambda_chat.memory_size<br>  timeout       = local.lambda_chat.timeout<br>  ## Package<br>  create_package = false<br>  package_type   = &quot;Image&quot;<br>  image_uri      = local.lambda_chat.image<br>  environment_variables = merge(<br>    local.lambda_chat.env_vars,<br>    {}<br>  )<br>  ## API Gateway<br>  create_current_version_allowed_triggers = false<br>  ## Permissions<br>  create_role = false<br>  lambda_role = aws_iam_role.warike_development_lambda_chat_role.arn<br>  ## Logging<br>  use_existing_cloudwatch_log_group = true<br>  logging_log_group                 = aws_cloudwatch_log_group.warike_development_lambda_chat_logs.name<br>  logging_log_format                = &quot;JSON&quot;<br>  logging_application_log_level     = &quot;INFO&quot;<br>  logging_system_log_level          = &quot;WARN&quot;<br>  ## Response Streaming<br>  invoke_mode = &quot;RESPONSE_STREAM&quot;<br>  ## Lambda Function URL<br>  create_lambda_function_url = true<br>  authorization_type         = &quot;AWS_IAM&quot;<br>  cors = {<br>    allow_credentials = true<br>    allow_origins     = [&quot;*&quot;]<br>    allow_methods     = [&quot;*&quot;]<br>    allow_headers     = [&quot;*&quot;]<br>    expose_headers    = [&quot;*&quot;]<br>    max_age           = 86400<br>  }<br>  tags = merge(local.tags, { Name = local.lambda_chat.name })<br>  depends_on = [<br>    aws_cloudwatch_log_group.warike_development_lambda_chat_logs,<br>    aws_ecr_repository.warike_development_ecr,<br>    null_resource.warike_development_build_image_seed<br>  ]<br>}</pre><p><em>Unlike my previous article, this version will stream responses as they are generated.</em></p><h4>ACM and Route 53</h4><p>Next, to access our Lambda function through CloudFront, we define the DNS records and a certificate.</p><pre>## Amazon Certificate Manager<br>module &quot;warike_development_acm&quot; {<br>  source  = &quot;terraform-aws-modules/acm/aws&quot;<br>  version = &quot;~&gt; 6.1.0&quot;<br>domain_name               = local.domain_name<br>  zone_id                   = data.aws_route53_zone.warike_development_warike_tech.id<br>  subject_alternative_names = [&quot;*.${local.domain_name}&quot;]<br>  validation_method = &quot;DNS&quot;<br>  tags = local.tags<br>}<br>## Route 53 - Hosted Zone<br>data &quot;aws_route53_zone&quot; &quot;warike_development_warike_tech&quot; {<br>  name = local.domain_name<br>}<br>## Route 53 - Apex Record<br>resource &quot;aws_route53_record&quot; &quot;warike_development_apex_record&quot; {<br>  zone_id = data.aws_route53_zone.warike_development_warike_tech.zone_id<br>  name    = local.domain_name<br>  type    = &quot;A&quot;<br>  alias {<br>    name                   = module.warike_development_cloudfront.cloudfront_distribution_domain_name<br>    zone_id                = module.warike_development_cloudfront.cloudfront_distribution_hosted_zone_id<br>    evaluate_target_health = false<br>  }<br>  depends_on = [<br>    module.warike_development_cloudfront,<br>  ]<br>}</pre><p>With everything above in place we can start configuring CloudFront.</p><h4>CloudFront</h4><p>For CloudFront we need to consider that an Origin Access Control will be created.</p><p>We will reference lambda_function_url from it.</p><pre>module &quot;warike_development_cloudfront&quot; {<br>  source  = &quot;terraform-aws-modules/cloudfront/aws&quot;<br>  version = &quot;~&gt; 5.0.1&quot;<br>## Configuration<br>  enabled                        = true<br>  price_class                    = &quot;PriceClass_100&quot;<br>  retain_on_delete               = false<br>  wait_for_deployment            = true<br>  is_ipv6_enabled                = true<br>  create_monitoring_subscription = true<br>  ## Extra CNAMEs<br>  aliases = [&quot;${local.domain_name}&quot;]<br>  comment = &quot;Chat CloudFront Distribution&quot;<br>  ## Origin access control<br>  create_origin_access_control = true<br>  origin_access_control = {<br>    &quot;chat_lambda_function_url&quot; = {<br>      description      = &quot;CloudFront access to Lambda Function URL&quot;<br>      origin_type      = &quot;lambda&quot;<br>      signing_behavior = &quot;always&quot;<br>      signing_protocol = &quot;sigv4&quot;<br>    }<br>  }<br>  origin = {<br>    &quot;chat_lambda_function_url&quot; = {<br>      domain_name           = trimsuffix(replace(module.warike_development_lambda_chat.lambda_function_url, &quot;https://&quot;, &quot;&quot;), &quot;/&quot;)<br>      origin_access_control = local.cloudfront_oac_lambda_function_url<br>      custom_origin_config = {<br>        http_port              = 80<br>        https_port             = 443<br>        origin_protocol_policy = &quot;match-viewer&quot;<br>        origin_ssl_protocols   = [&quot;TLSv1&quot;, &quot;TLSv1.1&quot;, &quot;TLSv1.2&quot;]<br>      }<br>    }<br>  }<br>  default_cache_behavior = {<br>    target_origin_id       = local.cloudfront_oac_lambda_function_url<br>    viewer_protocol_policy = &quot;redirect-to-https&quot;<br>    allowed_methods        = [&quot;HEAD&quot;, &quot;DELETE&quot;, &quot;POST&quot;, &quot;GET&quot;, &quot;OPTIONS&quot;, &quot;PUT&quot;, &quot;PATCH&quot;]<br>    cached_methods         = [&quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;]<br>    ## Cache policy disabled<br>    cache_policy_id = &quot;4135ea2d-6df8-44a3-9df3-4b5a84be39ad&quot;<br>    ## Forwarded values disabled<br>    use_forwarded_values = false<br>    ## TTL settings<br>    min_ttl     = 0<br>    default_ttl = 0<br>    max_ttl     = 0<br>    compress    = true<br>    function_association = {<br>      viewer-request = {<br>        function_arn = aws_cloudfront_function.warike_development_restrict_domain.arn<br>      }<br>    }<br>  }<br>  viewer_certificate = {<br>    acm_certificate_arn = module.warike_development_acm.acm_certificate_arn<br>    ssl_support_method  = &quot;sni-only&quot;<br>  }<br>  tags = merge(local.tags, { Name = local.cloudfront_oac_lambda_function_url })<br>  depends_on = [<br>    module.warike_development_acm,<br>    module.warike_development_lambda_chat,<br>  ]<br>}<br>resource &quot;aws_cloudfront_function&quot; &quot;warike_development_restrict_domain&quot; {<br>  name    = &quot;restrict-domain-${local.project_name}&quot;<br>  runtime = &quot;cloudfront-js-1.0&quot;<br>  comment = &quot;Restrict access to custom domain only&quot;<br>  publish = true<br>  code    = file(&quot;${path.module}/functions/auth.js&quot;)<br>}</pre><h4>CloudFront function</h4><p>Additionally, I added a lightweight CloudFront function to ensure requests are directed to the predefined domain.</p><pre>function handler(event) {<br>    var request = event.request;<br>    var host = request.headers.host.value;<br>    var allowedDomain = &#39;dev.zaistev.com&#39;;<br>    if (host !== allowedDomain) {<br>        return {<br>            statusCode: 403,<br>            statusDescription: &#39;Forbidden&#39;,<br>            headers: {<br>                &quot;content-type&quot;: { &quot;value&quot;: &quot;text/plain&quot; }<br>            },<br>            body: { &quot;encoding&quot;: &quot;text&quot;, &quot;value&quot;: &quot;Access denied. Please use the custom domain.&quot; }<br>        };<br>    }<br>    return request;<br>}</pre><p>With the main resources in place we can move on to the actual cloud deployment.</p><h4>Deployment</h4><p>I created a set of functions that automate the deployment.</p><pre>.PHONY: deploy compile-server push-image terraform-apply<br># Extract current version from terraform file (e.g., chat-v1)<br>CURRENT_VERSION := $(shell grep -o &#39;chat-v[0-9]*&#39; infra/lambda-chat.tf | head -n 1)<br># Extract the number part (e.g., 1)<br>VERSION_NUM := $(shell echo $(CURRENT_VERSION) | sed &#39;s/chat-v//&#39;)<br># Increment the number<br>NEXT_VERSION_NUM := $(shell echo $$(($(VERSION_NUM) + 1)))<br># Form the new version string (e.g., chat-v2)<br>NEXT_VERSION := chat-v$(NEXT_VERSION_NUM)<br>deploy: compile-server push-image terraform-apply test<br>compile-server:<br> @echo &quot;Compiling server app...&quot;<br> cd apps/server &amp;&amp; pnpm install &amp;&amp; pnpm run build<br>push-image:<br> @echo &quot;Current version: $(CURRENT_VERSION)&quot;<br> @echo &quot;Next version: $(NEXT_VERSION)&quot;<br> @echo &quot;Building and pushing Docker image...&quot;<br> ./infra/push_chat_image.sh $(NEXT_VERSION)<br> @echo &quot;Updating Terraform configuration...&quot;<br> # Update the version in the terraform file<br> sed -i &#39;&#39; &#39;s/$(CURRENT_VERSION)/$(NEXT_VERSION)/g&#39; infra/lambda-chat.tf<br>terraform-apply:<br> @echo &quot;Applying Terraform changes...&quot;<br> cd infra &amp;&amp; terraform apply -auto-approve<br>test:<br> @echo &quot;Running integration tests...&quot;<br> ./infra/test_stream.sh</pre><p>Therefore, to get it running we need to execute</p><pre>make deploy</pre><h3>Testing</h3><p>Additionally, we don’t have any context data available. This can be addressed by manually inserting data using Python.</p><pre>def insert_vector(text, bucket_name, index_name):<br>    &quot;&quot;&quot;<br>    Insert a single text chunk into the S3 Vector Index.<br>    &quot;&quot;&quot;<br>    if not s3_vectors_client:<br>        print(&quot;❌ S3 Vectors client is not initialized.&quot;)<br>        return False<br>    <br>    if not bucket_name or not index_name:<br>        print(&quot;⚠️ S3_VECTOR_BUCKET_NAME or S3_VECTOR_INDEX_NAME is not set.&quot;)<br>        return False<br>    <br>    # Generate unique ID<br>    unique_id = generate_nanoid()<br>    <br>    # Generate embedding<br>    embedding = get_embedding(text)<br>    if not embedding:<br>        print(f&quot;❌ Failed to generate embedding for text: {text[:50]}...&quot;)<br>        return False<br>    <br>    # Create metadata<br>    metadata = {<br>        &quot;id&quot;: unique_id,<br>        &quot;chunk&quot;: text<br>    }<br>    <br>    try:<br>        # Insert vector into S3 Vector Index<br>        response = s3_vectors_client.put_vectors(<br>            vectorBucketName=bucket_name,<br>            indexName=index_name,<br>            vectors=[<br>                {<br>                    &quot;key&quot;: unique_id,<br>                    &quot;data&quot;: {&quot;float32&quot;: embedding},<br>                    &quot;metadata&quot;: metadata<br>                }<br>            ]<br>        )<br>        <br>        print(f&quot;✅ Inserted vector with ID: {unique_id}&quot;)<br>        print(f&quot;   Text preview: {text[:80]}...&quot;)<br>        return True<br>        <br>    except Exception as e:<br>        print(f&quot;❌ Error inserting vector: {e}&quot;)<br>        return False<br>    # Insert all predefined texts<br>    print(&quot;\\n🚀 Starting vector insertion...\\n&quot;)<br>    success_count = 0<br>    fail_count = 0<br>    for i, text in enumerate(predefined_texts, 1):<br>        print(f&quot;\\n[{i}/{len(predefined_texts)}] Processing...&quot;)<br>        if insert_vector(text, s3_vector_bucket_name, s3_vector_index_name):<br>            success_count += 1<br>        else:<br>            fail_count += 1<br>    print(f&quot;\\n\\n📊 Insertion Summary:&quot;)<br>    print(f&quot;   ✅ Successful: {success_count}&quot;)<br>    print(f&quot;   ❌ Failed: {fail_count}&quot;)<br>    print(f&quot;   📝 Total: {len(predefined_texts)}&quot;)</pre><p>Later, if we test with available context, we can get a result like the following.</p><pre>🔍 Testing with query: &#39;Explain how EventBridge works in LLM Workflow context?&#39;<br>✅ Found 3 similar vectors:<br>1. ID: HlgHN84M1CUmWH3q5tzHl<br>   Distance: 0.4293<br>   Text: An application emits an event (for example, {&quot;type&quot;: &quot;orderCreated&quot;, &quot;priority&quot;: &quot;high&quot;}). Amazon EventBridge evaluates the event against its routing rules. Based on an event&#39;s attributes, the system dynamically dispatches to the following: HighPriorityOrderProcessor (service A), StandardOrderProcessor (service B), UpdateOrderProcessor (service C). This pattern supports loose coupling, domain-based specialization, and runtime extensibility. This allows systems to respond intelligently to changing requirements and event semantics.<br>2. ID: Pv2Y1r0zYKxdFRrToZ0fo<br>   Distance: 0.5672<br>   Text: LLM-based routing: In agentic systems, routing also performs dynamic task delegation - but instead of Amazon EventBridge rules or metadata filters, the LLM classifies and interprets the user&#39;s intent through natural language. The result is a flexible, semantic, and adaptive form of dispatching.<br>3. ID: Cp98hjhcis6SSNooIuhZ8<br>   Distance: 0.6386<br>   Text: Agent router workflow: A user submits a natural language request through an SDK. An Amazon Bedrock agent uses an LLM to classify the task (for example, legal, technical, or scheduling). The agent dynamically routes the task through an action group to invoke the required agent: Domain-specific agent, Specialized tool chain, Custom prompt configuration. The selected handler processes the task and returns a tailored response.</pre><h3>Conclusions</h3><p>Building this context-aware Agent proves that serverless RAG is both practical and cost-efficient. By pairing the AI SDK with AWS Lambda, we achieved real-time streaming without the operational overhead of complex implementation, and yes, I mean WebSockets on Lambda.</p><p>We had to rely on the AWS CLI for S3 Vectors since native Terraform support is currently missing. While this adds a manual step, it effectively removes the need for a dedicated and expensive vector database.</p><p>Ultimately, this architecture provides a secure and scalable starting point. With CloudFront and Docker in place, you have a system that keeps costs remarkably low.</p><h4>References</h4><ul><li><a href="https://aws.plainenglish.io/uploading-documents-to-s3-vector-buckets-f418594feca3">https://aws.plainenglish.io/uploading-documents-to-s3-vector-buckets-f418594feca3</a></li><li><a href="https://dev.to/aws-builders/ai-sdk-streaming-text-from-lambda-cfd">https://dev.to/aws-builders/ai-sdk-streaming-text-from-lambda-cfd</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-response-streaming.html">https://docs.aws.amazon.com/lambda/latest/dg/configuration-response-streaming.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aba55bc56641" width="1" height="1" alt=""><hr><p><a href="https://medium.com/warike/launching-your-rag-system-on-aws-aba55bc56641">Launching your RAG system on AWS: Cloudfront, Lambda, Bedrock &amp; S3 Vectors</a> was originally published in <a href="https://medium.com/warike">Warike technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Launching Your AI Agent on AWS: Bedrock, Lambda & API Gateway]]></title>
            <link>https://medium.com/warike/launching-your-ai-agent-on-aws-bedrock-lambda-api-gateway-bd0934f3697b?source=rss-4f077c6eb02a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd0934f3697b</guid>
            <dc:creator><![CDATA[Sergio Esteban]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 09:33:20 GMT</pubDate>
            <atom:updated>2025-11-06T09:33:20.278Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implement a low-cost, serverless agent on AWS to validate cost savings quickly using Terraform and Typescript with AI SDK.</h4><h3>Introduction</h3><p>In this post, I’m going to explore the implementation of a service that allows us to send a questions and receive an answer back. Sending a question would be handle as a <strong>prompt to a specific model using Bedrock.</strong></p><p>To minimize the costs of this implementation, I’ll be utilizing the services of <strong>API Gateway</strong>, <strong>AWS Lambda</strong>, and <strong>Amazon Bedrock</strong>.</p><h3>Context</h3><p>When we want to implement a Generative AI service, there are several possible paths, and we must take the time to understand the minimal requirements before making a decision.</p><p>In this post, I will demonstrate the process of deploying a simple GenAI solution that we can either connect to our current solution or expose to a third party via API Gateway.</p><h3>TLDRS</h3><p>All the content for this implementation can be found in this <a href="https://github.com/warike/showcase/tree/main/projects/11-aws-lambda-apigw-bedrock"><strong>repository</strong></a>.</p><h3>Scope</h3><p>For this implementation, I’m going to define a set of quite <strong>simple requirements</strong>.</p><p>Below is a diagram that represents the implementation we will be building.</p><figure><img alt="High level Diagram of the target AWS Architecture" src="https://cdn-images-1.medium.com/max/1024/1*m9HqeMgvKVRW702fA7O0MQ.png" /></figure><h3>Functional Requirements</h3><ul><li>We should be able to send a prompt and receive a response in the form of model completion from Nova Micro.</li><li>We should be able to expose an HTTP endpoint to trigger the process of generating a response.</li><li>Let’s estimate, for the sake of cost calculations, that we will serve a monthly volume of 100 requests.</li></ul><h3>Non-Functional Requirements</h3><p>Since we’re using AWS serverless services, we can lean on their built in features for our non-functional requirements.</p><p>For automation, the deployment should be handled completely by GitHub Actions. When it comes to availability, the API needs to maintain a monthly uptime of 99.9% or higher.</p><p>On the security front, we’ll need IAM-scoped access for Bedrock, use OpenID Connect for authentication, and ensure all traffic is HTTPS only.</p><p>And finally, for observability, we must have structured logs that capture metadata, token usage, and any errors, all visualized with CloudWatch dashboards.</p><p>Simple.</p><h3>What is Out of Scope?</h3><p>For this implementation, I will be excluding <strong>authentication</strong>, <strong>sanitization</strong>, <strong>authorization</strong> and any <strong>security processes</strong> applied to the requests. This approach allows me to focus on the general GenAI implementation process.</p><h3>Cost Breakdown per service</h3><p>Given the predefined volume, we can estimate an average usage per request of <strong>22 input tokens</strong> and <strong>232 output tokens</strong>.</p><p><strong>Amazon Bedrock (Nova Micro)</strong></p><p>The Nova Micro model is processing <strong>2,200 input tokens</strong> and <strong>23,200 output tokens</strong> monthly. This runs about <strong>$0.003/month</strong>. Output tokens cost more than input about x 4 times.</p><p><strong>AWS Lambda</strong></p><p>Considering only <strong>100 invocations</strong> and maybe <strong>3 to 5 seconds per call</strong> with <strong>512MB memory</strong>, we are nowhere near the <strong>Free Tier</strong> limits. Lambda gives us <strong>1 million requests</strong> and <strong>400,000 GB-seconds</strong> free every month.</p><p><strong>API Gateway</strong></p><p>For the first year, we get <strong>1 million requests free</strong>. After that, we are looking at maybe <strong>$0.0004/month</strong>.</p><p><strong>Amazon ECR</strong></p><p>That <strong>300MB Docker image</strong> sitting in ECR costs about <strong>a cent a month</strong>. After the <strong>500MB Free Tier</strong>, we are paying for around 136MB of storage.</p><h3>What Happens When It Scales?</h3><p>If it reaches <strong>1,000 requests monthly</strong>, costs are around <strong>$0.04</strong>. At <strong>10K requests</strong>, it’s about <strong>$0.39</strong>. Even at <strong>100K requests</strong>, we are only paying about <strong>$3.76/month</strong>.</p><p>Alrighty, let’s move ahead.</p><h3>Implementation</h3><p>To begin the implementation, we can start by creating the agent.</p><h3>Creating the Agent</h3><p>To create the agent, I first need to set up the complete <strong>TypeScript project</strong>.</p><p>We can move quickly by following these instructions and installing the necessary dependencies so the project can operate correctly.</p><p>Feel free to use the configuration that suits you best.</p><pre>mkdir -p handler terraform <br>cd handler<br>pnpm init -y<br>pnpm --package=typescript dlx tsc --init<br>mkdir -p src __tests__<br>touch src/{app,env,index}.ts <br>pnpm add -D @types/node tsx typescript<br>pnpm add ai @ai-sdk/amazon-bedrock<br>pnpm add zod dotenv</pre><p>In this project, I will define <strong>three fundamental parts</strong>:</p><ol><li><strong>Logic for compatibility</strong> with AWS Lambda.</li><li><strong>Logic to manage requests as prompts</strong>, solicit the text generation based on these, and handle their potential future evolution.</li><li><strong>Core logic for the actual text generation</strong> using the <strong>@ai-sdk</strong> and Bedrock invocations.</li></ol><p>Below is a summary of the project’s main files.</p><pre>import { main } from &quot;./app&quot;;<br><br>export const handler = async (event: any, context: any) =&gt; {<br>    try {<br>        const body = event.body ? JSON.parse(event.body) : {};<br>        const prompt = body.prompt ?? &quot;Welcome from Warike technologies - GenAI solutions architecture&quot;;<br>        const response = await main(prompt);<br>        return {<br>            statusCode: 200,<br>            body: JSON.stringify({<br>                success: true,<br>                data: response,<br>            }),<br>        };<br>    } catch (error) {<br>        console.error(&#39;Error in Lambda handler:&#39;, error);<br>        return {<br>            statusCode: 500,<br>            body: JSON.stringify({<br>                success: false,<br>                error: error instanceof Error ? error.message : &#39;An unexpected error occurred&#39;<br>            }),<br>        };<br>    }<br>};<br><br>// app.ts<br>import { generateResponse } from &quot;./utils/bedrock&quot;;<br>export async function main(prompt: string) {<br>    try {<br>        console.log(&#39;🚀 Starting Bedrock:&#39;);<br>        return await generateResponse(prompt)<br>    } catch (error) {<br>        console.error(&#39;An unexpected error occurred running workflow:&#39;, error);<br>        throw error;<br>    }<br>    <br>}<br><br>// utils/bedrock.ts<br>import { config } from &quot;./config&quot;;<br>import { createAmazonBedrock } from &#39;@ai-sdk/amazon-bedrock&#39;;<br>import { generateText } from &#39;ai&#39;;<br><br>export async function generateResponse(prompt: string){<br>  const { regionId, modelId } = config({ });<br>  try {<br>    const bedrock = createAmazonBedrock({ <br>        region: regionId<br>    });<br>    const { text, usage } = await generateText({<br>        model: bedrock(modelId),<br>        system: &quot;You are a helpful assistant.&quot;,<br>        prompt: [<br>          { role: &quot;user&quot;, content: prompt },<br>        ],<br>        });  <br>    console.log(`model: ${modelId}, \\n response: ${text}, usage: ${JSON.stringify(usage)}`);<br>    return text;<br>    <br>  } catch (error) {<br>    console.log(`ERROR: Can&#39;t invoke &#39;${modelId}&#39;. Reason: ${error}`);<br>  }<br>}</pre><p>For local testing, I’ve defined the following environment variables. We can use an AWS Bedrock API key for testing purposes.</p><pre>AWS_REGION=us-west-2<br>AWS_BEDROCK_MODEL=&#39;amazon.nova-micro-v1:0&#39;<br>AWS_BEARER_TOKEN_BEDROCK=&#39;aws_bearer_token_bedrock&#39;</pre><p>It’s highly recommended to only use <strong>Short-term API keys</strong> to avoid compromising the system’s security.</p><h3>Defining the Infrastructure</h3><p>Now that the system’s logic is functional, we can create its Dockerfile, which will facilitate its deployment to AWS Lambda.</p><pre># ---- Build Stage ----<br>FROM node:22-alpine AS builder<br>WORKDIR /usr/src/app<br>RUN corepack enable<br>COPY package.json pnpm-lock.yaml* ./<br>RUN pnpm install --frozen-lockfile<br>COPY . .<br>RUN pnpm run build<br># ---- Runtime Stage ----<br>FROM public.ecr.aws/lambda/nodejs:22<br>WORKDIR ${LAMBDA_TASK_ROOT}<br>COPY --from=builder /usr/src/app/dist/src ./ <br>COPY --from=builder /usr/src/app/node_modules ./node_modules<br>CMD [ &quot;index.handler&quot; ]</pre><p>With all components ready in our handler, we can proceed to define the resources in Terraform.</p><h3>Exposing the Service with API Gateway</h3><p>We’ll start by defining our API Gateway. We’ll use the HTTP protocol and focus solely on creating the API, its stage, and its subsequent integration with Lambda.</p><pre>locals {<br>  api_gateway_name = &quot;dev-http-${local.project_name}&quot;<br>}<br>module &quot;warike_development_api_gw&quot; {<br>  source  = &quot;terraform-aws-modules/apigateway-v2/aws&quot;<br>  version = &quot;5.4.1&quot;<br>  name          = local.api_gateway_name<br>  description   = &quot;API Gateway for ${local.project_name}&quot;<br>  protocol_type = &quot;HTTP&quot;<br>  create_domain_name    = false<br>  create_certificate    = false<br>  create_domain_records = false<br>  cors_configuration = {<br>    allow_headers = [&quot;*&quot;]<br>    allow_methods = [&quot;*&quot;]<br>    allow_origins = [&quot;*&quot;]<br>  }<br>  # Access logs<br>  stage_name        = &quot;dev&quot;<br>  stage_description = &quot;Development API Gateway&quot;<br>  <br>  <br>  stage_access_log_settings = {<br>    create_log_group = false<br>    destination_arn = aws_cloudwatch_log_group.warike_development_api_gw_logs.arn<br>    format = jsonencode({<br>      context = {<br>        requestId               = &quot;$context.requestId&quot;<br>        requestTime             = &quot;$context.requestTime&quot;<br>        protocol                = &quot;$context.protocol&quot;<br>        httpMethod              = &quot;$context.httpMethod&quot;<br>        resourcePath            = &quot;$context.resourcePath&quot;<br>        routeKey                = &quot;$context.routeKey&quot;<br>        status                  = &quot;$context.status&quot;<br>        responseLength          = &quot;$context.responseLength&quot;<br>        integrationErrorMessage = &quot;$context.integrationErrorMessage&quot;<br>        error = {<br>          message      = &quot;$context.error.message&quot;<br>          responseType = &quot;$context.error.responseType&quot;<br>        }<br>        identity = {<br>          sourceIP = &quot;$context.identity.sourceIp&quot;<br>        }<br>        integration = {<br>          error             = &quot;$context.integration.error&quot;<br>          integrationStatus = &quot;$context.integration.integrationStatus&quot;<br>        }<br>      }<br>    })<br>  }<br>  # Routes &amp; Integration<br>  routes = {<br>    &quot;POST /&quot; = {<br>      integration = {<br>        uri                    = module.warike_development_lambda.lambda_function_arn<br>        payload_format_version = &quot;2.0&quot;<br>      }<br>    }<br>  }<br>  stage_tags = merge(local.tags, {<br>    Name = &quot;${local.api_gateway_name}-dev&quot;<br>  })<br>  tags = merge(local.tags, {<br>    Name = local.api_gateway_name<br>  })<br>  depends_on = [<br>    aws_cloudwatch_log_group.warike_development_api_gw_logs,<br>  ]<br>}<br>resource &quot;aws_cloudwatch_log_group&quot; &quot;warike_development_api_gw_logs&quot; {<br>  name              = &quot;/aws/api-gw/${local.api_gateway_name}&quot;<br>  retention_in_days = 7<br>}</pre><h3>Connecting to Amazon Bedrock</h3><p>Next, to utilize Amazon Bedrock, this implementation will use the Amazon Nova Micro inference profile in the US region.</p><pre>locals {<br>  model_id = &quot;amazon.nova-micro-v1:0&quot;<br>}<br><br>data &quot;aws_bedrock_inference_profile&quot; &quot;warike_development_lambda_bedrock_model&quot; {<br>  inference_profile_id = &quot;us.${local.model_id}&quot;<br>}<br>## Bedrock Policy ##<br>data &quot;aws_iam_policy_document&quot; &quot;warike_development_lambda_bedrock_policy_doc&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br>    actions = [<br>      &quot;bedrock:InvokeModel&quot;,<br>    ]<br>    resources = [&quot;*&quot;]<br>  }<br>}</pre><h3>Lambda Service</h3><p>Finally, we’ll create the Lambda function associated with all the components we’ve created, along with others that can be found in the repository.</p><pre>locals {<br>  lambda_function_name = local.project_name<br>  lambda_env_vars = {<br>    AWS_BEDROCK_MODEL = data.aws_bedrock_inference_profile.warike_development_lambda_bedrock_model.inference_profile_arn<br>  }<br>}<br><br>module &quot;warike_development_lambda&quot; {<br>  source  = &quot;terraform-aws-modules/lambda/aws&quot;<br>  version = &quot;8.1.2&quot;<br>  function_name = local.lambda_function_name<br>  description   = &quot;Lambda function for ${local.project_name}&quot;<br>  image_uri               = &quot;${aws_ecr_repository.warike_development_ecr.repository_url}:latest&quot;<br>  package_type            = &quot;Image&quot;<br>  create_package          = false<br>  ignore_source_code_hash = true<br>  memory_size             = 512<br>  timeout                 = 900<br>  environment_variables = merge(<br>    local.lambda_env_vars,<br>    {}<br>  )<br>  create_role = false<br>  lambda_role = aws_iam_role.warike_development_lambda_role.arn<br>  ## Cloudwatch logging<br>  use_existing_cloudwatch_log_group = true<br>  logging_log_group                 = aws_cloudwatch_log_group.warike_development_lambda_logs.name<br>  logging_log_format                = &quot;JSON&quot;<br>  logging_application_log_level     = &quot;INFO&quot;<br>  logging_system_log_level          = &quot;WARN&quot;<br>  ## function URL<br>  create_lambda_function_url = false<br>  depends_on = [<br>    aws_cloudwatch_log_group.warike_development_lambda_logs,<br>    null_resource.warike_development_seed_ecr_image<br>  ]<br>  tags = merge(local.tags, {<br>    Name = local.lambda_function_name<br>  })<br>}<br>resource &quot;null_resource&quot; &quot;warike_development_seed_ecr_image&quot; {<br>  provisioner &quot;local-exec&quot; {<br>    command = &lt;&lt;EOT<br>      aws ecr get-login-password --region ${local.aws_region} --profile ${local.aws_profile} \\<br>        | docker login --username AWS --password-stdin ${data.aws_caller_identity.current.account_id}.dkr.ecr.${local.aws_region}.amazonaws.com<br>      docker pull public.ecr.aws/lambda/nodejs:22<br>      docker tag public.ecr.aws/lambda/nodejs:22 ${aws_ecr_repository.warike_development_ecr.repository_url}:latest<br>      docker push ${aws_ecr_repository.warike_development_ecr.repository_url}:latest<br>    EOT<br>  }<br>  depends_on = [aws_ecr_repository.warike_development_ecr]<br>}</pre><p>Important notice, <strong><em>warike_development_seed_ecr_image</em></strong> will require you to have your local docker running.</p><p>Let’s move ahead.</p><h3>Creating the Resources</h3><p>Once the resources are created, you should see a message similar to this:</p><pre>terraform apply<br>...<br>Apply complete! Resources: 26 added, 0 changed, 0 destroyed.</pre><h3>Configuring CI/CD with GitHub + ECR</h3><p>Additionally, we need a Docker image containing our project. The following GitHub pipeline will allow us to build and push an image to ECR, followed by its deployment to Lambda.</p><pre>---<br>name: Lambda CI/CD Common<br>&#39;on&#39;:<br>  workflow_call:<br>    inputs:<br>      app-name:<br>        type: string<br>      lambda-function-secret-name:<br>        required: true<br>        type: string<br>      pnpm-version:<br>        required: false<br>        type: number<br>        default: 10<br>      node-version:<br>        required: false<br>        type: number<br>        default: 22<br>    secrets:<br>      PROJECT_NAME:<br>        required: true<br>      AWS_OIDC_ROLE_ARN:<br>        required: true<br>      AWS_REGION:<br>        required: true<br>      ECR_REPOSITORY:<br>        required: true<br>      AWS_LAMBDA_FUNCTION_NAME:<br>        required: true<br>      AWS_LAMBDA_FUNCTION_ROLE_ARN:<br>        required: true<br>jobs:<br>  build:<br>    name: Build and Test<br>    runs-on: ubuntu-latest<br>    defaults:<br>      run:<br>        working-directory: ./handler<br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v4<br>      <br>      - name: Install pnpm<br>        uses: pnpm/action-setup@v4<br>        with:<br>          version: ${{ inputs.pnpm-version }}<br>- name: Use Node.js ${{ inputs.node-version }}<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: ${{ inputs.node-version }}<br>      - name: Install Dependencies<br>        run: pnpm install --frozen-lockfile<br>  <br>      - name: Scan for critical vulnerabilities<br>        run: pnpm audit --audit-level=critical<br>  <br>      - name: Run Tests<br>        env:<br>          DOTENV_QUIET: true<br>        run: pnpm test:ci<br>        <br>      - name: Build<br>        run: pnpm run build<br>      <br>  build-docker:<br>    name: Build and Push Docker Image<br>    runs-on: ubuntu-latest<br>    needs: build<br>    permissions:<br>      id-token: write<br>      contents: read<br>    outputs:<br>      sha: ${{ steps.vars.outputs.sha }}<br>    defaults:<br>      run:<br>        working-directory: ./handler<br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v4<br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          role-to-assume: ${{ secrets.AWS_OIDC_ROLE_ARN }}<br>          aws-region: ${{ secrets.AWS_REGION }}<br>      - name: Login to Amazon ECR<br>        id: login-ecr<br>        uses: aws-actions/amazon-ecr-login@v2<br>        with:<br>          mask-password: &#39;true&#39;<br>          <br>      - name: Set commit-sha<br>        id: vars<br>        run: |<br>          calculatedSha=$(git rev-parse --short ${{ github.sha }})<br>          echo &quot;sha=${calculatedSha}&quot; &gt;&gt; $GITHUB_OUTPUT<br>      - name: Build and Push Docker Image<br>        env:<br>          DOCKER_IMAGE: ${{ secrets.ECR_REPOSITORY }}:${{ inputs.app-name }}-${{ steps.vars.outputs.sha }}<br>        run: |<br>          echo &quot;Building Docker image $DOCKER_IMAGE&quot;<br>          docker build -t $DOCKER_IMAGE .<br>          docker tag $DOCKER_IMAGE &quot;${{ secrets.ECR_REPOSITORY }}:${{ inputs.app-name }}-${{ steps.vars.outputs.sha }}&quot;<br>          docker tag $DOCKER_IMAGE &quot;${{ secrets.ECR_REPOSITORY }}:latest&quot;<br>          docker push $DOCKER_IMAGE<br>          docker push &quot;${{ secrets.ECR_REPOSITORY }}:${{ inputs.app-name }}-${{ steps.vars.outputs.sha }}&quot;<br>          docker push &quot;${{ secrets.ECR_REPOSITORY }}:latest&quot;<br>  deploy-prod:<br>    name: Deploy Production Lambda<br>    runs-on: ubuntu-latest<br>    if: github.ref == &#39;refs/heads/main&#39;<br>    needs: build-docker<br>    permissions:<br>      id-token: write<br>      contents: read<br>    defaults:<br>      run:<br>        working-directory: ./handler<br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v4<br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          role-to-assume: ${{ secrets.AWS_OIDC_ROLE_ARN }}<br>          aws-region: ${{ secrets.AWS_REGION }}<br>      - name: Deploy Production Lambda<br>        uses: aws-actions/aws-lambda-deploy@v1.1.0<br>        with:<br>          function-name: ${{ secrets.AWS_LAMBDA_FUNCTION_NAME }}<br>          package-type: Image<br>          image-uri: ${{ secrets.ECR_REPOSITORY }}:${{ inputs.app-name }}-${{ needs.build-docker.outputs.sha }}</pre><p>And if everything is correct, we will be in a position to test Amazon Bedrock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YeyNLwCF3iKe7wpnJKLAA.png" /></figure><h3>Testing</h3><p>Let’s perform a test. From our terminal, we can make the following query and observe the result:</p><pre>curl -sS &quot;&lt;https://123456.execute-api.us-west-2.amazonaws.com/dev/&gt;&quot; \\<br>  -H &quot;Content-Type: application/json&quot; \\<br>  -d &#39;{&quot;prompt&quot;:&quot;Heeey hoe gaat het?&quot;}&#39; | jq</pre><p>The expected output is something like this:</p><pre>{<br>  &quot;success&quot;: true,<br>  &quot;data&quot;: &quot;Hoi! Het gaat prima, bedankt voor het vragen. Hoe gaat het met jou? Is er iets waar ik je kan helpen of iets waar je graag over wilt praten?&quot;<br>}</pre><p>I call that a <strong>success</strong>.</p><h3>Observability</h3><p>It is important to mention that we can monitor any errors from CloudWatch, so we don’t have to navigate in the dark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LLlx1ug3g6wZ_X-xPSlNg.png" /></figure><h3>Cleaning</h3><p>Finally, we clean up the resources.</p><pre>terraform destroy<br>...<br>Destroy complete! Resources: 26 destroyed.</pre><h3>Conclusions</h3><p>Overall, implementing this GenAI service using AWS serverless components was quite straightforward.</p><p>The combination of API Gateway, AWS Lambda, and Amazon Bedrock, specifically with the Nova Micro model, proves to be not only functional but also incredibly cost-effective. The analysis showed that this solution remains exceptionally inexpensive, even when (manually) scaling traffic significantly.</p><p>By leveraging Terraform for infrastructure management and GitHub Actions for the CI/CD pipeline, we achieved a robust and fully automated deployment process.</p><p>Finally, even by excluding aspects like authentication, it provides a solid and scalable foundation for building more complex Generative AI applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd0934f3697b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/warike/launching-your-ai-agent-on-aws-bedrock-lambda-api-gateway-bd0934f3697b">Launching Your AI Agent on AWS: Bedrock, Lambda &amp; API Gateway</a> was originally published in <a href="https://medium.com/warike">Warike technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS and MongoDB Atlas: High-Performance Connection with VPC Peering and Terraform]]></title>
            <link>https://medium.com/warike/aws-and-mongodb-atlas-high-performance-connection-with-vpc-peering-and-terraform-5cf450f6328a?source=rss-4f077c6eb02a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf450f6328a</guid>
            <category><![CDATA[aws-architecture]]></category>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[vpc-peering]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sergio Esteban]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 15:29:34 GMT</pubDate>
            <atom:updated>2025-09-22T10:01:34.317Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a robust and secure architecture. VPC Peering setup to connect your services efficiently.</h4><h3>Introduction</h3><p>The following post is a summary of how to establish a high-performance connection between private workloads in AWS and MongoDB Atlas services.</p><p>Atlas is a cloud platform that simplifies the deployment, operation, and scalability of MongoDB databases.</p><h3>Context</h3><p>A common reason to consider Atlas services is when you need your MongoDB deployment to have high availability, security, automated backups, and smooth integration with your cloud provider, whether AWS, Azure, or GCP, without the need to manage servers.</p><h4>Scope</h4><p>For this post, we will implement VPC Peering, which in short enables secure and private communication between resources hosted in your VPC and Atlas-managed instances without exposing them to the internet.</p><p>In addition, to demonstrate subnet connectivity, you will create a pair of EC2 instances within a public network as bastions without access to Atlas. Finally, we will deploy another instance in a private subnet with the ability to access Atlas services.</p><p>The following high-level diagram shows the target architecture we are going to implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xSIyxxa2BjMBC7rY6yxGw.png" /><figcaption>High-level Architecture — VPC Peering</figcaption></figure><h3>TLDR</h3><p>All source code can be found in the following <a href="https://github.com/warike/showcase/tree/main/projects/10-mongodb-vpc-peering">repository</a>.</p><h3>Implementation</h3><p>For this post we assume that accounts have already been created in both AWS and Atlas.</p><p>Otherwise, you can use the following links:</p><ul><li><a href="https://www.mongodb.com/cloud/atlas/register">https://www.mongodb.com/cloud/atlas/register</a></li><li><a href="https://aws.amazon.com/es/free/">https://aws.amazon.com/es/free/</a></li></ul><h3>VPC</h3><p>We start by defining our VPC in <strong><em>us-east-1</em></strong>. At a minimum you must ensure the creation of two subnets. To optimize costs we specify the creation of only one NAT Gateway by setting <strong><em>single_nat_gateway</em></strong>.</p><p>It’s important to keep in mind the network segments we are going to work with. For this post we defined 10.0.0.0/16.</p><pre>// main.tf<br><br>// AZ Availables<br>data &quot;aws_availability_zones&quot; &quot;available&quot; {<br>  state = &quot;available&quot;<br>}<br><br>locals {<br>  vpc_name = &quot;vpc-${var.project_name}&quot;<br>  ## Use 3 AZs form data.aws_availability_zones.available.names<br>  azs            = slice(data.aws_availability_zones.available.names, 0, 3)<br>  vpc_cidr_block = &quot;10.0.0.0/16&quot;<br><br>  # Generate 3 private subnets (/24 each)<br>  private_subnets = [<br>    for i in range(3) : cidrsubnet(local.vpc_cidr_block, 8, i)<br>  ]<br><br>  # Generate 3 public subnets (/24 each), offset to avoid overlap<br>  public_subnets = [<br>    for i in range(3) : cidrsubnet(local.vpc_cidr_block, 8, i + 100)<br>  ]<br>  <br>  additional_public_subnet_tags = {<br>    &quot;public&quot; = &quot;true&quot;<br>  }<br>  additional_private_subnet_tags = {<br>    &quot;private&quot; = &quot;true&quot;<br>  }<br>}<br><br>module &quot;vpc&quot; {<br>  source  = &quot;terraform-aws-modules/vpc/aws&quot;<br>  version = &quot;6.0.1&quot;<br><br>  name = local.vpc_name<br>  cidr = local.vpc_cidr_block<br><br>  azs             = local.azs<br>  private_subnets = local.private_subnets<br>  public_subnets  = local.public_subnets<br><br>  map_public_ip_on_launch = true<br><br><br>  enable_dns_hostnames = true<br>  enable_dns_support   = true<br><br>  enable_nat_gateway     = true<br>  single_nat_gateway     = true<br>  one_nat_gateway_per_az = false<br><br>  public_subnet_tags = merge(<br>    local.additional_public_subnet_tags,<br>    {}<br>  )<br>  private_subnet_tags = merge(<br>    local.additional_private_subnet_tags,<br>    {}<br>  )<br><br>  tags = local.tags<br>}</pre><h3>MongoDB Cluster</h3><p>Next we move on to creating the necessary resources for the MongoDB cluster in Atlas, defining the Mongo Atlas CIDR block as <strong><em>10.8.0.0/21</em></strong>. It’s important to use the same <strong><em>region</em></strong> between AWS and Atlas.</p><p>This ensures there is no overlap between segments and prevents conflicts when setting up VPC peering.</p><pre>locals {<br>  mongodb_org_id                 = data.mongodbatlas_roles_org_id.warike_development_mongodb_atlas_org_id<br>  mongodb_project_name           = var.mongodbatlas_project_name<br>  mongodb_cluster_name           = &quot;cluster-${local.project_name}&quot;<br>  mongodb_provider_name          = &quot;AWS&quot;<br>  mongodb_region_name            = &quot;US_EAST_1&quot;<br>  mongodb_main_database_name     = &quot;database-${random_pet.warike_development_atlas_database.id}&quot;<br>  mongodb_administrator_username = &quot;administrator-${random_string.warike_development_atlas_username.id}&quot;<br>  mongodb_administrator_password = random_password.warike_development_atlas_password.result<br><br>  atlas_cidr_block = &quot;10.8.0.0/21&quot;<br><br>}<br><br>## Random name<br>resource &quot;random_pet&quot; &quot;warike_development_atlas_database&quot; {<br>  length    = 6<br>  separator = &quot;-&quot;<br>}<br><br>## Random String<br>resource &quot;random_string&quot; &quot;warike_development_atlas_username&quot; {<br>  length = 4<br>  lower  = true<br>}<br><br>## MongoDB Atlas password<br>resource &quot;random_password&quot; &quot;warike_development_atlas_password&quot; {<br>  length           = 20<br>  special          = false<br>  override_special = &quot;_%@&quot;<br>}<br><br>## MongoDB Atlas organization ID<br>data &quot;mongodbatlas_roles_org_id&quot; &quot;warike_development_mongodb_atlas_org_id&quot; {<br>}<br><br>## MongoDB Atlas Project<br>resource &quot;mongodbatlas_project&quot; &quot;warike_development_mongodb_atlas_project&quot; {<br>  name   = local.mongodb_project_name<br>  org_id = data.mongodbatlas_roles_org_id.warike_development_mongodb_atlas_org_id.org_id<br><br>  limits {<br>    name  = &quot;atlas.project.deployment.clusters&quot;<br>    value = 1<br>  }<br><br>  is_collect_database_specifics_statistics_enabled = true<br>  is_data_explorer_enabled                         = true<br>  is_extended_storage_sizes_enabled                = false<br>  is_performance_advisor_enabled                   = true<br>  is_realtime_performance_panel_enabled            = true<br>  is_schema_advisor_enabled                        = true<br><br>  tags = local.tags<br>}<br><br>## MongoDB Atlas Database User<br>resource &quot;mongodbatlas_database_user&quot; &quot;warike_development_mongodb_atlas_db_user&quot; {<br>  username   = local.mongodb_administrator_username<br>  password   = local.mongodb_administrator_password<br>  project_id = mongodbatlas_project.warike_development_mongodb_atlas_project.id<br><br>  auth_database_name = &quot;admin&quot;<br><br>  roles {<br>    role_name     = &quot;dbAdmin&quot;<br>    database_name = local.mongodb_main_database_name<br>  }<br><br>  depends_on = [<br>    random_password.warike_development_atlas_password,<br>    random_string.warike_development_atlas_username,<br>    random_pet.warike_development_atlas_database<br>  ]<br>}<br><br>## MongoDB Atlas Advanced Cluster <br>resource &quot;mongodbatlas_advanced_cluster&quot; &quot;warike_development_mongodb_atlas_cluster&quot; {<br>  project_id     = mongodbatlas_project.warike_development_mongodb_atlas_project.id<br>  name           = local.mongodb_cluster_name<br>  cluster_type   = &quot;REPLICASET&quot;<br>  backup_enabled = false<br><br><br>  replication_specs = [<br>    {<br>      region_configs = [<br>        {<br>          electable_specs = {<br>            instance_size = &quot;M10&quot;<br>            node_count    = 3<br>          }<br><br>          provider_name = local.mongodb_provider_name<br>          region_name   = local.mongodb_region_name<br>          priority      = 7<br>          tags          = local.tags<br>        }<br>      ]<br>    }<br>  ]<br><br>}</pre><p>After applying the changes we can see the cluster being created in the Atlas platform. Once the process finishes we can view the final result.</p><p>The following image shows the MongoDB Atlas dashboard with the cluster created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqgqWnL2lhVH09rf9H2XQw.png" /><figcaption>Atlas Dashboard— Cluster management</figcaption></figure><h3>VPC Peering</h3><pre>locals {<br>  aws_private_cidr_block = module.vpc.private_subnets_cidr_blocks[0]<br>  mongodb_ip_list = {<br>    &quot;AWS&quot;  = local.aws_private_cidr_block,<br>    &quot;MyIP&quot; = var.my_ip<br>  }<br>}<br><br>data &quot;aws_caller_identity&quot; &quot;current&quot; {}<br><br>## MongoDB Atlas Network Container<br>resource &quot;mongodbatlas_network_container&quot; &quot;warike_development_mongodb_atlas_network_container&quot; {<br>  project_id       = mongodbatlas_project.warike_development_mongodb_atlas_project.id<br>  atlas_cidr_block = local.atlas_cidr_block<br>  provider_name    = local.mongodb_provider_name<br>  region_name      = local.mongodb_region_name<br>}<br><br>## MongoDB Atlas Project IP Access List from local mongodb_ip_list<br>resource &quot;mongodbatlas_project_ip_access_list&quot; &quot;warike_development_mongodb_atlas_ip_access&quot; {<br>  for_each = local.mongodb_ip_list<br><br>  project_id = mongodbatlas_project.warike_development_mongodb_atlas_project.id<br>  cidr_block = each.value<br>  comment    = each.key<br>}<br><br>## MongoDB Atlas Network Peering<br>resource &quot;mongodbatlas_network_peering&quot; &quot;warike_development_mongodb_atlas_network_peering&quot; {<br>  container_id  = mongodbatlas_network_container.warike_development_mongodb_atlas_network_container.id<br>  project_id    = mongodbatlas_project.warike_development_mongodb_atlas_project.id<br>  provider_name = local.mongodb_provider_name<br><br>  accepter_region_name   = local.aws_region<br>  vpc_id                 = module.vpc.vpc_id<br>  aws_account_id         = data.aws_caller_identity.current.account_id<br>  route_table_cidr_block = local.aws_private_cidr_block<br>}<br><br>## AWS VPC Peering Connection Accepter<br>## Accept the peering connection request<br>resource &quot;aws_vpc_peering_connection_accepter&quot; &quot;warike_development_mongodb_atlas_vpc_peering_connection_accepter&quot; {<br>  vpc_peering_connection_id = mongodbatlas_network_peering.warike_development_mongodb_atlas_network_peering.connection_id<br>  auto_accept               = true<br><br>  tags = {<br>    Side = &quot;Accepter&quot;<br>    Name = local.project_name<br>  }<br>}<br><br>## AWS Route for MongoDB Atlas Network Peering<br>resource &quot;aws_route&quot; &quot;warike_development_mongodb_atlas_vpc_peering_route&quot; {<br>  route_table_id            = module.vpc.private_route_table_ids[0]<br>  destination_cidr_block    = local.atlas_cidr_block<br>  vpc_peering_connection_id = mongodbatlas_network_peering.warike_development_mongodb_atlas_network_peering.connection_id<br>  depends_on = [<br>    aws_vpc_peering_connection_accepter.warike_development_mongodb_atlas_vpc_peering_connection_accepter<br>  ]<br>}</pre><p>The next image shows the MongoDB Atlas dashboard with the mapping of the first private subnet segment <strong><em>10.0.0.0/24</em></strong>, and the Atlas segment <strong><em>10.8.0.0/21</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFfzrSD3nMuVm8cd_DPYhw.png" /><figcaption>Atlas Dashboard — Network Access</figcaption></figure><p>Additionally, we can observe the counterpart from our AWS account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5t5x6X4i0mGX_lbw6iUVgQ.png" /><figcaption>AWS Console — VPC Peering</figcaption></figure><h3>Compute instances</h3><p>Let’s go ahead and deploy the EC2 instances inside their respective subnets. Additionally, I’ll add the VPC CIDR and my IP so we can move between machines over SSH.</p><pre>locals {<br>  key_name = &quot;key-${local.project_name}&quot;<br>  key_pair = var.key_pair<br><br>  instances = {<br>    bastion = {<br>      name                        = &quot;bastion-${local.project_name}&quot;<br>      type                        = &quot;t2.micro&quot;<br>      subnet_id                   = module.vpc.public_subnets[0]<br>      associate_public_ip_address = true<br>    }<br>    internal = {<br>      name                        = &quot;internal-${local.project_name}&quot;<br>      type                        = &quot;t2.micro&quot;<br>      subnet_id                   = module.vpc.private_subnets[0]<br>      associate_public_ip_address = false<br>    }<br>  }<br><br>  whitelist_cidr_blocks = [<br>    local.vpc_cidr_block,<br>    var.my_ip<br>  ]<br>}<br><br>data &quot;aws_ami&quot; &quot;latest_amazon_linux&quot; {<br>  most_recent = true<br>  owners      = [&quot;amazon&quot;]<br><br>  filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;amzn2-ami-hvm-*-x86_64-gp2&quot;]<br>  }<br>}<br><br># AWS Key Pair<br>resource &quot;aws_key_pair&quot; &quot;warike_sandbox_instaces_key_pair&quot; {<br>  key_name   = local.key_name<br>  public_key = local.key_pair<br>}<br><br># AWS Bastion instance<br>resource &quot;aws_instance&quot; &quot;warike_sandbox_bastion&quot; {<br>  for_each = local.instances<br><br>  ami                         = data.aws_ami.latest_amazon_linux.id<br>  instance_type               = each.value.type<br>  subnet_id                   = each.value.subnet_id<br>  associate_public_ip_address = each.value.associate_public_ip_address<br>  key_name                    = aws_key_pair.warike_sandbox_instaces_key_pair.key_name<br><br>  vpc_security_group_ids = [<br>    aws_security_group.warike_sandbox_instances_security_group.id,<br>  ]<br><br>  tags = {<br>    Name         = each.value.name<br>    InstanceType = each.value.type<br>  }<br>}<br><br># AWS Security group<br>resource &quot;aws_security_group&quot; &quot;warike_sandbox_instances_security_group&quot; {<br>  name        = &quot;instances-sg-${local.project_name}&quot;<br>  description = &quot;Security group for ${local.project_name} instances&quot;<br>  vpc_id      = module.vpc.vpc_id<br><br>  ## allow ssh<br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;TCP&quot;<br>    cidr_blocks = local.whitelist_cidr_blocks<br>  }<br>  ## allow icmp<br>  ingress {<br>    from_port   = -1<br>    to_port     = -1<br>    protocol    = &quot;ICMP&quot;<br>    cidr_blocks = local.whitelist_cidr_blocks<br>  }<br>  ## allow egress<br>  egress {<br>    from_port = 0<br>    to_port   = 0<br>    protocol  = &quot;-1&quot;<br>    cidr_blocks = [<br>      &quot;0.0.0.0/0&quot;<br>    ]<br>  }<br><br>  tags = {<br>    Name = &quot;instances-sg-${local.project_name}&quot;<br>  }<br>}<br><br></pre><h3>Testing</h3><p>To test the implementation the first step is knowing the connection string we need to connect to.</p><p>We can retrieve it from the following output:</p><pre>## MongoDB Atlas standard connection string<br>output &quot;atlas_connection_string&quot; {<br>  value = mongodbatlas_advanced_cluster.warike_development_mongodb_atlas_cluster.connection_strings.standard<br>}</pre><p>Once we have the connection string, we can try logging into the instances. Below are the commands to access both the instance in the public subnet and the one in the private subnet:</p><pre>ssh -A -i aws-key.pem ec2-user@&lt;public-ip-bastion&gt;<br>ssh -A -i aws-key.pem -J ec2-user@&lt;public-ip-bastion&gt; ec2-user@&lt;private-ip-internal&gt;</pre><p>Next, you should install <a href="https://www.mongodb.com/docs/mongodb-shell/">MongoSH</a> on each instance:</p><pre>echo &quot;[mongodb-org-7.0]<br>name=MongoDB Repository<br>baseurl=https://repo.mongodb.org/yum/amazon/2/mongodb-org/7.0/x86_64/<br>gpgcheck=1<br>enabled=1<br>gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc&quot; | sudo tee /etc/yum.repos.d/mongodb-org-7.0.repo<br><br>sudo yum install -y mongodb-mongosh<br>mongosh --version</pre><p>With everything installed, you can attempt the connection:</p><pre>mongosh &quot;mongodb://&lt;credentials&gt;@&lt;url&gt;:27017/?ssl=true&amp;authSource=admin&amp;replicaSet=atlas-zogrp0-shard-0&quot;</pre><h3>Bastion</h3><p>As expected, when trying to connect from the Bastion in the public subnet we get a timeout.</p><pre>Current Mongosh Log ID: 68cd84a4ab953eefb8ce5f46<br>Connecting to: mongodb://&lt;credentials&gt;@&lt;url&gt;:27017/?ssl=true&amp;authSource=admin&amp;replicaSet=atlas-zogrp0-shard-0<br>MongoServerSelectionError: Server selection timed out after 30000 ms. It looks like this is a MongoDB Atlas cluster. Please ensure that your Network Access List allows connections from your IP.</pre><h3>Internal</h3><p>Also as expected, when connecting from the Internal instance in the private subnet we get a successful connection.</p><pre>Current Mongosh Log ID: 68cd843bc940d026fece5f46<br>Connecting to: mongodb://&lt;credentials&gt;@&lt;url&gt;:27017/?ssl=true&amp;authSource=admin&amp;replicaSet=atlas-zogrp0-shard-0<br>Using MongoDB: 8.0.13<br>Using Mongosh: 2.5.8<br>For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/<br>To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).<br>You can opt-out by running the disableTelemetry() command.<br>Deprecation warnings:<br>  - Using mongosh on the current operating system is deprecated, and support may be removed in a future release.<br>See https://www.mongodb.com/docs/mongodb-shell/install/#supported-operating-systems for documentation on supported platforms.<br>Atlas atlas-zogrp0-shard-0 [primary] test&gt;</pre><p>I can see that as a success.</p><h3>Conclusions</h3><p>The process of creating a VPC Peering connection is quite straightforward and efficient. In addition, setting up a secure configuration is simple and well-documented.</p><p>This becomes especially important when considering the externalization of the MongoDB service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf450f6328a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/warike/aws-and-mongodb-atlas-high-performance-connection-with-vpc-peering-and-terraform-5cf450f6328a">AWS and MongoDB Atlas: High-Performance Connection with VPC Peering and Terraform</a> was originally published in <a href="https://medium.com/warike">Warike technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to automate a Mastra Workflow in Lambda Using EventBridge]]></title>
            <link>https://medium.com/warike/how-to-automate-a-mastra-workflow-in-lambda-using-eventbridge-7084fcc4cac7?source=rss-4f077c6eb02a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7084fcc4cac7</guid>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[mastra-ai]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Sergio Esteban]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 00:37:39 GMT</pubDate>
            <atom:updated>2025-08-25T00:45:02.264Z</atom:updated>
            <content:encoded><![CDATA[<p>A step-by-step guide with Typescript, Mastra and Terraform</p><h3>Introduction</h3><p>The need to implement Gen AI has been steadily growing, with the greatest benefits seen in deploying Agents within workflows tailored to client-specific needs.</p><p>If our business logic and technological solutions are already deployed on AWS, it makes sense to implement a cloud solution that is as compatible as possible with this ecosystem.</p><h3>Objective</h3><p>This post aims to demonstrate the technical implementation of an AI agent within a workflow stage and its deployment as a Lambda function.</p><p>The following high-level diagram illustrates the final architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81vyspLE62HIsv4WRcIQIw.png" /></figure><h3>Implementation</h3><p>For workflow orchestration, I’ll be using <a href="https://mastra.ai/">Mastra.ai</a>, a TypeScript Agent Framework that provides a range of features for efficient agentic workflow orchestration.</p><p>This post is not intended to dive into code implementation details, but rather to demonstrate agentic workflow orchestration in AWS.</p><h3>TLDRS</h3><p>You can still find the complete project code in the following <a href="https://github.com/warike/showcase/tree/main/projects/09-aws-lambda-eventbridge">GitHub repo</a>.</p><h3>Creating an Agent</h3><p>Mastra allows us to create an agent responsible for generating text based on a given prompt.</p><p>The following code shows how we define an agent, and for this example, I’ll be using gemini-2.0-flash-exp.</p><pre>// agent.ts<br>import { google } from &#39;@ai-sdk/google&#39;;<br>import { Agent } from &#39;@mastra/core/agent&#39;;<br>import prompt from &#39;./prompt&#39;;<br><br>export const reportAgent = new Agent({<br>  name: &#39;Report Agent&#39;,<br>  instructions: prompt,<br>  model: google(&#39;gemini-2.0-flash-exp&#39;)<br>});</pre><h3>Creating a Workflow</h3><p>Mastra lets us create different types of flow control, allowing us to tailor the workflow to our specific business needs.</p><blockquote>When you build a workflow, you typically break down operations into smaller tasks that can be linked and reused. <strong>Steps</strong> provide a structured way to manage these tasks by defining inputs, outputs, and execution logic.</blockquote><p>In this use case, we’ll use the following steps:</p><ul><li><strong>Fetch data</strong>: represents querying data from a source.</li><li><strong>Generate report</strong>: represents text generation via an agent.</li><li><strong>Send report</strong>: represents sending an email based on the data from the previous steps.</li></ul><p>If this use case looks familiar, you can find it applied in another scenario <a href="https://aws.amazon.com/blogs/big-data/automate-alerting-and-reporting-for-aws-glue-job-resource-usage/">here</a>.</p><p>Next, the following code shows the implementation of the steps.</p><pre>// workflow.ts<br>import { createWorkflow } from &#39;@mastra/core/workflows&#39;;<br>import { z } from &#39;zod&#39;;<br>import { fetchData } from &#39;./fetchdata-step&#39;;<br>import { generateReport } from &#39;./generatereport-step&#39;;<br>import { sendReport } from &#39;./sendreport-step&#39;;<br><br>export const reportWorkflow = createWorkflow({<br>  id: &#39;report-workflow&#39;,<br>  inputSchema: z.object({}),<br>  outputSchema: z.object({}),<br>})<br>.then(fetchData)<br>.foreach(generateReport, { concurrency: 10 })<br>.then(sendReport)<br>.commit();</pre><p>It’s important to note that Mastra allows us to use .foreach to iterate over the results of the fetchData function and then consolidate the iterations within sendReport.</p><h3>Mastra Instance</h3><p>With all the pieces in place, we bring them together by creating a Mastra instance.</p><pre><br>// mastra/index.ts<br>import { Mastra } from &#39;@mastra/core/mastra&#39;;<br>import { reportWorkflow } from &#39;./workflows/report-workflow&#39;;<br>import { reportAgent } from &#39;./agents/report-agent&#39;;<br>import { env } from &#39;../env&#39;;<br>import { logger } from &#39;../utils/logger&#39;;<br><br>export const mastra = new Mastra({<br>  workflows: { reportWorkflow },<br>  agents: { reportAgent },<br>  logger: logger,<br>});</pre><p>This instance is then used in our workflow’s main function, which gets triggered when we invoke the Lambda function.</p><pre>// app.ts<br>import { mastra } from &quot;./mastra&quot;;<br><br>export async function runWorkflow() {<br>    try {<br>        console.log(&#39;🚀 Starting reportWorkflow...&#39;);<br>        <br>        const run = await mastra.getWorkflow(&quot;reportWorkflow&quot;).createRunAsync();<br>        const runResult = await run.start({<br>            inputData: {}<br>        });<br>        <br>        if (runResult.status === &#39;success&#39;) {<br>            console.log(&#39;✅ Workflow executed successfully:&#39;);<br>            console.log(runResult.result);<br>            return runResult.result;<br>        } else if (runResult.status === &#39;failed&#39;) {<br>            console.error(&#39;❌ Workflow error:&#39;);<br>            console.error(runResult.error);<br>            throw new Error(`Workflow failed: ${runResult.status}`);<br>        }else {<br>            console.warn(&#39;⚠️ Unknown workflow status:&#39;, runResult.status);<br>            throw new Error(`Unknown workflow status: ${runResult.status}`);<br>        }<br>    } catch (error) {<br>        console.error(&#39;💥 Fatal error running workflow:&#39;, error);<br>        throw error;<br>    }<br>    <br>}</pre><p>This is the handler function that will interact with the AWS Lambda ecosystem.</p><pre>import { runWorkflow } from &#39;./app&#39;;<br><br>export const handler = async (event: any, context: any) =&gt; {<br>    console.log(&#39;Lambda function invoked&#39;);<br>    console.log(&#39;Event:&#39;, JSON.stringify(event, null, 2));<br>    console.log(&#39;Context:&#39;, JSON.stringify(context, null, 2));<br><br>    try {<br>        const result = await runWorkflow();<br>        <br>        return {<br>            statusCode: 200,<br>            headers: {<br>                &quot;Content-Type&quot;: &quot;application/json&quot;,<br>            },<br>            body: JSON.stringify({<br>                message: &#39;Workflow executed successfully!&#39;,<br>                result: result,<br>            }),<br>        };<br>    } catch (error) {<br><br>        console.error(&#39; Error in handler:&#39;, error);<br>        <br>        return {<br>            statusCode: 500,<br>            headers: {<br>                &quot;Content-Type&quot;: &quot;application/json&quot;,<br>            },<br>            body: JSON.stringify({<br>                message: &#39;An error occurred during workflow execution.&#39;,<br>                error: error instanceof Error ? error.message : String(error),<br>            }),<br>        };<br>    }<br>};</pre><h3>Containerization</h3><p>With the workflow ready, we package the solution in our Dockerfile.</p><pre># ---- Build Stage ----<br>FROM node:22-alpine AS builder<br><br>WORKDIR /usr/src/app<br>RUN corepack enable<br><br>COPY package.json pnpm-lock.yaml* ./<br><br>RUN pnpm install --frozen-lockfile<br><br>COPY . .<br><br>RUN pnpm run build<br><br># ---- Runtime Stage ----<br>FROM public.ecr.aws/lambda/nodejs:22<br><br>WORKDIR ${LAMBDA_TASK_ROOT}<br><br>COPY --from=builder /usr/src/app/dist ./<br>COPY --from=builder /usr/src/app/node_modules ./node_modules<br><br>CMD [ &quot;index.handler&quot; ]</pre><p>That should cover the application. Let’s move on to the infrastructure.</p><h3>Infrastructure</h3><p>With all previous steps completed, we can now start building the AWS infrastructure using Terraform.</p><p>The following diagram shows the resources that we need to deploy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ysayMZlTJ6Uhfz8wtWmY5A.png" /></figure><p>To start, we’ll create an ECR to host the Docker images that will be used by Lambda.</p><h3>ECR Repository</h3><p>The first step is to create the ECR repository that will host the Docker images generated throughout the project’s lifecycle.</p><p>Additionally, upload a nodejs:22 image that will be used as the default when creating the project.</p><pre>locals {<br>  ecr_name = &quot;ecr-${local.project_name}&quot;<br>}<br><br>## ECR Repository<br>resource &quot;aws_ecr_repository&quot; &quot;warike_development_ecr&quot; {<br>  name = local.ecr_name<br><br>  # security config<br>  image_tag_mutability = &quot;IMMUTABLE_WITH_EXCLUSION&quot;<br>  image_scanning_configuration {<br>    scan_on_push = true<br>  }<br>  encryption_configuration {<br>    encryption_type = &quot;AES256&quot;<br>  }<br><br>  # latest mutability config<br>  image_tag_mutability_exclusion_filter {<br>    filter      = &quot;latest*&quot;<br>    filter_type = &quot;WILDCARD&quot;<br><br>  }<br><br>  force_delete = true<br>}<br><br>## Upload nodejs:22<br>resource &quot;null_resource&quot; &quot;seed_ecr_image&quot; {<br>  provisioner &quot;local-exec&quot; {<br>    command = &lt;&lt;EOT<br>      aws ecr get-login-password --region ${local.aws_region} --profile ${local.aws_profile} \<br>        | docker login --username AWS --password-stdin ${data.aws_caller_identity.current.account_id}.dkr.ecr.${local.aws_region}.amazonaws.com<br><br>      docker pull public.ecr.aws/lambda/nodejs:22<br>      docker tag public.ecr.aws/lambda/nodejs:22 ${aws_ecr_repository.warike_development_ecr.repository_url}:latest<br>      docker push ${aws_ecr_repository.warike_development_ecr.repository_url}:latest<br>    EOT<br>  }<br><br>  depends_on = [aws_ecr_repository.warike_development_ecr]<br>}<br><br>## ECR - Output repository URL<br>output &quot;ecr_repository_url&quot; {<br>  value = aws_ecr_repository.warike_development_ecr.repository_url<br>}</pre><p>With the ECR ready, we are able to link it to the Lambda function. But first, we need to define an IAM Role for our function.</p><pre>## IAM Policy Assume role<br>data &quot;aws_iam_policy_document&quot; &quot;warike_development_lambda_assume_role&quot; {<br>  statement {<br>    sid     = &quot;1&quot;<br>    actions = [&quot;sts:AssumeRole&quot;]<br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;lambda.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br>## IAM Role for Lambda<br>resource &quot;aws_iam_role&quot; &quot;warike_development_lambda_role&quot; {<br>  name               = &quot;lambda-role-${local.project_name}&quot;<br>  description        = &quot;IAM role for Lambda&quot;<br>  assume_role_policy = data.aws_iam_policy_document.warike_development_lambda_assume_role.json<br>}</pre><h3>Parameter Store</h3><p>Additionally, we know the workflow requires environment variables from .envfile, we can store them in AWS SSM Parameter Store.</p><p>To use them as a file within the Lambda function, I’ve mapped them into a key-value structure.</p><pre>locals {<br>  env_file = file(&quot;${path.module}/../workflow/.env&quot;)<br>  env_vars = {<br>    for line in split(&quot;\n&quot;, local.env_file) :<br>    split(&quot;=&quot;, line)[0] =&gt; split(&quot;=&quot;, line)[1]<br>    if length(trimspace(line)) &gt; 0 &amp;&amp; !startswith(trimspace(line), &quot;#&quot;)<br>  }<br>}<br><br># Create one SSM parameter per key/value<br>resource &quot;aws_ssm_parameter&quot; &quot;warike_development_env_vars&quot; {<br>  for_each    = local.env_vars<br>  name        = &quot;/${local.project_name}/${each.key}&quot;<br>  description = &quot;Env var ${each.key} for ${local.project_name}&quot;<br>  type        = &quot;SecureString&quot;<br>  value       = each.value<br>}</pre><p>Next.</p><h3>CloudWatch</h3><p>When a Lambda function is first invoked, AWS automatically creates a CloudWatch Logs log group for it. However, deleting the function does not delete the log group. <br>It’s recommended to manage log groups explicitly (including retention and deletion policies) to avoid leaving unused log groups behind.</p><pre><br>## IAM role policy for Cloudwatch logging<br>data &quot;aws_iam_policy_document&quot; &quot;warike_development_lambda_logging&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br>    actions = [<br>      &quot;logs:CreateLogStream&quot;,<br>      &quot;logs:PutLogEvents&quot;<br>    ]<br>    resources = [<br>      &quot;arn:aws:logs:*:*:log-group:/aws/lambda/${local.lambda_function_name}:*&quot;<br>    ]<br>  }<br>}<br>## Cloudwatch Lambda logs IAM policy<br>resource &quot;aws_iam_role_policy&quot; &quot;warike_development_lambda_logging&quot; {<br>  name = &quot;cloudwatch-${local.project_name}&quot;<br>  role = aws_iam_role.warike_development_lambda_role.id<br><br>  policy = data.aws_iam_policy_document.warike_development_lambda_logging.json<br>}<br>## Cloudwatch log group<br>resource &quot;aws_cloudwatch_log_group&quot; &quot;warike_development_lambda_logs&quot; {<br>  name              = &quot;/aws/lambda/${local.lambda_function_name}&quot;<br>  retention_in_days = 7<br>}</pre><h3>Lambda function</h3><p>Finally, we define the Lambda function.</p><pre>locals {<br>  lambda_function_name = &quot;lambda-${local.project_name}&quot;<br>}<br><br>## Lambda function workflow<br>resource &quot;aws_lambda_function&quot; &quot;warike_development_lambda&quot; {<br>  #config<br>  function_name = local.lambda_function_name<br>  timeout       = 900<br>  image_uri     = &quot;${aws_ecr_repository.warike_development_ecr.repository_url}:latest&quot;<br>  package_type  = &quot;Image&quot;<br>  role          = aws_iam_role.warike_development_lambda_role.arn<br><br>  logging_config {<br>    log_format            = &quot;JSON&quot;<br>    application_log_level = &quot;INFO&quot;<br>    system_log_level      = &quot;WARN&quot;<br>  }<br><br>  environment {<br>    variables = local.env_vars<br>  }<br><br>  lifecycle {<br>    ignore_changes = [image_uri]<br>  }<br><br>  depends_on = [<br>    aws_ecr_repository.warike_development_ecr,<br>    aws_ssm_parameter.warike_development_env_vars,<br>    aws_cloudwatch_log_group.warike_development_lambda_logs,<br>    null_resource.seed_ecr_image,<br>  ]<br>}</pre><h3>EventBridge Rule</h3><p>Since we need the lambda function to run on a specific schedule, a simple and cost-effective solution would be to use an EventBridge Rule.</p><p>We define a rule with the desired schedule, set our Lambda function as the target, and finally add the invocation permissions.</p><pre># EventBridge Rule to trigger<br>resource &quot;aws_cloudwatch_event_rule&quot; &quot;warike_development_lambda_schedule&quot; {<br>  name                = &quot;lambda-schedule-${local.project_name}&quot;<br>  description         = &quot;Daily Run Lambda Function 03.00 hrs UTC&quot;<br>  schedule_expression = &quot;cron(0 03 * * ? *)&quot;<br>}<br># Target that connects the Rule with the API Destination<br>resource &quot;aws_cloudwatch_event_target&quot; &quot;warike_development_lambda_http_target&quot; {<br>  rule      = aws_cloudwatch_event_rule.warike_development_lambda_schedule.name<br>  target_id = &quot;target_workflow_lambda&quot;<br>  arn       = aws_lambda_function.warike_development_lambda.arn<br><br>  input = jsonencode({<br>    inputData = {}<br>  })<br>}<br>## Allow Eventbridge &lt;&gt; Lambda<br>resource &quot;aws_lambda_permission&quot; &quot;warike_development_allow_eventbridge&quot; {<br>  statement_id  = &quot;AllowExecutionFromEventBridge&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.warike_development_lambda.function_name<br>  principal     = &quot;events.amazonaws.com&quot;<br>  source_arn    = aws_cloudwatch_event_rule.warike_development_lambda_schedule.arn<br>}</pre><h3>Deployment automation</h3><p>To complete the deployment, I’ll set up a GitHub workflow to automate the process. We need to map all the Actions secrets in our GitHub repository.</p><p>You can also map them manually if preferred.</p><pre>locals {<br>  gh = {<br>    repository_name = local.project_name<br>    owner           = local.gh_owner<br>  }<br><br>  gh_secrets = {<br>    PROJECT_NAME                 = local.project_name<br>    AWS_REGION                   = local.aws_region<br>    AWS_ECR_REPOSITORY           = aws_ecr_repository.warike_development_ecr.repository_url<br>    AWS_IAM_ROLE_ARN             = aws_iam_role.warike_development_github_iam_role.arn<br>    AWS_LAMBDA_FUNCTION_NAME     = aws_lambda_function.warike_development_lambda.function_name<br>    AWS_LAMBDA_FUNCTION_ROLE_ARN = aws_iam_role.warike_development_lambda_role.arn<br>  }<br>}<br><br>data &quot;github_repository&quot; &quot;main&quot; {<br>  full_name = &quot;${local.gh.owner}/${local.gh.repository_name}&quot;<br>}<br><br>## Github secrets<br>resource &quot;github_actions_secret&quot; &quot;secrets&quot; {<br>  for_each = local.gh_secrets<br>  repository      = data.github_repository.main.name<br>  secret_name     = each.key<br>  plaintext_value = each.value<br><br>  depends_on = [<br>    github_repository.main,<br>    aws_ecr_repository.warike_development_ecr,<br>    aws_iam_role.warike_development_github_iam_role,<br>    aws_lambda_function.warike_development_lambda<br>  ]<br>}</pre><h3>Github workflow</h3><p>The following diagram provides a high-level view of what we’re going to implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPcnCiV47KDOz3QHBy_GGg.png" /></figure><p>Before defining the GitHub workflow pipeline, we need to be aware that an OpenID Connect provider and its corresponding IAM policies are required.</p><pre>## Github - OIDC provider<br>resource &quot;aws_iam_openid_connect_provider&quot; &quot;warike_development_github&quot; {<br>  # config<br>  url            = &quot;https://token.actions.githubusercontent.com&quot;<br>  client_id_list = [&quot;sts.amazonaws.com&quot;]<br>}<br><br>## IAM Policy OIDC<br>data &quot;aws_iam_policy_document&quot; &quot;warike_development_github_oidc&quot; {<br>  statement {<br>    effect  = &quot;Allow&quot;<br>    actions = [&quot;sts:AssumeRoleWithWebIdentity&quot;]<br>    principals {<br>      type        = &quot;Federated&quot;<br>      identifiers = [aws_iam_openid_connect_provider.warike_development_github.arn]<br>    }<br>    condition {<br>      test     = &quot;StringLike&quot;<br>      variable = &quot;token.actions.githubusercontent.com:sub&quot;<br>      values   = [&quot;repo:${local.gh_owner}/${local.gh.repository_name}:ref:refs/heads/*&quot;]<br>    }<br>    condition {<br>      test     = &quot;StringEquals&quot;<br>      variable = &quot;token.actions.githubusercontent.com:aud&quot;<br>      values   = [&quot;sts.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br>## Github - IAM role<br>resource &quot;aws_iam_role&quot; &quot;warike_development_github_iam_role&quot; {<br>  name               = &quot;github-iam-role-${local.project_name}&quot;<br>  description        = &quot;IAM role for github actions to interact with AWS resources&quot;<br>  assume_role_policy = data.aws_iam_policy_document.warike_development_github_oidc.json<br>}<br>## IAM Policy for Github workflow<br>data &quot;aws_iam_policy_document&quot; &quot;warike_development_github_workflow&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br>    actions = [<br>      &quot;ecr:GetAuthorizationToken&quot;<br>    ]<br>    resources = [&quot;*&quot;]<br>  }<br>  statement {<br>    actions = [<br>      &quot;ecr:BatchCheckLayerAvailability&quot;,<br>      &quot;ecr:GetDownloadUrlForLayer&quot;,<br>      &quot;ecr:BatchGetImage&quot;,<br>      &quot;ecr:PutImage&quot;,<br>      &quot;ecr:InitiateLayerUpload&quot;,<br>      &quot;ecr:UploadLayerPart&quot;,<br>      &quot;ecr:CompleteLayerUpload&quot;,<br>      &quot;ecr:ListImages&quot;,<br>      &quot;ecr:DescribeImages&quot;,<br>      &quot;ecr:GetLifecyclePolicy&quot;,<br>      &quot;ecr:GetLifecyclePolicyPreview&quot;,<br>      &quot;ecr:GetRepositoryPolicy&quot;,<br>      &quot;ecr:DescribeRepositories&quot;,<br>      &quot;ecr:ListRepositories&quot;<br>    ]<br>    effect = &quot;Allow&quot;<br>    resources = [<br>      aws_ecr_repository.warike_development_ecr.arn,<br>      &quot;arn:aws:ecr:${local.aws_region}:${data.aws_caller_identity.current.account_id}:repository/${local.gh_owner}/${local.gh.repository_name}&quot;,<br>    ]<br>  }<br>  statement {<br>    effect = &quot;Allow&quot;<br>    actions = [<br>      &quot;lambda:UpdateFunctionCode&quot;,<br>      &quot;lambda:GetFunction&quot;,<br>      &quot;lambda:GetFunctionConfiguration&quot;<br>    ]<br>    resources = [<br>      aws_lambda_function.warike_development_lambda.arn<br>    ]<br>  }<br>  statement {<br>    effect = &quot;Allow&quot;<br>    actions = [<br>      &quot;iam:PassRole&quot;<br>    ]<br>    resources = [<br>      aws_iam_role.warike_development_lambda_role.arn<br>    ]<br>  }<br>}<br><br>## Github - IAM Policy<br>resource &quot;aws_iam_policy&quot; &quot;warike_developmente_ecr_iam_policy&quot; {<br>  # config<br>  name        = &quot;ecr-policy-${local.project_name}&quot;<br>  description = &quot;Allows github actions to pull and push images ECR, and lambda updates&quot;<br>  policy      = data.aws_iam_policy_document.warike_development_github_workflow.json<br>}<br><br>## Attach policy to role<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;warike_development_github_iam_policy_attachment&quot; {<br>  role       = aws_iam_role.warike_development_github_iam_role.name<br>  policy_arn = aws_iam_policy.warike_developmente_ecr_iam_policy.arn<br>}<br><br></pre><p>We apply the changes using Terraform.</p><pre>terraform apply<br>...<br>Apply complete! Resources: 27 added, 0 changed, 0 destroyed.</pre><p>With all the pieces in place, we can create the pipeline.</p><pre>name: CI - Mastra workflow<br><br>on:<br>  push:<br>    branches: [main, master]<br>    paths:<br>      - &#39;workflow/**&#39;      <br>      - &#39;.github/workflows/**&#39;<br>  pull_request:<br>    branches: [main, master]<br>    paths:<br>      - &#39;workflow/**&#39;<br>      - &#39;.github/workflows/**&#39;<br>env:<br>  NODE_VERSION: 22<br>  PNPM_VERSION: 10<br>  AWS_REGION: ${{ secrets.AWS_REGION }}<br>  ECR_REPOSITORY: ${{ secrets.AWS_ECR_REPOSITORY }}<br>  PROJECT_NAME: ${{ secrets.PROJECT_NAME }}<br>  AWS_ROLE_ARN: ${{ secrets.AWS_IAM_ROLE_ARN }}<br>  AWS_LAMBDA_FUNCTION_NAME: ${{ secrets.AWS_LAMBDA_FUNCTION_NAME }}<br>  AWS_LAMBDA_FUNCTION_ROLE_ARN: ${{ secrets.AWS_LAMBDA_FUNCTION_ROLE_ARN }}<br><br>jobs:<br>  tests:<br>    name: Test workflow<br>    runs-on: ubuntu-latest<br>    <br>    defaults:<br>      run:<br>        working-directory: ./workflow<br>    <br>    strategy:<br>      matrix:<br>        node-version: [22]<br>        pnpm-version: [10]<br>    steps:<br>      - name: Checkout Repository<br>        uses: actions/checkout@v4<br>      <br>      - name: Install pnpm<br>        uses: pnpm/action-setup@v4<br>        with:<br>          version: ${{ matrix.pnpm-version }}<br>      <br>      - name: Use Node.js ${{ matrix.node-version }}<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: ${{ matrix.node-version }}<br>          cache: &#39;pnpm&#39;<br>          cache-dependency-path: workflow/pnpm-lock.yaml<br>      <br>      - name: Install Dependencies<br>        run: pnpm install --frozen-lockfile<br>  <br>      - name: Scan for critical vulnerabilities<br>        run: pnpm audit --audit-level=critical<br>  <br>      - name: Run Tests<br>        env:<br>          DOTENV_QUIET: true<br>          GOOGLE_GENERATIVE_AI_API_KEY: &quot;example-api-key&quot;<br>        run: pnpm test:ci<br>  build:      <br>    name: Build workflow<br>    needs: tests<br>    runs-on: ubuntu-latest<br><br>    defaults:<br>      run:<br>        working-directory: ./workflow<br>    <br>    strategy:<br>      matrix:<br>        node-version: [22]<br>        pnpm-version: [10]<br><br>    steps:<br>      - name: Checkout Repository<br>        uses: actions/checkout@v4<br><br>      - name: Install pnpm<br>        uses: pnpm/action-setup@v4<br>        with:<br>          version: ${{ matrix.pnpm-version }}<br><br>      - name: Use Node.js ${{ matrix.node-version }}<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: ${{ matrix.node-version }}<br>          cache: &#39;pnpm&#39;<br>          cache-dependency-path: workflow/pnpm-lock.yaml<br>          <br>      - name: Install Dependencies<br>        run: pnpm install --frozen-lockfile<br>        <br>      - name: Build<br>        working-directory: ./workflow<br>        run: pnpm run build<br>  build-docker:<br>    name: Build Docker image<br>    needs: build<br>    runs-on: ubuntu-latest<br>    outputs:<br>      sha: ${{ steps.vars.outputs.sha }}<br>    permissions:<br>      id-token: write<br>      contents: read<br><br>    steps:<br>      - name: Checkout Repository<br>        uses: actions/checkout@v4<br><br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          role-to-assume: ${{ env.AWS_ROLE_ARN }}<br>          aws-region: ${{ env.AWS_REGION }}<br>      - name: Login to Amazon ECR<br>        id: login-ecr<br>        uses: aws-actions/amazon-ecr-login@v1<br>        with:<br>          mask-password: &#39;true&#39;<br>      <br>      - name: Set commit-sha<br>        id: vars<br>        run: |<br>          calculatedSha=$(git rev-parse --short ${{ github.sha }})<br>          echo &quot;sha=${calculatedSha}&quot; &gt;&gt; $GITHUB_OUTPUT<br>          <br>      - name: Build image and push to ECR<br>        working-directory: ./workflow<br>        env:<br>          DOCKER_IMAGE: ${{env.ECR_REPOSITORY}}:${{steps.vars.outputs.sha}}<br>        run: |<br>          echo &quot;Building ${{env.DOCKER_IMAGE}}&quot;<br>          docker build -t ${{env.DOCKER_IMAGE}} .<br>          docker tag &quot;${{env.DOCKER_IMAGE}}&quot; &quot;${{env.ECR_REPOSITORY}}:latest&quot;<br>          docker push ${{env.DOCKER_IMAGE}}<br>          docker push &quot;${{env.ECR_REPOSITORY}}:latest&quot;<br>  deploy-lambda:<br>    name: Deploy workflow<br>    runs-on: ubuntu-latest<br>    needs: build-docker<br>    permissions:<br>      id-token: write<br>      contents: read<br>    <br>    defaults:<br>      run:<br>        working-directory: ./workflow<br>    steps:<br>      - name: Checkout Repository<br>        uses: actions/checkout@v4<br><br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          role-to-assume: ${{ env.AWS_ROLE_ARN }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Deploy Lambda Function<br>        uses: aws-actions/aws-lambda-deploy@v1.1.0<br>        with:<br>          function-name: ${{ env.AWS_LAMBDA_FUNCTION_NAME }}<br>          package-type: Image<br>          image-uri: ${{ env.ECR_REPOSITORY }}:${{ needs.build-docker.outputs.sha }}<br>          role:  ${{ env.AWS_LAMBDA_FUNCTION_ROLE_ARN }}</pre><p>I’ll use <a href="https://github.com/nektos/act">Act</a> to test everything locally and ensure it’s working correctly.</p><pre>$ act -j build --container-architecture linux/amd64<br>...<br>[CI - Mastra workflow/Build workflow] Cleaning up container for job Build workflow<br>[CI - Mastra workflow/Build workflow]   ✅  Success - Complete job<br>[CI - Mastra workflow/Build workflow] 🏁  Job succeeded</pre><p>By committing our changes, we can verify that everything is operational.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bebk72xx1KblFm55BGWEQg.png" /></figure><h3>Testing</h3><p>There are different ways to test; the most straightforward is to verify that the Lambda function is invoked. That means we should be able to see the function we created in the AWS console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ng1h6l2aSOweWWemhs_1yQ.png" /></figure><p>We can use the test event functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqfTvUdCEaml_8Ph94KTrg.png" /></figure><p>And check the logs in CloudWatch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NjaGxwvg6UBjksYRZ5wgtQ.png" /></figure><p>I see this as a successful implementation.</p><h3>Cost breakdown</h3><p>Let’s consider <strong>1,000 emails per month</strong> and take a look at the costs of each service.</p><h4><strong>AWS Lambda</strong></h4><p>One run per month, the usage is so low it doesn’t even come close to the free tier limits of 1 million requests and 400,000 GB-seconds of compute time. <strong>Cost: $0.00</strong></p><h4><strong>Amazon SES</strong></h4><p>Sending about 30,000 emails a month by a Lambda function, we get a special free tier that includes 62,000 emails per month. This easily covers our usage. <strong>Cost: $0.00</strong></p><h4><strong>Amazon EventBridge</strong></h4><p>This service runs the schedule that kicks off our function once a month. This kind of minimal usage is completely free. <strong>Cost: $0.00</strong></p><h4><strong>Amazon CloudWatch</strong></h4><p>Aa single 36 KB log file per event, it stays within the free 5 GB of log storage. <strong>Cost: $0.00</strong></p><h4><strong>AWS Systems Manager Parameter Store</strong></h4><p>Storing three simple parameters is free. <strong>Cost: $0.00</strong></p><p>Based on the usage breakdown, the total estimated monthly cost for this architecture should be $0.00.</p><p>Please notice that <strong>I am not considering inference costs</strong>.</p><h3>Conclusions</h3><p>Overall, deploying a basic agentic workflow using Mastra was quite straightforward. Even without diving into the specifics of what the agent generates, it’s clear that AWS provides deployment conveniences, and Mastra ensures seamless integration.</p><p>It’s important to note that, in this setup, all the logic is packaged into a single Lambda. This limits our ability to fully leverage Lambda’s scaling features when using Mastra’s .foreach() function.</p><p>An alternative approach would be to break the workflow into separate parts, taking advantage of Mastra features like nested workflows, and suspend &amp; resume.</p><p>Nevertheless, after implementing the Mastra workflow, it’s clear that by leveraging tools like Terraform for infrastructure management, Docker for application packaging, and GitHub Actions for deployment automation, a robust, scalable, and fully integrated solution within the AWS ecosystem can be achieved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7084fcc4cac7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/warike/how-to-automate-a-mastra-workflow-in-lambda-using-eventbridge-7084fcc4cac7">How to automate a Mastra Workflow in Lambda Using EventBridge</a> was originally published in <a href="https://medium.com/warike">Warike technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>