<?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 Gkimari on Medium]]></title>
        <description><![CDATA[Stories by Gkimari on Medium]]></description>
        <link>https://medium.com/@gkimari041?source=rss-c5ecb2d107c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ITNxhASm9xb-nnP2</url>
            <title>Stories by Gkimari on Medium</title>
            <link>https://medium.com/@gkimari041?source=rss-c5ecb2d107c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:22:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gkimari041/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[Ditching Long-Lived AWS Keys: How I Set Up IAM Roles Anywhere for a Backup Server]]></title>
            <link>https://medium.com/@gkimari041/ditching-long-lived-aws-keys-how-i-set-up-iam-roles-anywhere-for-a-backup-server-4fd2ded9a67c?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fd2ded9a67c</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 20:36:46 GMT</pubDate>
            <atom:updated>2026-07-31T20:36:46.888Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem</h3><p>Like a lot of teams, we had an on-premises (or non-AWS) server that needed to write backup files to an S3 bucket. The quick-and-dirty solution is always the same: create an IAM user, generate an access key pair, and drop it into a config file somewhere on the server.</p><p>The problem is that this approach means:</p><ul><li>A long-lived credential sitting on a disk, waiting to be leaked in a log file, a git commit, or a stolen backup image</li><li>No automatic expiration — the key works until someone remembers to rotate it</li><li>No easy way to scope permissions tightly without creating a sprawl of IAM users</li></ul><p>I wanted the same flexibility and security model we use <em>inside</em> AWS — IAM roles with scoped policies and short-lived credentials — but for a machine that lives outside AWS. That’s exactly what <strong>AWS IAM Roles Anywhere</strong> is built for.</p><h3>What I Built</h3><p>A backup server (simulated here with an EC2 instance to keep the lab self-contained, but the process is identical for a real on-prem box) that:</p><ol><li>Authenticates to AWS using an X.509 client certificate instead of a static access key</li><li>Assumes an IAM role scoped down to <strong>write-only</strong> access on a single S3 bucket</li><li>Gets temporary credentials that expire automatically (as short as 15 minutes)</li><li>Can have its access revoked instantly via a Certificate Revocation List if the certificate is ever compromised</li></ol><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hsz5-jTKrwwrjXij.png" /></figure><h3>Prerequisites</h3><ul><li>An AWS account (or role/permissions to create IAM resources)</li><li>A certificate authority — I used a self-signed CA for testing, but in production you’d use <strong>AWS Private CA</strong> or your organization’s existing PKI</li><li>OpenSSL installed on the client machine</li><li>The AWS CLI installed on the client machine</li><li>jq for parsing JSON responses (optional but makes life easier)</li></ul><h3>Step 1: Generate a Client Certificate and Key</h3><p>Every workload authenticating via Roles Anywhere needs an X.509 certificate signed by a CA that AWS trusts (via a “trust anchor,” covered in Step 3).</p><p>For testing, I generated a root CA and used it to sign a client certificate:</p><pre># Generate a client key and certificate signing request<br>openssl req \<br>    -nodes \<br>    -new \<br>    -keyout client-key.pem \<br>    -out client-csr.pem \<br>    -config client.conf# Sign the CSR with the root CA to produce the client certificate<br>openssl x509 \<br>    -req \<br>    -in client-csr.pem \<br>    -CA root-cert.pem \<br>    -CAkey root-key.pem \<br>    -set_serial 2 \<br>    -out client-cert.pem \<br>    -days 365 \<br>    -sha256 \<br>    -extfile client.conf \<br>    -extensions v3</pre><blockquote><strong><em>Production note:</em></strong><em> Don’t use a self-signed CA in production. Use </em><strong><em>AWS Private CA</em></strong><em> (a managed CA-as-a-service) or plug into your organization’s existing certificate infrastructure. AWS Private CA is a regional service, so if you need it in multiple regions, you’ll create a CA per region.</em></blockquote><h3>Step 2: Create the IAM Role</h3><p>This is a normal IAM role, just with a different trusted entity:</p><ol><li>Go to <strong>IAM → Roles → Create role</strong></li><li>Trusted entity type: <strong>AWS Service</strong></li><li>Use case: <strong>Roles Anywhere</strong></li><li>Attach a policy — start broad if needed for testing (e.g. AmazonS3FullAccess), then narrow it down using a <strong>profile</strong> (Step 4)</li><li>Name the role something descriptive, e.g. backup-role</li><li>Save the role’s ARN — you’ll need it later</li></ol><p>The trust policy generated here allows AWS STS to hand out temporary credentials to anything presenting a valid certificate from your trust anchor. You can further restrict this in the trust policy to specific certificate subject names or organizations.</p><h3>Step 3: Create a Trust Anchor</h3><p>The trust anchor tells AWS “trust certificates issued by this CA.”</p><ol><li>Go to <strong>IAM → Roles Anywhere → Create a trust anchor</strong></li><li>Give it a name</li><li>Certificate authority source: <strong>External certificate bundle</strong> (if using a self-signed/external CA) or select your <strong>AWS Private CA</strong></li><li>Paste in the full contents of your root certificate, including the -----BEGIN CERTIFICATE----- / -----END CERTIFICATE----- lines</li><li>Save the trust anchor’s ARN</li></ol><blockquote><em>Roles Anywhere is a </em><strong><em>regional</em></strong><em> service, unlike IAM itself, so make sure you’re working in the correct region throughout.</em></blockquote><h3>Step 4: Create a Profile to Scope Down Permissions</h3><p>A <strong>profile</strong> is what actually restricts what the assumed role can do, independent of the full policy attached to the role. This is where the real least-privilege enforcement happens.</p><p>For my backup use case, I created a profile with a policy that allows <strong>only </strong><strong>s3:PutObject</strong> on the target bucket — nothing else. Even though the underlying role has a broader policy attached, the profile clamps it down to write-only.</p><p>Save the profile’s ARN.</p><h3>Step 5: Generate Temporary Credentials on the Client</h3><p>On the client server (no AWS credentials configured at all), download the AWS-provided signing helper:</p><pre>wget https://your-source/aws_signing_helper<br>chmod +x aws_signing_helper</pre><p>Then request temporary credentials, referencing the certificate, role, trust anchor, and profile:</p><pre>./aws_signing_helper credential-process \<br>    --certificate client-cert.pem \<br>    --private-key client-key.pem \<br>    --role-arn &lt;ROLE-ARN&gt; \<br>    --trust-anchor-arn &lt;TRUST-ANCHOR-ARN&gt; \<br>    --profile-arn &lt;PROFILE-ARN&gt; | jq</pre><p>This returns short-lived AccessKeyId, SecretAccessKey, and SessionToken values — no different in shape from any other STS-issued credentials.</p><h3>Step 6: Wire the Credentials into the AWS CLI</h3><p>For testing, I exported them directly as environment variables:</p><pre>CREDENTIALS=$(./aws_signing_helper credential-process ... | jq)</pre><pre>export AWS_ACCESS_KEY_ID=$(echo $CREDENTIALS | jq -r .AccessKeyId)<br>export AWS_SECRET_ACCESS_KEY=$(echo $CREDENTIALS | jq -r .SecretAccessKey)<br>export AWS_SESSION_TOKEN=$(echo $CREDENTIALS | jq -r .SessionToken)</pre><p>In a real deployment, you’d typically wire the signing helper into the AWS SDK’s credential_process configuration so this happens automatically and refreshes on expiry, rather than exporting variables by hand.</p><p>Verify it worked:</p><pre>aws sts get-caller-identity</pre><p>The returned ARN should show the assumed role, confirming the on-prem machine is now acting as that IAM role.</p><h3>Step 7: Test the Scoped Access</h3><pre>echo &quot;test backup file&quot; &gt; hello.txt<br>aws s3 cp hello.txt s3://your-backup-bucket/</pre><p>Upload succeeds. Now try to list the bucket:</p><pre>aws s3 ls s3://your-backup-bucket/</pre><p>This should be <strong>denied</strong> — the profile restricted the role to write-only, even though the role’s attached policy technically allows full S3 access. This is the least-privilege enforcement doing its job.</p><h3>Operational Notes</h3><ul><li><strong>Session duration</strong> is configurable between 15 minutes and 1 hour — pick based on how long your workload realistically needs a session.</li><li><strong>Revocation:</strong> if a certificate/key is ever compromised, add it to a Certificate Revocation List (CRL) tied to the trust anchor. Roles Anywhere stops issuing credentials for that certificate immediately.</li><li><strong>Auditing:</strong> every credential issuance is logged in <strong>AWS CloudTrail</strong> as a CreateSession event, so you get a full audit trail of which certificate requested credentials and when.</li></ul><h3>Next Steps</h3><ul><li>Automate certificate issuance and rotation using AWS Private CA instead of a self-signed CA</li><li>Integrate the signing helper with the AWS SDK’s credential_process so applications don&#39;t need manual credential export</li><li>Extend the trust policy with certificate subject/organization conditions to further restrict which certificates can assume the role</li></ul><p><em>Feel free to adapt the bucket names, role names, and policies above to your own environment — the structure and sequence of steps stays the same regardless of the specific workload you’re securing.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fd2ded9a67c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Built an AI That Reads Your Company’s Messy PDFs (So You Don’t Have To)]]></title>
            <link>https://medium.com/@gkimari041/we-built-an-ai-that-reads-your-companys-messy-pdfs-so-you-don-t-have-to-ae8e8c8d6e23?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae8e8c8d6e23</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-ai-services]]></category>
            <category><![CDATA[aws-sqs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-vpc]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 21:17:17 GMT</pubDate>
            <atom:updated>2026-07-09T21:17:17.216Z</atom:updated>
            <content:encoded><![CDATA[<p>Your boss hands you a folder containing 50 different PDFs — each 100 pages long — covering company insurance policies, compliance rules, and technical manuals. Then they say, <em>“Hey, look through these and tell me if our health plan covers acupuncture for remote workers by 5:00 PM.”</em></p><p>Panic sets in. You can’t read 5,000 pages in an afternoon. You try using Ctrl + F, but the keyword is buried, or worse, written as &quot;alternative holistic medicine&quot; instead of &quot;acupuncture.&quot;</p><p>This is a massive, real-world headache for businesses everywhere. Companies waste millions of hours searching for information trapped inside chaotic internal documents. Large Language Models (LLMs) like ChatGPT or Claude could help, but they don’t know your company’s private secrets — they only know what’s on the public internet.</p><p>To bridge this gap, we built a smart <strong>PDF Chatbot</strong> using a cutting-edge AI trick called <strong>RAG (Retrieval-Augmented Generation)</strong>. It gives an AI a “temporary brain” filled purely with your private company documents, allowing anyone to chat with their PDFs like a helpful colleague.</p><h3>The Magic Blueprint: How the System Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHR7a_kzKbyb6_7IXFNwIA.png" /></figure><p>To keep the application fast and reliable, we split it into two distinct parts: <strong>The Document Factory</strong> (which processes data quietly in the background) and <strong>The Customer Front Desk</strong> (the chat application users interact with).</p><p>Here is how a file travels through our cloud pipeline:</p><ol><li><strong>The Upload:</strong> A user uploads a PDF. It lands safely in an <strong>Amazon S3</strong> storage bucket.</li><li><strong>The Alarm:</strong> The moment the file lands, it trips a digital tripwire. This triggers our first <strong>AWS Lambda</strong> worker function (ExtractMetadata), which notes down the file&#39;s name and size in a <strong>DynamoDB</strong> tracking spreadsheet.</li><li><strong>The Assembly Line:</strong> To make sure the system doesn’t crash if 1,000 people upload files at once, the file is put into a waiting line called an <strong>SQS Queue</strong>.</li><li><strong>The AI Brain-Maker:</strong> A second worker function (GenerateEmbeddings) picks up the file from the queue. It cuts the long PDF into tiny, bite-sized text chunks and sends them to <strong>Amazon Bedrock</strong>. Bedrock translates these human words into numerical vectors (math formulas that represent what the words actually <em>mean</em>).</li><li><strong>The Chat Interface:</strong> The user logs onto a beautiful, simple webpage built with <strong>Streamlit</strong> (hosted on an <strong>Amazon ECS</strong> container). They type: <em>“Do we cover acupuncture?”</em> The app looks up the mathematical meanings, grabs the exact page from the document, feeds it to the AI, and spits out the perfect answer in seconds.</li></ol><h3>Part 2: The Complete Terraform Blueprint</h3><p>Create a clean directory and organize your files. To make it simple yet robust, you can place this into a single main.tf file (or split it into variables.tf, iam.tf, and outputs.tf later).</p><h3>1. Provider and Variables</h3><p>Terraform</p><pre>terraform {<br>  required_version = &quot;&gt;= 1.5.0&quot;<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>}<br>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}<br>variable &quot;aws_region&quot; {<br>  type    = string<br>  default = &quot;us-east-1&quot;<br>}<br>variable &quot;environment&quot; {<br>  type    = string<br>  default = &quot;dev&quot;<br>}</pre><h3>2. S3 Bucket, SQS Queue, and DynamoDB Table</h3><p>Terraform</p><pre># Storage S3 Bucket<br>resource &quot;aws_s3_bucket&quot; &quot;pdf_bucket&quot; {<br>  bucket        = &quot;rag-pdf-ingestion-bucket-${var.environment}&quot;<br>  force_destroy = true<br>}<br># DynamoDB Metadata Table<br>resource &quot;aws_dynamodb_table&quot; &quot;docs_table&quot; {<br>  name         = &quot;DocumentsTable-${var.environment}&quot;<br>  billing_mode = &quot;PAY_PER_REQUEST&quot;<br>  hash_key     = &quot;document_id&quot;<br>  attribute {<br>    name = &quot;document_id&quot;<br>    type = &quot;S&quot;<br>  }<br>}<br># Dead Letter Queue (DevOps Practice: Always capture failed events)<br>resource &quot;aws_sqs_queue&quot; &quot;embedding_dlq&quot; {<br>  name = &quot;pdf-embedding-dlq-${var.environment}&quot;<br>}<br># Main SQS Queue<br>resource &quot;aws_sqs_queue&quot; &quot;embedding_queue&quot; {<br>  name                       = &quot;pdf-embedding-queue-${var.environment}&quot;<br>  visibility_timeout_seconds = 300 # Match or exceed Lambda timeout<br>  redrive_policy = jsonencode({<br>    deadLetterTargetArn = aws_sqs_queue.embedding_dlq.arn<br>    maxReceiveCount     = 3<br>  })<br>}</pre><h3>3. IAM Roles &amp; Policies (Least Privilege)</h3><p>Terraform</p><pre># IAM Role Template for Lambdas<br>resource &quot;aws_iam_role&quot; &quot;lambda_role&quot; {<br>  name = &quot;rag-lambda-execution-role-${var.environment}&quot;<br>assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Action    = &quot;sts:AssumeRole&quot;<br>      Effect    = &quot;Allow&quot;<br>      Principal = { Service = &quot;lambda.amazonaws.com&quot; }<br>    }]<br>  })<br>}<br># Core Policy for Lambda Ingestion Operations<br>resource &quot;aws_iam_policy&quot; &quot;lambda_policy&quot; {<br>  name = &quot;rag-lambda-policy-${var.environment}&quot;<br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [&quot;logs:CreateLogGroup&quot;, &quot;logs:CreateLogStream&quot;, &quot;logs:PutLogEvents&quot;]<br>        Resource = &quot;arn:aws:logs:*:*:*&quot;<br>      },<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [&quot;s3:GetObject&quot;, &quot;s3:ListBucket&quot;]<br>        Resource = [&quot;${aws_s3_bucket.pdf_bucket.arn}&quot;, &quot;${aws_s3_bucket.pdf_bucket.arn}/*&quot;]<br>      },<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [&quot;dynamodb:PutItem&quot;, &quot;dynamodb:UpdateItem&quot;, &quot;dynamodb:GetItem&quot;]<br>        Resource = aws_dynamodb_table.docs_table.arn<br>      },<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [&quot;sqs:SendMessage&quot;, &quot;sqs:ReceiveMessage&quot;, &quot;sqs:DeleteMessage&quot;, &quot;sqs:GetQueueAttributes&quot;]<br>        Resource = [aws_sqs_queue.embedding_queue.arn, aws_sqs_queue.embedding_dlq.arn]<br>      },<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [&quot;bedrock:InvokeModel&quot;]<br>        Resource = &quot;*&quot; # Bedrock requires * for foundational model access<br>      }<br>    ]<br>  })<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_attach&quot; {<br>  role       = aws_iam_role.lambda_role.name<br>  policy_arn = aws_iam_policy.lambda_policy.arn<br>}</pre><h3>4. Lambda Pipeline Implementation</h3><p><em>Note: Ensure you have local zip packages (</em><em>extract.zip and </em><em>embed.zip) or point these to your packaged deployment build zip locations.</em></p><p>Terraform</p><pre># Lambda 1: Extract Metadata<br>resource &quot;aws_lambda_function&quot; &quot;extract_metadata&quot; {<br>  filename      = &quot;extract.zip&quot; # Path to your zipped python code<br>  function_name = &quot;ExtractMetadata-${var.environment}&quot;<br>  role          = aws_iam_role.lambda_role.arn<br>  handler       = &quot;index.handler&quot;<br>  runtime       = &quot;python3.11&quot;<br>  timeout       = 60<br>environment {<br>    variables = {<br>      QUEUE_URL  = aws_sqs_queue.embedding_queue.url<br>      TABLE_NAME = aws_dynamodb_table.docs_table.name<br>    }<br>  }<br>}<br># Lambda S3 Trigger Permissions<br>resource &quot;aws_lambda_permission&quot; &quot;allow_s3&quot; {<br>  statement_id  = &quot;AllowExecutionFromS3&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.extract_metadata.function_name<br>  principal     = &quot;s3.amazonaws.com&quot;<br>  source_arn    = aws_s3_bucket.pdf_bucket.arn<br>}<br># S3 Event Link configuration<br>resource &quot;aws_s3_bucket_notification&quot; &quot;bucket_notification&quot; {<br>  bucket = aws_s3_bucket.pdf_bucket.id<br>  lambda_function {<br>    lambda_function_arn = aws_lambda_function.extract_metadata.arn<br>    events              = [&quot;s3:ObjectCreated:*&quot;]<br>    filter_suffix       = &quot;.pdf&quot;<br>  }<br>  depends_on = [aws_lambda_permission.allow_s3]<br>}<br># Lambda 2: Generate Embeddings<br>resource &quot;aws_lambda_function&quot; &quot;generate_embeddings&quot; {<br>  filename      = &quot;embed.zip&quot; <br>  function_name = &quot;GenerateEmbeddings-${var.environment}&quot;<br>  role          = aws_iam_role.lambda_role.arn<br>  handler       = &quot;index.handler&quot;<br>  runtime       = &quot;python3.11&quot;<br>  timeout       = 180<br>  environment {<br>    variables = {<br>      TABLE_NAME = aws_dynamodb_table.docs_table.name<br>    }<br>  }<br>}<br># SQS to Lambda Mapping<br>resource &quot;aws_lambda_event_source_mapping&quot; &quot;sqs_trigger&quot; {<br>  event_source_arn = aws_sqs_queue.embedding_queue.arn<br>  function_name    = aws_lambda_function.generate_embeddings.arn<br>  batch_size       = 5<br>}</pre><h3>5. Elastic Container Service (ECS) Web Application Layer</h3><p>Terraform</p><pre># ECS Cluster<br>resource &quot;aws_ecs_cluster&quot; &quot;rag_cluster&quot; {<br>  name = &quot;rag-ecs-cluster-${var.environment}&quot;<br>}<br># ECR Container Repository<br>resource &quot;aws_ecr_repository&quot; &quot;app_repo&quot; {<br>  name                 = &quot;rag-chatbot-app&quot;<br>  image_tag_mutability = &quot;MUTABLE&quot;<br>  image_scanning_configuration { scan_on_push = true } # DevOps security check<br>}<br># IAM Role for ECS Task execution<br>resource &quot;aws_iam_role&quot; &quot;ecs_execution_role&quot; {<br>  name = &quot;rag-ecs-execution-role-${var.environment}&quot;<br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{ Action = &quot;sts:AssumeRole&quot;, Effect = &quot;Allow&quot;, Principal = { Service = &quot;ecs-tasks.amazonaws.com&quot; }}]<br>  })<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs_execution&quot; {<br>  role       = aws_iam_role.ecs_execution_role.name<br>  policy_arn = &quot;arn:aws:iam:aws:policy/service-role/AmazonECSTaskExecutionRolePolicy&quot;<br>}<br># ECS Task Definition (Fargate Container Specifications)<br>resource &quot;aws_ecs_task_definition&quot; &quot;streamlit_task&quot; {<br>  family                   = &quot;streamlit-chat-task&quot;<br>  network_mode             = &quot;awsvpc&quot;<br>  requires_compatibilities = [&quot;FARGATE&quot;]<br>  cpu                      = &quot;512&quot;<br>  memory                   = &quot;1024&quot;<br>  execution_role_arn       = aws_iam_role.ecs_execution_role.arn<br>  task_role_arn            = aws_iam_role.lambda_role.arn # Reuse policy as it needs similar Bedrock/S3 access<br>  container_definitions = jsonencode([{<br>    name      = &quot;streamlit-container&quot;<br>    image     = &quot;${aws_ecr_repository.app_repo.repository_url}:latest&quot;<br>    essential = true<br>    portMappings = [{<br>      containerPort = 8501<br>      hostPort      = 8501<br>    }]<br>  }])<br>}</pre><h3>Deployment Guide</h3><p>Follow this CI/CD workflow sequence to safely provision your cloud resources using the code template provided:</p><h3>Step 1: Initialize Terraform</h3><p>Prepare your local setup, download provider plug-ins, and prepare the state ecosystem.</p><p>Bash</p><pre>terraform init</pre><h3>Step 2: Code Compilation &amp; Asset Staging</h3><p>Create dummy target packages (or substitute your actual application python zips) so Terraform can reference the source bundle payloads during resource initialization.</p><p>Bash</p><pre>echo &quot;def handler(event, context): pass&quot; &gt; index.py<br>zip extract.zip index.py<br>zip embed.zip index.p</pre><h3>Step 3: Preview the Plan</h3><p>Generate a visual confirmation strategy map of what changes will be safely committed into your target active AWS cloud environment.</p><p>Bash</p><pre>terraform plan</pre><h3>Step 4: Execute &amp; Apply Build</h3><p>Run the execution framework to cleanly construct all components simultaneously.</p><p>Bash</p><pre>terraform apply --auto-approve</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wn2w69foAqz_gJJ5lSKg3g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae8e8c8d6e23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guarding the Gates: Building an Automated AI Content Moderation Pipeline with SNS, SQS, and Amazon…]]></title>
            <link>https://medium.com/@gkimari041/guarding-the-gates-building-an-automated-ai-content-moderation-pipeline-with-sns-sqs-and-amazon-cea5598d1031?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cea5598d1031</guid>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 20:25:33 GMT</pubDate>
            <atom:updated>2026-06-24T20:25:33.226Z</atom:updated>
            <content:encoded><![CDATA[<h3>Guarding the Gates: Building an Automated AI Content Moderation Pipeline with SNS, SQS, and Amazon Bedrock</h3><p>Imagine running a rapidly growing online discussion forum or social media platform. Hundreds of pieces of text, user bios, and comments are uploaded every single minute. Now imagine the nightmare: a sudden influx of malicious spam links and leaked personally identifiable information (PII) — like phone numbers and credit card details — floods your platform.</p><p>This was the exact challenge our engineering team faced. Manual moderation couldn’t scale, and traditional keyword filtering was too rigid, throwing false positives left and right while missing clever spam variations.</p><p>We needed a system that could dynamically analyze context, flag bad content instantly, and scale gracefully without managing servers or introducing massive latency.</p><p>Our solution? A fully decoupled, serverless <strong>event-driven architecture</strong> that utilizes <strong>Amazon SNS</strong>, <strong>Amazon SQS</strong>, and an <strong>AWS Lambda</strong> function backed by the generative AI capabilities of <strong>Amazon Bedrock</strong>. Here is the story of how we built it, step by step.</p><h3>The Architecture at a Glance</h3><p>To solve this sustainably, we avoided a monolithic approach. Instead, we designed a pipeline where each component does one thing exceptionally well:</p><ol><li><strong>Ingestion:</strong> Text enters the system via an <strong>Amazon S3</strong> bucket.</li><li><strong>Decoupling:</strong> <strong>Amazon EventBridge</strong> notices the upload, notifies an <strong>Amazon SNS</strong> topic, which fans out to an <strong>Amazon SQS</strong> queue.</li><li><strong>Processing:</strong> <strong>AWS Lambda</strong> consumes messages from the queue asynchronously.</li><li><strong>Intelligence:</strong> Lambda calls <strong>Amazon Bedrock (Amazon Nova)</strong> to classify the text.</li><li><strong>Storage:</strong> The finalized, flagged data is saved to <strong>Amazon DynamoDB</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ybRLKwmrEcIhfWD3pLlyQ.png" /></figure><h3>Step 1: Link the Communication Channels (SNS &amp; SQS)</h3><p>First, we had to ensure our messaging layer was tightly wired so no data dropped during high-traffic spikes.</p><ul><li><strong>Create the Subscription:</strong> We navigated to <strong>Amazon SNS -&gt; Topics -&gt; content</strong> and clicked <strong>Create subscription</strong>. We set the protocol to <strong>Amazon SQS</strong> and mapped the endpoint directly to our dedicated content SQS queue.</li><li><strong>Establish the Lambda Trigger:</strong> Next, we opened our content SQS queue dashboard. Under the <strong>Lambda triggers</strong> tab, we clicked <strong>Configure Lambda function trigger</strong>, selected our processing Lambda function, and saved changes.</li></ul><p>By mapping the queue directly to Lambda as an event source, AWS automatically processes messages in efficient batches, saving computing costs.</p><h3>Step 2: Inject AI Brains into the Lambda Worker</h3><p>With our infrastructure components communicating, we wrote the core Python (boto3) logic inside our Lambda function to invoke Amazon Bedrock&#39;s <strong>Amazon Nova</strong> model.</p><p>We focused on building out two critical components: invoking the model and handling the database serialization.</p><h4>A. The Bedrock Invocation Function</h4><p>This block formats our raw prompt into the exact input payload structure expected by the Amazon Nova model, setting a low token threshold (max_new_tokens: 3) to force the model to answer with a definitive &quot;true&quot; or &quot;false&quot; instead of writing a lengthy explanation.</p><p>Python</p><pre>import json<br>import boto3<br>def invoke_bedrock(prompt):<br>    # Construct the native payload schema for Amazon Nova<br>    payload = {<br>        &quot;messages&quot;: [<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: [<br>                    {<br>                        &quot;text&quot;: prompt<br>                    }<br>                ]<br>            }<br>        ],<br>        &quot;inferenceConfig&quot;: {<br>            &quot;max_new_tokens&quot;: 3,<br>        }<br>    }<br>    <br>    body = json.dumps(payload)<br>    <br>    # Fire the request directly to the Bedrock runtime client<br>    response = bedrock_client.invoke_model(body=body, modelId=MODEL_ID)<br>    return json.loads(response.get(&quot;body&quot;).read())</pre><h4>B. The Content Classification Engine</h4><p>This block loops over arriving messages, swapping our text into pre-defined prompt templates (SPAM_PROMPT_TEMPLATE and PII_PROMPT_TEMPLATE), evaluating the model&#39;s response, and applying binary safety flags.</p><p>Python</p><pre>def classify_content(messages):<br>    for message in messages:<br>        # Task 1: Check for Spam<br>        message[&#39;spam&#39;] = False<br>        prompt = SPAM_PROMPT_TEMPLATE.replace(&quot;MESSAGE&quot;, message[&quot;message&quot;])<br>        response = invoke_bedrock(prompt)<br>        for result in response.get(&quot;results&quot;, []):<br>            if &quot;true&quot; in result[&#39;output&#39;][&#39;message&#39;][&#39;content&#39;][0][&#39;text&#39;].lower():<br>                message[&quot;spam&quot;] = True<br>                <br>        # Task 2: Check for PII leaks<br>        message[&#39;pii&#39;] = False<br>        prompt = PII_PROMPT_TEMPLATE.replace(&quot;MESSAGE&quot;, message[&quot;message&quot;])<br>        response = invoke_bedrock(prompt)<br>        for result in response.get(&quot;results&quot;, []):<br>            if &quot;true&quot; in result[&#39;output&#39;][&#39;message&#39;][&#39;content&#39;][0][&#39;text&#39;].lower():<br>                message[&quot;pii&quot;] = True<br>                <br>    return messages</pre><h4>C. Storing the Telemetry to DynamoDB</h4><p>Finally, we serialized the python dictionary structures using TypeSerializer to save the analyzed metadata cleanly into a NoSQL format.</p><p>Python</p><pre>from boto3.dynamodb.types import TypeSerializer<br>def upload_to_dynamodb(messages):<br>    serializer = TypeSerializer()<br>    for message in messages:<br>        # Convert Python types into explicit DynamoDB attribute values<br>        item = {key: serializer.serialize(value) for key, value in message.items()}<br>        dynamodb_client.put_item(Item=item, TableName=DYNAMODB_TABLE_NAME)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwlDGRnppPlphjkzXWebAQ.png" /></figure><h3>Step 3: Put the Pipeline to the Test</h3><p>To ensure our setup functioned in practice, we jumped into the terminal to simulate real-world user activity.</p><p>We generated a classic, high-velocity spam message and synchronized it up to our ingestion S3 bucket:</p><p>Bash</p><pre># Generate a unique text payload simulating a spam injection<br>echo &quot;Win a free iPhone! Click here to claim your prize.&quot; &gt; $(uuidgen).txt,<br># Sync the payload to our ingestion bucket<br>aws s3 sync --exclude &quot;*&quot; --include &quot;*.txt&quot; . s3://content-1782329502-qoigkg</pre><p>Within a few seconds, the event rippled smoothly through EventBridge, hit the SNS topic, landed in SQS, triggered our Lambda code, ran through Bedrock’s evaluation, and landed securely in DynamoDB.</p><p>We ran a scan command on our database table to verify the output:</p><p>Bash</p><pre>aws dynamodb scan --table-name content</pre><p><strong>The Final Result Payload:</strong></p><p>JSON</p><pre>{<br>    &quot;Items&quot;: [<br>        {<br>            &quot;content_id&quot;: {&quot;S&quot;: &quot;63a54b38-e6b7-4c8e-a2e1-7890bcadef12&quot;},<br>            &quot;message&quot;: {&quot;S&quot;: &quot;Win a free iPhone! Click here to claim your prize.&quot;},<br>            &quot;spam&quot;: {&quot;BOOL&quot;: true},<br>            &quot;pii&quot;: {&quot;BOOL&quot;: false}<br>        }<br>    ],<br>    &quot;Count&quot;: 1,<br>    &quot;ScannedCount&quot;: 1<br>}</pre><p>The system worked seamlessly! The text was immediately caught, contextualized, and marked as spam: true.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cea5598d1031" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Evaluated Generative AI Models Using Amazon Bedrock]]></title>
            <link>https://medium.com/@gkimari041/how-we-evaluated-generative-ai-models-using-amazon-bedrock-2f88aae57c04?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f88aae57c04</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-sagemaker]]></category>
            <category><![CDATA[awscommunitybuilder]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 19:10:07 GMT</pubDate>
            <atom:updated>2026-06-22T19:10:07.139Z</atom:updated>
            <content:encoded><![CDATA[<p>Choosing the right Large Language Model (LLM) for your business can feel like guesswork. How do you know if a model actually gives accurate answers before you deploy it to your users?</p><p>We recently faced this exact problem. We needed to test an AI model against a specific set of general knowledge questions to check its accuracy. Instead of testing prompts manually one by one, we used <strong>Amazon Bedrock</strong> to run an automated evaluation job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVUYMO-m98Rj8BMQY0J7GQ.png" /></figure><h3>Phase 1: Solving the Permission Problem (S3 CORS Setup)</h3><p>Before we could start evaluating, we had to lay the groundwork. We already had two Amazon S3 buckets set up:</p><ol><li>A <strong>prompt dataset bucket</strong> containing a file named prompt_dataset.json (holding test questions about chemistry, geography, and literature).</li><li>An <strong>output bucket</strong> to store the final evaluation reports.</li></ol><h3>The Hurdle</h3><p>By default, Amazon S3 buckets are locked down securely. Amazon Bedrock cannot look inside your S3 bucket to read your prompt dataset unless you explicitly give it permission. If you skip this, your evaluation job will fail immediately.</p><h3>The Solution: Adding a CORS Policy</h3><p>To fix this, we needed to configure Cross-Origin Resource Sharing (CORS) to grant Amazon Bedrock secure access.</p><p><strong>1.Locate Your Bucket:</strong>AWS S3 Console.</p><p>Open the Amazon S3 Console, look at your general purpose buckets, and click on your specific prompt dataset bucket.</p><p><strong>2.Navigate to Permissions:</strong>Bucket Tabs.</p><p>Click the Permissions tab at the top of the screen and scroll down to the Cross-origin resource sharing (CORS) section.</p><p><strong>3.Edit the CORS Configuration:</strong>Add Permissions JSON.</p><p>Click Edit and paste the following configuration code into the editor to allow external services to send safe requests to this bucket:</p><p>JSON</p><pre>[<br>  {<br>    &quot;AllowedHeaders&quot;: [&quot;*&quot;],<br>    &quot;AllowedMethods&quot;: [&quot;GET&quot;, &quot;PUT&quot;, &quot;POST&quot;, &quot;DELETE&quot;],<br>    &quot;AllowedOrigins&quot;: [&quot;*&quot;],<br>    &quot;ExposeHeaders&quot;: [&quot;Access-Control-Allow-Origin&quot;]<br>  }<br>]</pre><p><strong>4.Save Your Changes:</strong>Finalize Security.</p><p>Click Save changes at the bottom of the page. Now, Amazon Bedrock has a green light to read our dataset.</p><h3>Phase 2: Launching the Automated Evaluation Job</h3><p>With our storage permissions successfully resolved, we moved over to Amazon Bedrock to set up the actual evaluation testing engine.</p><h3>The Hurdle</h3><p>We wanted to evaluate <strong>Amazon’s Nova Micro</strong> model. We needed to choose a specific test metric (Accuracy) and link the engine directly to our newly prepared S3 input and output paths.</p><h3>The Solution: Creating the Evaluation Job</h3><p><strong>1.Open Amazon Bedrock:</strong>AWS Console Navigation.</p><p>Search for Amazon Bedrock in the top AWS search bar. Expand the left-hand menu, scroll down to the Assess section, and select Evaluations.</p><p><strong>2.Initiate Job Creation:</strong>Select Evaluation Type.</p><p>Click the button labeled Create Automatic: Programmatic to start configuring a computer-managed evaluation test.</p><p><strong>3.Configure Model and Task:</strong>Job Details.</p><p>Name your job (e.g., lab-job-123). Under Model Selector, choose Amazon as the provider and Nova Micro as the target model. Set the Task Type to Question and answer.</p><p><strong>4.Refine Your Metrics:</strong>Set to Accuracy.</p><p>Under Metrics and datasets, remove the excess default metrics until only Accuracy remains.</p><p><strong>5.Link S3 Data and Finalize:</strong>Assign Roles.</p><p>Select Use your own prompt dataset. Point the input path to your S3 folder containing prompt_dataset.json, and point the output path to your evaluation-results S3 folder. Select your pre-configured lab-bedrock IAM role, and click Create.</p><p>Once created, you will see your job running inside the <strong>Model Evaluation Jobs</strong> dashboard with a status of In progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19SrBkyLgwf1ihLJDuEITw.png" /></figure><h3>Phase 3: Making Sense of the Results</h3><p>After the evaluation job finishes processing (which usually takes about 10 minutes), Amazon Bedrock drops a JSON Lines (.jsonl) file directly into your output S3 bucket.</p><p>When we opened our results file, we noticed a major trend in how <strong>Nova Micro</strong> answered our simple questions. Here is an example piece of raw data from the output:</p><p>JSON</p><pre>{<br>  &quot;automatedEvaluationResult&quot;: {<br>    &quot;scores&quot;: [{ &quot;metricName&quot;: &quot;Builtin.Accuracy&quot;, &quot;result&quot;: 0.058823 }]<br>  },<br>  &quot;inputRecord&quot;: {<br>    &quot;prompt&quot;: &quot;The chemical symbol for gold is&quot;,<br>    &quot;referenceResponse&quot;: &quot;Au&quot;<br>  },<br>  &quot;modelResponses&quot;: [<br>    {<br>      &quot;response&quot;: &quot;The question asks for the chemical symbol of gold... For gold, the symbol is derived from its Latin name \&quot;aurum,\&quot; which is why the chemical symbol for gold is:\n\n**Au**&quot;,<br>      &quot;modelIdentifier&quot;: &quot;us.amazon.nova-micro-v1:0&quot;<br>    }<br>  ]<br>}</pre><h3>Breaking Down the Math: Why is the Accuracy Score Low?</h3><p>Looking at the file, you might initially panic because the accuracy score looks incredibly low (0.058 out of 1.0).</p><p><strong>Why did this happen?</strong></p><p>Amazon Bedrock evaluates textual accuracy using an <strong>F1 Score</strong> (a mathematical balance between precision and recall).</p><ul><li>Our expected target answer was short and sweet: <strong>“Au”</strong>.</li><li>The model gave a highly detailed, conversational response explaining the periodic table before finally concluding with <strong>“Au”</strong>.</li></ul><p>Because the model introduced a lot of extra conversational text instead of giving <em>just</em> the raw symbol, the overlapping word match ratio dropped.</p><blockquote><strong><em>Key Takeaway:</em></strong><em> A low accuracy score doesn’t automatically mean your model failed! It often means you need to adjust your prompt formatting instructions (like adding </em>“Answer in one word only”<em>) so the model’s response length matches your expected answer style.</em></blockquote><h3>Summary of Success</h3><p>By approaching this problem systematically, we successfully accomplished three key objectives:</p><ul><li><strong>Fixed Data Silos:</strong> Used S3 CORS rules so cloud services could talk to each other cleanly.</li><li><strong>Automated Testing:</strong> Scheduled a hands-off evaluation pipeline in Bedrock to test model accuracy over a structured dataset.</li><li><strong>Deciphered Performance Metrics:</strong> Learned how to read F1 accuracy scores to help us plan how to better prompt our models in the future.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f88aae57c04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Infrastructure for a Highly Available Web Application (Terraform, ALB, Auto Scaling)]]></title>
            <link>https://medium.com/@gkimari041/aws-infrastructure-for-a-highly-available-web-application-terraform-alb-auto-scaling-3fdb96df2600?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fdb96df2600</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[alb]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[autoscaling]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 08:02:37 GMT</pubDate>
            <atom:updated>2026-06-07T08:02:37.459Z</atom:updated>
            <content:encoded><![CDATA[<p>I designed and implemented a highly available web application infrastructure on AWS using <strong>Terraform (Infrastructure as Code)</strong>. The solution addressed critical reliability and cost inefficiencies in an existing environment by introducing <strong>multi-AZ architecture, load balancing, automated scaling, and scheduled capacity management</strong>.</p><p>The result was a resilient, self-healing system capable of handling variable traffic patterns while significantly reducing idle compute costs.</p><h3>Business Context</h3><p>A client-facing web application was experiencing recurring operational challenges:</p><ul><li>Intermittent downtime during traffic spikes</li><li>No automated scaling strategy</li><li>High infrastructure costs due to 24/7 EC2 provisioning</li><li>Manual and error-prone deployment processes</li></ul><p>The environment lacked elasticity and observability, resulting in poor reliability and inefficient resource utilization.</p><p>The objective was to redesign the infrastructure into a <strong>scalable, highly available, and cost-optimized cloud architecture</strong> using Infrastructure as Code.</p><h3>Technical Objectives</h3><ul><li>Architect a fault-tolerant system across multiple Availability Zones</li><li>Implement Infrastructure as Code using Terraform</li><li>Introduce load balancing to distribute traffic efficiently</li><li>Enable automatic scaling based on demand</li><li>Optimize cost through scheduled capacity adjustments</li><li>Eliminate manual infrastructure provisioning and configuration drift</li></ul><h3>Architecture Overview</h3><h3>High-Level System Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9eOp7AlTQHsOsE44Rg7Pw.png" /><figcaption>Diagram</figcaption></figure><h3>1. Infrastructure as Code (Terraform)</h3><p>The entire infrastructure was codified using Terraform to ensure:</p><ul><li>Declarative and version-controlled infrastructure</li><li>Repeatable deployments across environments</li><li>Reduced configuration drift</li><li>Faster recovery and rollback capabilities</li></ul><p>Core resources included:</p><ul><li>VPC networking components</li><li>Security groups</li><li>Launch templates</li><li>Application Load Balancer</li><li>Target groups</li><li>Auto Scaling Groups</li><li>Scheduled scaling policies</li></ul><h3>2. High Availability Architecture</h3><p>The system was deployed across multiple Availability Zones to eliminate single points of failure.</p><p>An <strong>Application Load Balancer (ALB)</strong> was introduced to:</p><ul><li>Distribute traffic across healthy EC2 instances</li><li>Perform continuous health checks</li><li>Improve fault tolerance and service continuity</li></ul><p>This significantly improved application resilience under load.</p><h3>3. Standardized Compute Layer (Launch Templates)</h3><p>A Launch Template was implemented to enforce consistency across EC2 instances:</p><ul><li>Amazon Linux 2 base image</li><li>Predefined instance configuration (t2.micro)</li><li>Automated bootstrapping via user data</li><li>Security group attachment for controlled HTTP access</li></ul><p>This eliminated manual server configuration and ensured consistency at scale.</p><h3>4. Elastic Scaling Strategy (Auto Scaling Group)</h3><p>An Auto Scaling Group was configured to manage compute capacity dynamically:</p><ul><li>Minimum capacity: 0</li><li>Desired capacity: 1</li><li>Maximum capacity: 1</li></ul><p>This allowed the environment to scale in response to demand while maintaining strict cost controls.</p><p>The ASG also ensured self-healing by replacing unhealthy instances automatically.</p><h3>5. Cost Optimization via Scheduled Scaling</h3><p>To align infrastructure usage with predictable business hours, scheduled scaling was implemented:</p><p>EventTime (UTC)ActionBusiness Start08:00Scale to 1 instanceBusiness End20:00Scale down to 0 instances</p><p>This introduced a <strong>predictable cost optimization model</strong>, eliminating unnecessary idle compute spend.</p><h3>Key Outcomes</h3><h3>Reliability Improvements</h3><ul><li>Eliminated single-instance dependency</li><li>Improved uptime through multi-AZ design and health-checked load balancing</li><li>Introduced automatic recovery via Auto Scaling</li></ul><h3>Operational Efficiency</h3><ul><li>Fully automated provisioning using Terraform</li><li>Removed manual deployment processes</li><li>Reduced configuration inconsistencies</li></ul><h3>Cost Optimization</h3><ul><li>Eliminated 24/7 compute waste</li><li>Introduced time-based scaling aligned to business usage patterns</li><li>Achieved significant reduction in idle resource consumption</li></ul><h3>Engineering Challenges &amp; Resolution</h3><p>A key challenge encountered involved <strong>IAM permission constraints during EC2 provisioning via Launch Templates</strong>. This required:</p><ul><li>Debugging Terraform execution roles and instance profiles</li><li>Reviewing AWS permission boundaries</li><li>Refining least-privilege IAM policies for compute resources</li></ul><p>This exercise reinforced the importance of <strong>secure-by-design infrastructure provisioning</strong> in production environments.</p><h3>Key Technical Takeaways</h3><ul><li>Infrastructure as Code is essential for scalable and repeatable cloud systems</li><li>Load balancing is foundational to designing resilient distributed applications</li><li>Auto Scaling must be aligned with real-world traffic behavior, not static assumptions</li><li>Cost efficiency is achieved through architecture design, not post-deployment optimization</li><li>Production-grade systems require automation, not manual intervention</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fdb96df2600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying High-Availability Network Load Balancers via Terraform]]></title>
            <link>https://medium.com/@gkimari041/deploying-high-availability-network-load-balancers-via-terraform-2c4627f390d9?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c4627f390d9</guid>
            <category><![CDATA[aws-networking]]></category>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[aws-load-balancer]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Tue, 19 May 2026 17:43:39 GMT</pubDate>
            <atom:updated>2026-05-19T17:47:15.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8hcgreZEF3-V4aE6fwYYw.png" /></figure><p>Modern cloud environments require scalable, fault-tolerant, and automated infrastructure capable of handling different types of traffic efficiently. In many organizations, infrastructure teams are responsible for deploying environments that support both application services and internal networking services such as DNS while maintaining high availability, observability, and infrastructure consistency.</p><p>This project focused on designing and deploying a production AWS networking environment using Terraform and core AWS networking services. The infrastructure was built entirely through Infrastructure as Code (IaC), simulating how a real cloud engineering or DevOps team would provision and manage cloud resources in a professional environment.</p><p>A growing organization needed a lightweight but scalable network infrastructure capable of handling both web traffic and DNS traffic through a centralized load balancing solution. The environment needed to support:</p><ul><li>Web application traffic over TCP port 80</li><li>DNS traffic over UDP port 53</li><li>Automated and repeatable infrastructure provisioning</li><li>Centralized logging and observability</li><li>Fault tolerance across multiple Availability Zones</li><li>Infrastructure consistency across deployments</li></ul><p>The engineering team also wanted to move away from manual console-based deployments and adopt Infrastructure as Code practices to improve scalability, operational consistency, and deployment speed.</p><p>The objective was to design and provision a fully functional AWS networking environment that included:</p><ul><li>Custom VPC networking</li><li>Public subnets across multiple Availability Zones</li><li>EC2 instances acting as DNS and web servers</li><li>A Network Load Balancer handling both TCP and UDP traffic</li><li>Multiple target groups with protocol-specific routing</li><li>Sticky sessions for web traffic</li><li>Centralized access logging to Amazon S3</li><li>Automated provisioning using Terraform</li></ul><p>The solution needed to resemble a real-world production deployment while remaining modular, scalable, and easy to maintain.</p><h3>Step 1 — Configuring the Terraform Provider</h3><p>The AWS provider was configured to allow Terraform to authenticate and provision infrastructure resources.</p><h3>provider.tf</h3><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>}<br>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}</pre><h3>Step 2 — Defining Variables</h3><p>Variables were created to make the project reusable across environments.</p><h3>variables.tf</h3><pre>variable &quot;aws_region&quot; {<br>  default = &quot;us-east-1&quot;<br>}<br>variable &quot;vpc_cidr&quot; {<br>  default = &quot;10.0.0.0/16&quot;<br>}</pre><h3>Step 3 — Creating Terraform Variable Values</h3><h3>terraform.tfvars</h3><pre>aws_region = &quot;us-east-1&quot;</pre><h3>Step 4 — Creating the VPC</h3><p>A custom VPC was created to isolate the infrastructure environment.</p><h3>main.tf</h3><pre>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block           = var.vpc_cidr<br>  enable_dns_support   = true<br>  enable_dns_hostnames = true<br>tags = {<br>    Name = &quot;main-vpc&quot;<br>  }<br>}</pre><h3>Step 5 — Creating the Internet Gateway</h3><p>An Internet Gateway was attached to allow public internet access.</p><pre>resource &quot;aws_internet_gateway&quot; &quot;igw&quot; {<br>  vpc_id = aws_vpc.main.id<br>tags = {<br>    Name = &quot;main-igw&quot;<br>  }<br>}</pre><h3>Step 6 — Creating Public Subnets</h3><p>Two public subnets were deployed across separate Availability Zones for high availability.</p><pre>resource &quot;aws_subnet&quot; &quot;public_1&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = &quot;10.0.1.0/24&quot;<br>  availability_zone       = &quot;${var.aws_region}a&quot;<br>  map_public_ip_on_launch = true<br>}<br>resource &quot;aws_subnet&quot; &quot;public_2&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = &quot;10.0.2.0/24&quot;<br>  availability_zone       = &quot;${var.aws_region}b&quot;<br>  map_public_ip_on_launch = true<br>}</pre><h3>Step 7 — Creating Route Tables</h3><p>Route tables were configured to allow internet-bound traffic.</p><pre>resource &quot;aws_route_table&quot; &quot;public&quot; {<br>  vpc_id = aws_vpc.main.id<br>route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.igw.id<br>  }<br>}</pre><h3>Step 8 — Creating Security Groups</h3><p>Security groups were configured to allow:</p><ul><li>HTTP traffic on port 80</li><li>DNS traffic on port 53</li><li>SSH access for administration</li></ul><pre>resource &quot;aws_security_group&quot; &quot;web_sg&quot; {<br>  name   = &quot;web-security-group&quot;<br>  vpc_id = aws_vpc.main.id<br>ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  ingress {<br>    from_port   = 53<br>    to_port     = 53<br>    protocol    = &quot;udp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;YOUR-IP/32&quot;]<br>  }<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><h3>Step 9 — Deploying EC2 Instances</h3><p>Separate EC2 instances were provisioned for DNS and web services.</p><h3>DNS Server</h3><pre>resource &quot;aws_instance&quot; &quot;dns_server&quot; {<br>  ami                    = data.aws_ami.amazon_linux.id<br>  instance_type          = &quot;t2.micro&quot;<br>  subnet_id              = aws_subnet.public_1.id<br>  vpc_security_group_ids = [aws_security_group.web_sg.id]<br>user_data = &lt;&lt;-EOF<br>              #!/bin/bash<br>              yum install -y bind bind-utils<br>              systemctl enable named<br>              systemctl start named<br>              EOF<br>  tags = {<br>    Name = &quot;dns-server&quot;<br>  }<br>}</pre><h3>Web Server</h3><pre>resource &quot;aws_instance&quot; &quot;web_server&quot; {<br>  ami                    = data.aws_ami.amazon_linux.id<br>  instance_type          = &quot;t2.micro&quot;<br>  subnet_id              = aws_subnet.public_2.id<br>  vpc_security_group_ids = [aws_security_group.web_sg.id]<br>user_data = &lt;&lt;-EOF<br>              #!/bin/bash<br>              yum install -y python3<br>              nohup python3 -m http.server 80 &amp;<br>              EOF<br>  tags = {<br>    Name = &quot;web-server&quot;<br>  }<br>}</pre><h3>Step 10 — Creating the S3 Logging Bucket</h3><p>An S3 bucket was provisioned to store Network Load Balancer access logs.</p><pre>resource &quot;aws_s3_bucket&quot; &quot;nlb_logs&quot; {<br>  bucket = &quot;unique-nlb-log-bucket-name&quot;<br>}</pre><h3>Step 11 — Creating the Network Load Balancer</h3><p>The Network Load Balancer was configured to distribute TCP and UDP traffic.</p><pre>resource &quot;aws_lb&quot; &quot;network_lb&quot; {<br>  name               = &quot;network-load-balancer&quot;<br>  internal           = false<br>  load_balancer_type = &quot;network&quot;<br>subnets = [<br>    aws_subnet.public_1.id,<br>    aws_subnet.public_2.id<br>  ]<br>  access_logs {<br>    bucket  = aws_s3_bucket.nlb_logs.bucket<br>    enabled = true<br>  }<br>}</pre><h3>Step 12 — Creating Target Groups</h3><h3>DNS Target Group</h3><pre>resource &quot;aws_lb_target_group&quot; &quot;dns_tg&quot; {<br>  name        = &quot;dns-target-group&quot;<br>  port        = 53<br>  protocol    = &quot;UDP&quot;<br>  target_type = &quot;instance&quot;<br>  vpc_id      = aws_vpc.main.id<br>}</pre><h3>Web Target Group</h3><pre>resource &quot;aws_lb_target_group&quot; &quot;web_tg&quot; {<br>  name        = &quot;web-target-group&quot;<br>  port        = 80<br>  protocol    = &quot;TCP&quot;<br>  target_type = &quot;instance&quot;<br>  vpc_id      = aws_vpc.main.id<br>stickiness {<br>    enabled = true<br>    type    = &quot;source_ip&quot;<br>  }<br>}</pre><h3>Step 13 — Registering Targets</h3><h3>DNS Server Registration</h3><pre>resource &quot;aws_lb_target_group_attachment&quot; &quot;dns_attach&quot; {<br>  target_group_arn = aws_lb_target_group.dns_tg.arn<br>  target_id        = aws_instance.dns_server.id<br>  port             = 53<br>}</pre><h3>Web Server Registration</h3><pre>resource &quot;aws_lb_target_group_attachment&quot; &quot;web_attach&quot; {<br>  target_group_arn = aws_lb_target_group.web_tg.arn<br>  target_id        = aws_instance.web_server.id<br>  port             = 80<br>}</pre><h3>Step 14 — Creating Listeners</h3><h3>UDP Listener for DNS</h3><pre>resource &quot;aws_lb_listener&quot; &quot;dns_listener&quot; {<br>  load_balancer_arn = aws_lb.network_lb.arn<br>  port              = 53<br>  protocol          = &quot;UDP&quot;<br>default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.dns_tg.arn<br>  }<br>}</pre><h3>TCP Listener for Web Traffic</h3><pre>resource &quot;aws_lb_listener&quot; &quot;web_listener&quot; {<br>  load_balancer_arn = aws_lb.network_lb.arn<br>  port              = 80<br>  protocol          = &quot;TCP&quot;<br>default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.web_tg.arn<br>  }<br>}</pre><h3>Step 15 — Deploying Infrastructure</h3><p>Terraform commands were executed to initialize, validate, and deploy the environment.</p><pre>terraform init<br>terraform validate<br>terraform plan<br>terraform apply</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_nlOc-BA3RYrGsXTn91UA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLx26cT8rc5tyEtpvWgE6w.png" /></figure><h3>Result</h3><p>The deployment successfully provisioned:</p><ul><li>A fully functional custom VPC</li><li>Public networking infrastructure</li><li>DNS and web server EC2 instances</li><li>UDP and TCP target groups</li><li>A Network Load Balancer with multiple listeners</li><li>Sticky sessions for web traffic</li><li>Centralized access logging to Amazon S3</li></ul><p>The infrastructure became fully reproducible, scalable, and reusable through Infrastructure as Code.</p><p>The project also reinforced several real-world cloud engineering concepts, including:</p><ul><li>Multi-AZ networking</li><li>Load balancing</li><li>Traffic routing</li><li>Security group management</li><li>Infrastructure automation</li><li>Terraform state management</li><li>AWS networking architecture</li><li>Operational observability through access logging</li></ul><h3>Key Lessons Learned</h3><p>Several important lessons emerged during the project:</p><ul><li>Infrastructure dependencies must be planned carefully before deployment</li><li>Terraform significantly improves consistency and repeatability</li><li>Network Load Balancers support both TCP and UDP traffic, making them ideal for mixed workloads</li><li>Access logging is critical for operational monitoring and auditing</li><li>Separating infrastructure into reusable Terraform files improves maintainability</li></ul><h3>Final Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ym5Wmujkt6Zm6ub0jUjbCg.png" /></figure><pre>Internet<br>   ↓<br>Network Load Balancer<br>   ├── UDP 53 → DNS Target Group → DNS Server<br>   └── TCP 80 → Web Target Group → Web Server</pre><h3>Conclusion</h3><p>This project demonstrated how Infrastructure as Code can transform manual cloud deployments into scalable, production-ready environments.</p><p>By rebuilding the infrastructure entirely with Terraform, the deployment process became automated, repeatable, and significantly easier to manage. The project also provided hands-on experience with AWS networking, load balancing, security configuration, and infrastructure automation practices commonly used in modern cloud engineering environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c4627f390d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running the Terraform Workflow for Real]]></title>
            <link>https://medium.com/@gkimari041/running-the-terraform-workflow-for-real-ace785289424?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ace785289424</guid>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Tue, 05 May 2026 17:13:39 GMT</pubDate>
            <atom:updated>2026-05-05T17:13:39.547Z</atom:updated>
            <content:encoded><![CDATA[<p>Yesterday was all theory.</p><p>Alex took the seven-step application deployment workflow and mapped it to Terraform. It made sense on paper. Clean. Structured. Logical.</p><p>Today, Alex actually did it.</p><p>Not in a sandbox. Not hypothetically. Alex ran the full workflow against real AWS infrastructure — from planning to deployment — and along the way, Alex made a mistake that perfectly demonstrated <em>why this workflow exists in the first place.</em></p><p>I’ll get to that mistake. It’s important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jr2eUI6pLgpxPjMAYyUaEA.png" /></figure><h3>What Changed Today</h3><p>The goal wasn’t just to “run Terraform.” It was to make a meaningful infrastructure improvement.</p><p>Alex added two CloudWatch alarms to my webserver cluster:</p><ul><li>A <strong>low CPU alarm</strong> to detect when the system is over-provisioned</li><li>A <strong>tighter high CPU threshold</strong> to catch scaling issues earlier</li></ul><p>Why this matters:</p><p>If your CPU is constantly low, you’re wasting money.<br>If it’s too high, users will feel it before your monitoring system does.</p><p>So instead of waiting until things break, I adjusted the thresholds to catch issues earlier and surface inefficiencies.</p><p>In simple terms: better visibility, better decisions.</p><h3>Step 1 — Version Control (Where Everything Starts)</h3><p>Terraform code lives in GitHub, with the main branch protected.</p><p>That means:</p><ul><li>No direct pushes (in theory)</li><li>All changes go through pull requests</li><li>Every change is reviewed before it reaches production</li></ul><p>Also important:<br><strong>The Terraform state file is not in Git.</strong></p><p>It lives in S3, encrypted and versioned.</p><p>Why?</p><p>Because committing state would:</p><ul><li>Expose sensitive infrastructure details</li><li>Create conflicts between engineers</li><li>Break collaborative workflows</li></ul><p>So from the start, we already have a key difference from application code:<br>Infrastructure has shared state. And that changes everything.</p><h3>Step 2 — Run Locally (The First Reality Check)</h3><p>Before touching anything, Alex ran:</p><pre>terraform plan -out=day21.tfplan</pre><p>The output showed:</p><ul><li>New resources to be created</li><li>No modifications</li><li>No deletions</li></ul><p>Exactly what Alex expected.</p><p>That’s the goal here — <strong>predictability</strong>.</p><p>If the plan doesn’t match your intent, you stop immediately.</p><p>One interesting detail:<br>Alex expected more resources to be created, but fewer showed up.</p><p>Why?</p><p>Because monitoring is disabled in development.</p><p>So even though Alex defined both alarms, Terraform intelligently skipped them based on environment settings.</p><p>That’s a small detail, but it reinforces something important:<br><strong>your configuration is not always your outcome — the environment matters.</strong></p><h3>Step 3 — The Mistake</h3><p>This is where things got real.</p><p>Instead of creating a feature branch, Alex went straight ahead and ran:</p><pre>git add .<br>git commit -m &quot;Add CloudWatch alarms&quot;<br>git push</pre><p>Straight to main.</p><p>No branch. No pull request. No review.</p><p>On a real team, this would have been blocked instantly by branch protection rules.</p><p>But in my repo? It went through.</p><p>And that’s the point.</p><p>The workflow isn’t there because engineers don’t know better.<br>It exists because <em>even when you know better, you still make mistakes.</em></p><p>The correct process should have been:</p><pre>git checkout -b add-cloudwatch-alarms<br>git add .<br>git commit -m &quot;Add monitoring improvements&quot;<br>git push origin add-cloudwatch-alarms</pre><p>That one missed step removed every safety net.</p><h3>Step 4 — Pull Request and Blast Radius Thinking</h3><p>Even though Alex had already pushed to main, Alex still documented the change as if it were a proper PR.</p><p>Because this is where the real discipline happens.</p><p>A good infrastructure PR doesn’t just say <em>what</em> changed.<br>It explains:</p><ul><li>What resources are affected</li><li>Whether anything is being destroyed</li><li>What happens if the deployment fails midway</li></ul><p>In this case:</p><ul><li>All changes were <strong>additive</strong></li><li>No existing resources were modified</li><li>No risk to live traffic</li></ul><p>That’s what we call <strong>low blast radius</strong>.</p><p>And this step is underrated.</p><p>Because it forces you to think <em>before</em> applying changes:</p><blockquote><em>“If this breaks halfway, what’s the impact?</em></blockquote><p>That mindset is what separates safe deployments from risky ones.</p><h3>Step 5 — Automated Tests (Confidence Before Action)</h3><p>Once changes are proposed, automation takes over.</p><p>GitHub Actions ran:</p><ul><li>Validation checks</li><li>Terraform plan verification</li><li>Unit tests</li></ul><p>Everything passed.</p><p>Integration tests were skipped — as expected — because they only run after merging.</p><p>This is another key difference from application workflows:</p><p>Some infrastructure tests actually deploy resources.</p><p>Which means:</p><ul><li>They take longer</li><li>They cost money</li><li>They must be used carefully</li></ul><h3>Step 6 — Merge and Versioning</h3><p>After validation, Alex tagged the change:</p><pre>git tag -a &quot;v1.4.0&quot;<br>git push origin v1.4.0</pre><p>Versioning matters more than people think.</p><p>Because once modules are reused across environments or teams,<br>you need stable, predictable references.</p><p>Without versioning, everything becomes fragile.</p><h3>Step 7 — Deploy (Where It Becomes Real)</h3><p>Now the most critical step:</p><pre>terraform apply &quot;day21.tfplan&quot;</pre><p>Notice something important here.</p><p>Alex didn’t just run terraform apply.</p><p>Alex applied the <strong>saved plan file</strong>.</p><p>That means:</p><ul><li>Alex deployed exactly what I reviewed earlier</li><li>No surprises</li><li>No last-minute changes</li></ul><p>And after the apply:</p><ul><li>Resources were created successfully</li><li>The application was still running</li><li>The new version was live</li></ul><p>Verification confirmed everything worked as expected.</p><h3>The Safeguards That Actually Matter</h3><p>Running through this workflow made one thing clear:</p><p>Infrastructure needs stronger guardrails than application code.</p><p>Here are the ones that stood out most.</p><h3>1. Approval Gates for Destruction</h3><p>If a plan includes deletions, it should require extra approval.</p><p>Why?</p><p>Because deleting infrastructure is not reversible.</p><h3>2. Plan File Pinning</h3><p>Using a saved plan file ensures:</p><blockquote><em>What you reviewed is exactly what gets deployed.</em></blockquote><p>Skipping this step introduces risk.</p><h3>3. State Backups</h3><p>With S3 versioning enabled, I can restore previous state versions if something goes wrong.</p><p>Without backups, recovery becomes guesswork.</p><h3>4. Blast Radius Awareness</h3><p>Every change should answer:</p><blockquote><em>“What breaks if this fails halfway?”</em></blockquote><p>If you can’t answer that, you’re not ready to deploy.</p><h3>Sentinel Policies (The Guardrails You Can’t Bypass)</h3><p>Alex also explored Sentinel — Terraform Cloud’s policy system.</p><p>Example rule:</p><p>Only allow approved instance types.</p><p>If someone tries to deploy something outside that list, the system blocks it.</p><p>Not warns. Not suggests.</p><p><strong>Blocks.</strong></p><p>That’s powerful because it removes reliance on human discipline.</p><h3>What’s Actually Different From Application Deployment?</h3><p>After running this end-to-end, three differences stood out clearly:</p><h3>1. The Plan Is the Real Diff</h3><p>In application code, you review lines of code.</p><p>In Terraform, that’s not enough.</p><p>The <strong>plan output</strong> is what actually matters — <br>it tells you what will change in the real world.</p><h3>2. State Changes Everything</h3><p>Application code is stateless.</p><p>Infrastructure is not.</p><p>Multiple engineers applying changes at the same time can corrupt state.</p><p>That’s why locking and coordination exist.</p><h3>3. Mistakes Are Expensive</h3><p>A bad app deploy? Roll it back.</p><p>A bad infrastructure change?</p><p>You could:</p><ul><li>Delete a database</li><li>Break networking</li><li>Take down production</li></ul><p>Some mistakes cannot be undone.</p><p>That changes how careful you need to be.</p><h3>The Most Dangerous Moment</h3><p>The riskiest point in the workflow isn’t writing code.</p><p>It’s the gap between:</p><ul><li>Running terraform plan</li><li>Running terraform apply</li></ul><p>If something changes in between, your apply may not match what you reviewed.</p><p>That’s why <strong>plan file pinning</strong> is so important.</p><p>And yet, most teams skip it.</p><h3>What I Took Away From This</h3><p>Running the workflow taught me more than just commands.</p><p>Here’s what actually stuck:</p><ul><li>The plan is your source of truth — not the code</li><li>Small safeguards prevent big failures</li><li>Automation helps, but discipline matters more</li><li>Mistakes are inevitable — systems must catch them</li><li>Infrastructure demands more caution than application code</li></ul><p>And most importantly:</p><blockquote><em>The workflow isn’t bureaucracy.<br>It’s protection against very real, very costly mistakes.</em></blockquote><h3>Final Thought</h3><p>Before today, the workflow felt like a checklist.</p><p>After today, it feels like a safety system.</p><p>Because one missed step — like pushing directly to main —<br>is all it takes to bypass everything designed to protect your infrastructure.</p><p>And that’s exactly why the workflow exists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ace785289424" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Convince Your Team to Adopt Infrastructure as Code]]></title>
            <link>https://medium.com/@gkimari041/how-to-convince-your-team-to-adopt-infrastructure-as-code-74dcaaf1e879?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/74dcaaf1e879</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 18:35:38 GMT</pubDate>
            <atom:updated>2026-04-30T18:35:38.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmgD-9p81O5RxUGIo-OAyg.png" /></figure><p>Most teams don’t reject Infrastructure as Code (IaC) because it’s a bad idea.</p><p>They reject it because it feels risky, slow, and unnecessary — especially when “everything is already working.”</p><p>After working on a real client project and studying IaC adoption, I’ve learned this:<br><strong>adopting IaC is less about tools and more about timing, trust, and strategy.</strong></p><p>Let me walk you through what I’ve seen, what works, and what usually goes wrong.</p><h3>1. Know Where You Are Starting</h3><p>Before talking about Terraform, pipelines, or automation, you need to answer one simple question:</p><blockquote>Where is your team right now?</blockquote><p>There are four common levels of IaC maturity:</p><p>LevelDescription<strong>Level 0 — Manual</strong>Everything is done in the cloud console. No code, no tracking, no consistency.<strong>Level 1 — Scripts</strong>Some automation exists using scripts, but no state management.<strong>Level 2 — IaC Tools</strong>Infrastructure is written in code, stored in Git, and properly managed.<strong>Level 3 — Full Automation</strong>Everything runs through CI/CD. No manual changes at all.</p><p>My client?<br><strong>Level 0 — fully manual</strong></p><p>Everything was set up through a web dashboard. No infrastructure code. No version control. No audit trail.</p><p>If the person who set it up left, the system couldn’t be rebuilt from scratch.</p><h3>2. Why Most IaC Migrations Fail</h3><p>After reading and experiencing this firsthand, two mistakes show up again and again.</p><h3>Mistake #1: Trying to Migrate Everything at Once</h3><p>Teams get excited about IaC and try to convert their entire infrastructure in one go.</p><p>What happens?</p><ul><li>Hundreds of resources to define</li><li>Unexpected edge cases</li><li>Things start breaking</li><li>Progress slows down</li><li>Confidence drops</li></ul><p>Eventually, the team gives up.</p><p>The irony? The old system was working. Now nothing is.</p><h3>Mistake #2: Ignoring the Human Side</h3><p>IaC is not just a technical change.</p><p>It changes how teams work:</p><ul><li>No more quick fixes in the console</li><li>Every change goes through a pull request</li><li>Reviews become mandatory</li></ul><p>That’s a big shift.</p><p>If you don’t prepare the team for this, they will resist it — even if the technology is better.</p><h3>One Thing I Would Add</h3><p>There is one moment that changes everything:</p><blockquote><em>When the team sees the app deploy automatically from a Git push.</em></blockquote><p>That’s when trust is built.</p><p>That’s when IaC stops being theory and starts becoming real.</p><h3>3. The Reality Check (Honest Audit)</h3><p>Before building any plan, I looked at the actual system.</p><p>Here’s what I found.</p><h3>Infrastructure Setup</h3><p>AreaSituationProvisioningManual (web console)Infrastructure CodeNoneVersion ControlOnly for app codeAudit TrailNone</p><h3>Secrets Management</h3><p>ProblemImpactStored in .env fileOnly one machine has accessNo rotationSecurity riskNo logsNo visibility</p><h3>The Critical Technical Issue</h3><p>This was the biggest problem.</p><p>The application stores data in memory:</p><pre>const jobMetaStore = new Map();</pre><p>This works on a <strong>single server</strong>.</p><p>But on AWS, multiple servers run at the same time.</p><p>That means:</p><ul><li>Server A has its own data</li><li>Server B has different data</li></ul><p>Result: <strong>Users randomly lose their results</strong></p><p>This is not a Terraform problem.<br>It’s an architecture problem.</p><p>And it must be fixed before any migration.</p><h3>4. The Business Case (What Actually Matters)</h3><p>If you want leadership or a client to agree, don’t talk about Terraform.</p><p>Talk about outcomes.</p><p>Here’s how I framed it:</p><p>ProblemSolutionResultData randomly disappearsUse Redis instead of memoryReliable systemSecrets on one machineUse AWS Secrets ManagerNo single point of failureNo audit trailUse Git for infra changesFull visibilityNo dev environmentCreate separate environmentsSafer testingNo rollbackStore versions in registryFaster recovery</p><h3>Real Impact</h3><p>TaskBeforeAfterCreate environment2–3 hours&lt; 10 minutesOnboard developer1 day&lt; 2 hours</p><p>That’s the kind of improvement decision-makers understand.</p><h3>5. The 4-Phase Adoption Plan</h3><p>The key idea is simple:</p><blockquote><strong><em>Don’t break what works. Improve step by step.</em></strong></blockquote><h3>Phase 1 — Start Small</h3><p>Instead of touching existing systems, start with something new.</p><p>Create:</p><ul><li>S3 bucket for Terraform state</li><li>DynamoDB table for locking</li></ul><p>No risk. No downtime.</p><p>First win.</p><h3>Phase 2 — Import Existing Infrastructure</h3><p>Now bring existing resources into Terraform using:</p><pre>terraform import</pre><p>At the same time:</p><ul><li>Fix the application (replace memory with Redis)</li><li>Prepare Docker and CI/CD</li></ul><h3>Phase 3 — Deploy a Dev Environment</h3><p>This is the turning point.</p><p>Deploy the app on AWS for the first time.</p><p>Now the team can:</p><ul><li>See it working</li><li>Trust the process</li></ul><p>Also introduce team rules:</p><ul><li>No direct console changes</li><li>All changes via pull requests</li><li>terraform plan required</li></ul><h3>Phase 4 — Go Live</h3><p>Finally:</p><ul><li>Deploy production</li><li>Automate everything with CI/CD</li><li>Add monitoring and alerts</li></ul><p>At this point, IaC becomes the standard way of working.</p><h3>6. The Reality of terraform import</h3><p>I practiced importing existing resources, and it revealed something important.</p><p>After import, I ran:</p><pre>terraform plan</pre><p>I expected no changes.</p><p>Instead, I saw this:</p><pre>Plan: 0 to add, 2 to change, 0 to destroy</pre><h3>What Happened?</h3><ul><li>Tags were missing</li><li>Naming was inconsistent</li></ul><p>This is called <strong>drift</strong>.</p><p>The infrastructure exists — but doesn’t match the code.</p><h3>Important Lesson</h3><p>What terraform import doesWhat it does NOT doAdds resource to stateDoes not create codeLets Terraform track itDoes not fix issuesHelps detect driftDoes not update resources</p><p>You still need to:</p><ol><li>Write the correct configuration</li><li>Run terraform apply to fix differences</li></ol><h3>7. Terraform Cloud vs S3 Backend</h3><p>There are two main ways to manage Terraform state.</p><p>FeatureS3 BackendTerraform CloudSetupSimpleManagedUINoneWeb dashboardAccess controlIAMBuilt-in rolesPoliciesNoYesCost estimationNoYes</p><p>For small teams: <strong>S3 is enough</strong><br> For larger teams: Terraform Cloud becomes useful</p><h3>Key Lessons</h3><ul><li>Start small — don’t migrate everything at once</li><li>Show results early — visible success builds trust</li><li>IaC is a team change, not just a tool</li><li>terraform import reveals problems you didn’t know existed</li><li>Fix architecture issues before migration</li><li>Speak in business outcomes, not technical terms</li></ul><h3>Final Thoughts</h3><p>After 19 days of learning Terraform, one thing is clear:</p><blockquote><em>Writing infrastructure code is the easy part.</em></blockquote><p>The hard part is:</p><ul><li>Understanding the current system</li><li>Planning the transition</li><li>Getting people on board</li></ul><p>Even importing two simple resources showed hidden issues.</p><p>Now imagine doing that for an entire system.</p><p>That’s why successful IaC adoption is not about speed.</p><p>It’s about <strong>doing it right, step by step</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74dcaaf1e879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Terraform Testing: From Unit Tests to End-to-End Validation]]></title>
            <link>https://medium.com/@gkimari041/automating-terraform-testing-from-unit-tests-to-end-to-end-validation-760469eb7062?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/760469eb7062</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[terraform-modules]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 15:07:17 GMT</pubDate>
            <atom:updated>2026-04-27T15:07:17.189Z</atom:updated>
            <content:encoded><![CDATA[<p>I manually tested my infrastructure. I ran ten tests and wrote down every result. It worked, but it took time.That approach is fine when you are working alone or testing once. But what happens when the code changes? You have to repeat all the tests again. And again.Manual testing does not scale.</p><p>So, I moved to <strong>automated testing</strong>. The goal was simple:<br>Make tests run automatically on every change, catch problems early, and give the team confidence to deploy.To do this, I built three layers of testing and connected them to a CI/CD pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtAXATXFzgm66AKqTlfr0A.png" /></figure><h3>The Three Testing Layers</h3><p>Before writing any code, I first understood what each type of test does.</p><h3>1. Unit Tests</h3><ul><li>Tool: terraform test</li><li>No real infrastructure created</li><li>Runs in seconds</li><li>Free</li></ul><p><strong>What it checks:</strong><br>Logic, variables, conditionals, tags</p><h3>2. Integration Tests</h3><ul><li>Tool: Terratest (Go)</li><li>Deploys real infrastructure</li><li>Takes 5–15 minutes</li><li>Small cost</li></ul><p><strong>What it checks:</strong><br>HTTP responses, health checks, networking</p><h3>3. End-to-End Tests</h3><ul><li>Tool: Terratest</li><li>Deploys full system (multiple modules)</li><li>Takes longer and costs more</li></ul><p><strong>What it checks:</strong><br>How all parts work together</p><h3>Strategy I Used</h3><ul><li>Unit tests → run on every pull request</li><li>Integration tests → run after merge</li><li>End-to-end tests → run less frequently</li></ul><h3>1. Unit Tests with terraform test</h3><p>Terraform now supports built-in testing using .tftest.hcl files. These tests do not create real resources.</p><p>Example:</p><pre>variables {<br>  cluster_name  = &quot;test-cluster&quot;<br>  instance_type = &quot;t3.micro&quot;<br>  environment   = &quot;dev&quot;<br>}</pre><pre>run &quot;validate_instance_type&quot; {<br>  command = plan</pre><pre>  assert {<br>    condition     = aws_launch_template.web.instance_type == &quot;t3.micro&quot;<br>    error_message = &quot;Instance type must match input&quot;<br>  }<br>}</pre><p>Key point:</p><ul><li>command = plan means Terraform only checks the plan</li><li>No AWS resources are created</li><li>Tests are fast and cheap</li></ul><p>The most useful test here is checking production logic. For example, making sure production uses a larger instance type. This helps catch mistakes early.</p><h3>2. Integration Tests with Terratest</h3><p>Integration tests are written in Go and use real AWS resources.</p><p>Example:</p><pre>func TestWebserverClusterIntegration(t *testing.T) {<br>    t.Parallel()</pre><pre>    uniqueID := random.UniqueId()<br>    clusterName := fmt.Sprintf(&quot;test-%s&quot;, uniqueID)</pre><pre>    terraformOptions := terraform.WithDefaultRetryableErrors(t, &amp;terraform.Options{<br>        TerraformDir: &quot;../modules/services/webserver-cluster&quot;,<br>        Vars: map[string]interface{}{<br>            &quot;cluster_name&quot;:  clusterName,<br>            &quot;instance_type&quot;: &quot;t3.micro&quot;,<br>            &quot;environment&quot;:   &quot;dev&quot;,<br>        },<br>    })</pre><pre>    defer terraform.Destroy(t, terraformOptions)</pre><pre>    terraform.InitAndApply(t, terraformOptions)</pre><pre>    albDnsName := terraform.Output(t, terraformOptions, &quot;alb_dns_name&quot;)<br>    url := fmt.Sprintf(&quot;http://%s&quot;, albDnsName)</pre><pre>    http_helper.HttpGetWithRetry(t, url, nil, 200, &quot;Hello&quot;, 30, 10*time.Second)<br>}</pre><p>Important things here:</p><ul><li>defer terraform.Destroy → ensures cleanup always happens</li><li>random.UniqueId() → prevents name conflicts</li><li>Real infrastructure is created and tested</li></ul><p>Without cleanup, resources would stay running and cost money.</p><h3>3. End-to-End Tests</h3><p>End-to-end tests go further. They test the full system, not just one module.</p><p>Example flow:</p><ol><li>Deploy VPC</li><li>Deploy application</li><li>Connect them</li><li>Test full system</li></ol><p>These tests check if everything works together, not just individually.</p><p>Even if a module works alone, it can fail when connected to others. That is what E2E tests catch.</p><h3>4. CI/CD Pipeline</h3><p>To automate everything, I created a GitHub Actions pipeline.</p><h3>Workflow:</h3><ul><li>Pull Request → run unit tests</li><li>Merge to main → run integration tests</li></ul><p>Example:</p><pre>name: Terraform Tests</pre><pre>on:<br>  pull_request:<br>    branches: [main]<br>  push:<br>    branches: [main]</pre><pre>jobs:<br>  unit-tests:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: hashicorp/setup-terraform@v3<br>      - run: terraform init -backend=false<br>      - run: terraform test</pre><pre>  integration-tests:<br>    runs-on: ubuntu-latest<br>    if: github.event_name == &#39;push&#39;<br>    needs: unit-tests<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: actions/setup-go@v4<br>      - run: go test -v -timeout 30m ./...</pre><p>Key idea:</p><ul><li>Unit tests run often (fast and cheap)</li><li>Integration tests run less often (slower and cost money)</li></ul><p>This keeps the pipeline efficient.</p><h3>5. Branch Strategy</h3><p>I used a simple workflow:</p><ol><li>Work on develop branch</li><li>Open PR to main</li><li>Unit tests run automatically</li><li>Merge PR</li><li>Integration tests run</li></ol><p>This ensures:</p><ul><li>Fast feedback during development</li><li>Full testing before production</li></ul><h3>6. The Error I Encountered</h3><h3>Error:</h3><pre>missing go.sum entry for module</pre><h3>Cause:</h3><p>The go.sum file was not committed. This file is needed to verify dependencies.</p><h3>Fix:</h3><pre>go mod tidy<br>git add go.sum<br>git commit -m &quot;Add go.sum&quot;<br>git push</pre><p>After fixing this, the integration test ran successfully.</p><h3>Key Lessons Learned</h3><ul><li>Unit tests are fast and free — always use them</li><li>terraform test does not create real resources</li><li>Integration tests must always clean up resources</li><li>defer terraform.Destroy is critical</li><li>Unique names prevent conflicts during testing</li><li>CI/CD pipelines help catch issues early</li><li>Do not run expensive tests on every PR</li></ul><h3>Final Thoughts</h3><p>Instead of manually checking everything, tests now run automatically.<br>Instead of guessing if changes break things, I get clear feedback.</p><p>The result:</p><ul><li>Faster development</li><li>Fewer mistakes</li><li>More confidence in deployments</li></ul><p>This is what turns Terraform from a simple tool into a reliable system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=760469eb7062" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Importance of Manual Testing in Terraform]]></title>
            <link>https://medium.com/@gkimari041/the-importance-of-manual-testing-in-terraform-9400d7205336?source=rss-c5ecb2d107c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9400d7205336</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Gkimari]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 14:22:33 GMT</pubDate>
            <atom:updated>2026-04-27T14:22:33.811Z</atom:updated>
            <content:encoded><![CDATA[<p>Instead of Alex relying only on Terraform outputs or CI checks, he created a <strong>clear manual testing checklist</strong> and ran it on both dev and production environments.</p><p>He recorded every result — both passes and failures.</p><p>Out of all the tests, only one failed.</p><p>And that single failure taught more than all the successful tests combined.</p><h3>Why Manual Testing Still Matters</h3><p>Before this, Alex believed automated testing was enough.</p><p>But one key lesson changed everything:</p><p>👉 <strong>You cannot automate what you have not tested manually first.</strong></p><p>Manual testing helps you:</p><ul><li>Understand what “correct” looks like</li><li>Catch things automation might miss</li><li>Build better automated tests later</li></ul><p>Automated tests only check what you tell them to check.<br>Manual testing helps you discover what you should be checking in the first place.</p><h3>The Testing Checklist</h3><p>Alex created a simple checklist that any engineer could follow.</p><h3>1. Provisioning Checks</h3><ul><li>Does terraform init run without errors?</li><li>Does terraform validate pass?</li><li>Does terraform plan show the expected resources?</li><li>Does terraform apply complete successfully?</li></ul><h3>2. Resource Checks</h3><ul><li>Are all resources visible in AWS?</li><li>Are names, tags, and regions correct?</li><li>Do security rules match what was defined?</li></ul><h3>3. Functional Checks</h3><ul><li>Does the load balancer (ALB) respond?</li><li>Does curl return the expected result?</li><li>Are all instances healthy?</li></ul><h3>4. State Checks</h3><ul><li>Does terraform plan show <strong>“No changes”</strong> after apply?</li></ul><h3>5. Regression Checks</h3><ul><li>When a small change is made, does only that change appear?</li></ul><h3>6. Cleanup Checks</h3><ul><li>Does terraform destroy remove everything?</li><li>Are there no leftover resources?</li></ul><h3>Dev Environment Results</h3><p>Alex ran all tests in the dev environment.</p><h3>✅ Most Tests Passed</h3><ul><li>Terraform configuration was valid</li><li>Plan showed the correct number of resources</li><li>Apply completed successfully</li><li>The application worked when accessed through the browser</li><li>State was consistent (no unexpected changes)</li></ul><h3>🔍 The Most Important Test</h3><p>After running terraform apply, Alex immediately ran:</p><pre>terraform plan</pre><p>Result:<br>👉 <strong>No changes</strong></p><p>This confirmed that:</p><ul><li>Terraform state matched real infrastructure</li><li>No hidden issues existed</li></ul><p>This is a simple test — but many people skip it.</p><h3>🌐 Functional Test</h3><p>Alex tested the application using:</p><pre>curl http://&lt;alb-dns&gt;</pre><p>The response returned the expected HTML.</p><p>👉 This proved everything worked together:</p><ul><li>Load balancer</li><li>Instances</li><li>Application</li></ul><h3>The One Failure (And Why It Mattered)</h3><p>During cleanup, Alex ran:</p><pre>terraform plan -destroy</pre><p>Instead of success, he got an error.</p><h3>❌ Problem:</h3><p>Terraform refused to destroy the load balancer.</p><h3>Root Cause:</h3><pre>lifecycle {<br>  prevent_destroy = true<br>}</pre><p>This setting protects resources from accidental deletion.</p><h3>💡 Why This Was Important</h3><ul><li>In <strong>production</strong>, this is a good thing</li><li>In <strong>testing</strong>, it blocks cleanup</li></ul><h3>✅ Fix:</h3><ul><li>Removed prevent_destroy temporarily</li><li>Applied changes</li><li>Ran destroy again successfully</li></ul><h3>🎯 Key Lesson:</h3><p>👉 prevent_destroy should be used carefully<br>👉 It is better placed in <strong>production configs</strong>, not inside reusable modules</p><h3>Cleanup Verification</h3><p>After destroying resources, Alex double-checked using AWS CLI.</p><p>He confirmed:</p><ul><li>Instances were terminated</li><li>Load balancer was deleted</li><li>No leftover resources remained</li></ul><p>👉 This step is important because Terraform can sometimes fail halfway.</p><h3>Dev vs Production Comparison</h3><p>Alex ran the same tests in production.</p><h3>What changed:</h3><ul><li>More resources in production</li><li>Larger instance sizes</li><li>Autoscaling enabled</li></ul><h3>What stayed the same:</h3><ul><li>Everything worked as expected</li><li>No unexpected behavior</li></ul><p>👉 This proved that the setup was <strong>consistent and reliable across environments</strong></p><h3>Why Cleanup Discipline Matters</h3><p>Cleanup is often ignored — but it is critical.</p><p>If you skip it:</p><ul><li>You leave resources running (costing money)</li><li>You create conflicts in future tests</li><li>Your environment becomes messy</li></ul><h3>Best Practice:</h3><p>Always run:</p><pre>terraform plan -destroy</pre><p>Before running:</p><pre>terraform destroy</pre><p>And verify afterward.</p><h3>Key Lessons from Day 17</h3><ul><li>Manual testing is the foundation of automation</li><li>terraform validate checks syntax, not functionality</li><li>Running terraform plan after apply detects hidden issues</li><li>Real testing happens when you check the system end-to-end</li><li>One failure can teach more than many successes</li><li>Cleanup is just as important as deployment</li></ul><h3>Final Thoughts</h3><p>Day 17 was not about building new infrastructure.</p><p>It was about <strong>trusting what was already built</strong>.</p><p>Alex ran 10 tests:</p><ul><li>9 passed</li><li>1 failed</li></ul><p>But that one failure revealed a design issue that could cause problems in real teams.</p><p>And that is the value of testing.</p><p>👉 Not just proving things work<br>👉 But finding what could go wrong before it actually does</p><p>From this point on, Alex is no longer guessing.</p><p>He is <strong>testing, verifying, and improving with confidence</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9400d7205336" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>