<?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 Pankaj Gupta on Medium]]></title>
        <description><![CDATA[Stories by Pankaj Gupta on Medium]]></description>
        <link>https://medium.com/@pnkjofficial?source=rss-2c3532758bc0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MsMtaWjTX_XXLMtXVxD4EQ.png</url>
            <title>Stories by Pankaj Gupta on Medium</title>
            <link>https://medium.com/@pnkjofficial?source=rss-2c3532758bc0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:09:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pnkjofficial/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[A Hidden Gem for Enterprise Multi-Account AWS Architectures]]></title>
            <link>https://medium.com/@pnkjofficial/a-hidden-gem-for-enterprise-multi-account-aws-architectures-e623f1ecfcf5?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e623f1ecfcf5</guid>
            <category><![CDATA[aws-landing-zone]]></category>
            <category><![CDATA[enterprise-architecture]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[vpc-origins]]></category>
            <category><![CDATA[aws-cloudfront]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 17:20:20 GMT</pubDate>
            <atom:updated>2026-06-27T17:20:20.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>One Amazon CloudFront Feature That Changed How I Design Enterprise AWS Networks</h3><p>The AWS Feature That Finally Solves Private Cross-Account Origins</p><p>If you’re building a modern AWS Landing Zone, your architecture probably looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spoJf4SUeNXSJyMRqYX2aA.png" /></figure><p>For years, one limitation frustrated AWS architects:</p><blockquote><strong><em>CloudFront could not directly access a private Application Load Balancer located in another AWS account.</em></strong></blockquote><p>That has now changed.</p><h3>The Problem</h3><p>In enterprise environments, we usually separate responsibilities into multiple AWS accounts.</p><p>For example:</p><p>AccountResponsibilityEdgeCloudFront, WAF, Route53NetworkVPC, Transit Gateway, ALBWorkloadEKS, ECS, EC2SecurityGuardDuty, Security HubLoggingCloudTrail, CloudWatch Logs</p><p>The challenge was simple:</p><blockquote><strong><em>How can CloudFront securely access an Internal ALB without making it internet-facing?</em></strong></blockquote><p>Previously, this wasn’t possible across accounts.</p><h3>The New Capability</h3><p>AWS introduced <strong>Cross-Account CloudFront VPC Origins</strong>. Instead of sharing the ALB or the VPC, you share the <strong>VPC Origin</strong>. This enables:</p><pre>CloudFront (Edge Account)<br>        │<br>Shared VPC Origin<br>        │<br>Internal ALB (Network Account)</pre><p>No public ALB required.</p><h3>How It Works</h3><h3>Step 1</h3><p>Create an Internal ALB inside the Network Account.</p><pre>Network Account</pre><pre>Internal ALB</pre><h3>Step 2</h3><p>Go to</p><pre>CloudFront</pre><pre>↓</pre><pre>VPC Origins</pre><pre>↓</pre><pre>Create VPC Origin</pre><p>Select the Internal ALB. CloudFront deploys the VPC Origin.</p><h3>Step 3</h3><p>Share the VPC Origin using AWS RAM.</p><p>You can share it with:</p><ul><li>Another AWS Account</li><li>Organizational Unit</li><li>Entire AWS Organization</li></ul><p>You are only sharing the <strong>CloudFront VPC Origin resource</strong>.</p><h3>Step 4</h3><p>Go to the Edge Account.</p><p>Create (or update) the CloudFront Distribution.</p><p>When adding an Origin, you’ll now see</p><pre>Shared VPC Origin</pre><p>Select it. Done.</p><p><strong>CloudFront now communicates privately with the Internal ALB.</strong></p><h4><em>Note — Because </em><strong><em>CloudFront is a global AWS service</em></strong><em>, and VPC Origin management is exposed through the </em><strong><em>us-east-1</em></strong><em> console.</em></h4><p>That one detail can save hours of troubleshooting.</p><p>This pattern provides centralized edge security while keeping application workloads completely private.</p><h3>Lessons Learned</h3><p>✔ CloudFront VPC Origins are managed through us-east-1.<br>✔ Cross-account VPC Origins use AWS RAM.<br>✔ You share the VPC Origin, not the ALB.<br>✔ Your Edge Account doesn’t need a VPC.<br>✔ Internal ALBs remain private.<br>✔ Perfect for enterprise Landing Zones.</p><h3>Final Thoughts</h3><p>As AWS continues to evolve its networking capabilities, architectures that previously required public origins can now remain entirely private while still leveraging CloudFront’s global edge network.</p><p>If you’re designing a secure, multi-account AWS Landing Zone, Cross-Account CloudFront VPC Origins are worth evaluating.</p><p>They simplify edge networking, reduce exposure, and align well with enterprise security best practices.</p><p><strong>👏 P.S.</strong> Thanks to a long debugging session (and a user who kept challenging my assumptions), I ended up learning something new too. Sometimes the best architecture lessons come from real production environments — not just the documentation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e623f1ecfcf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eliminating Cross-Account Log Silos with CloudWatch Logs Centralization]]></title>
            <link>https://medium.com/@pnkjofficial/eliminating-cross-account-log-silos-with-cloudwatch-logs-centralization-5d9d0a9fdab4?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d9d0a9fdab4</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[aws-cloudwatch]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[logo-design]]></category>
            <category><![CDATA[aws-multiple-accounts]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 06:19:18 GMT</pubDate>
            <atom:updated>2026-06-16T06:19:18.796Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing logs across multiple AWS accounts can quickly become challenging. In our AWS Organization, we have separate accounts for Development, Staging, Production, Testing, and shared infrastructure. While CloudWatch Logs provides excellent visibility within individual accounts, troubleshooting and auditing across multiple accounts often requires switching contexts and running queries in multiple places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFlGRjZ46jppjx3vwEqiZg.png" /></figure><p>AWS now provides a native solution called <strong>CloudWatch Logs Centralization</strong>, which allows organizations to replicate CloudWatch Logs from multiple AWS accounts into a central logging account without building custom pipelines using Kinesis, Lambda, or Firehose.</p><h3>Why Centralize Logs?</h3><p>Common challenges in multi-account environments:</p><ul><li>Logs are distributed across multiple AWS accounts.</li><li>Troubleshooting requires jumping between accounts.</li><li>Security teams need a centralized view.</li><li>Auditing and compliance become more complex.</li><li>Operational visibility is fragmented.</li><li>Easy to configure with any SIEM tools.</li></ul><p>CloudWatch Logs Centralization solves these challenges by providing a single destination account where logs from multiple source accounts can be viewed and analyzed.</p><h3>Key Benefits</h3><h3>Native AWS Service</h3><p>No need for:</p><ul><li>Kinesis Data Firehose</li><li>Lambda functions</li><li>Custom subscription filters</li><li>Complex cross-account IAM configurations</li></ul><h3>Organization-Aware</h3><p>You can centralize logs from:</p><ul><li>Entire AWS Organization</li><li>Specific Organizational Units (OUs)</li><li>Individual AWS Accounts</li></ul><h3>Simplified Operations</h3><p>Operations teams can query logs from all accounts in a single location using CloudWatch Logs Insights.</p><h3>Implementation Steps</h3><h3>1. Choose a Central Logging Account</h3><p>Create or designate a dedicated AWS account that will act as the centralized logging destination.</p><h3>2. Enable Trusted Access</h3><p>Enable CloudWatch Logs integration with AWS Organizations.</p><h3>3. Configure Delegated Administrator</h3><p>Assign the logging account as the delegated administrator for CloudWatch Logs Centralization.</p><h3>4. Create a Centralization Rule</h3><p>Select:</p><ul><li>Source accounts or OUs</li><li>Source regions</li><li>Destination region</li><li>Destination log group naming strategy</li></ul><h3>Log Group Naming Strategy</h3><p>AWS allows custom naming patterns for centralized log groups.</p><h3>Option 1: Single Log Group</h3><pre>/centralized-logs</pre><p>All logs from all accounts are stored in a single log group.</p><p><strong>Pros</strong></p><ul><li>Simple setup</li><li>Single place to search</li></ul><p><strong>Cons</strong></p><ul><li>Large log volume</li><li>Harder retention management</li><li>Queries may scan more data</li></ul><h3>Option 2: Account-Based Organization</h3><pre>/centralized/${source.accountId}/${source.region}</pre><p>Example:</p><pre>/centralized/1234567890/eu-central-1</pre><p>This separates logs by account and region.</p><h3>Option 3: Preserve Original Log Structure</h3><pre>/centralized/${source.accountId}/${source.region}${source.logGroup}</pre><p>Example:</p><pre>/centralized/1234567890/eu-central-1/aws/eks/prod/cluster</pre><p>This approach preserves the original CloudWatch log group hierarchy and is generally the most operationally friendly option.</p><h3>Identifying Source Accounts</h3><p>Even when using centralized logging, CloudWatch preserves source metadata.</p><p>Example Logs Insights query:</p><pre>fields @timestamp,<br>       @message,<br>       @aws.account,<br>       @aws.region<br>| sort @timestamp desc<br>| limit 50</pre><p>This allows teams to identify:</p><ul><li>Source AWS Account</li><li>Source Region</li></ul><p>without needing to access the original account.</p><h3>Important Limitation</h3><p><strong><em>CloudWatch Logs Centralization only replicates new log events after the centralization rule is created.</em></strong></p><p>It does <strong>not</strong> migrate historical log data.</p><p>If historical logs are required, they must be exported separately.</p><h3>What Happens If the Rule Is Removed?</h3><p>Deleting a centralization rule:</p><ul><li>Stops future log replication.</li><li>Does not delete already centralized logs.</li><li>Existing destination log groups remain intact.</li><li>Existing log events remain searchable.</li></ul><p>This makes it safe to modify or remove centralization rules without losing historical centralized data.</p><h3>Final Thoughts</h3><p>CloudWatch Logs Centralization significantly simplifies multi-account observability. For organizations already using AWS Organizations and IAM Identity Center, it provides a native, scalable, and operationally efficient way to aggregate logs without building custom logging pipelines.</p><p>For most enterprise environments, preserving the original log group structure using:</p><pre>/centralized/${source.accountId}/${source.region}${source.logGroup}</pre><p>offers the best balance between visibility, troubleshooting efficiency, and long-term maintainability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d9d0a9fdab4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Secure Aurora PostgreSQL User Management on AWS EKS with Terraform, Secrets Manager, and…]]></title>
            <link>https://medium.com/@pnkjofficial/building-secure-aurora-postgresql-user-management-on-aws-eks-with-terraform-secrets-manager-and-aa65dc8b2a1c?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa65dc8b2a1c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[aurora-postgresql]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 06:51:34 GMT</pubDate>
            <atom:updated>2026-06-12T06:51:34.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Secure Aurora PostgreSQL User Management on AWS EKS with Terraform, Secrets Manager, and Kubernetes Jobs</h3><p>As organizations move toward cloud-native platforms, managing database users securely becomes just as important as managing infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1CpWEQVRIitMjzGoRi4KCQ.png" /></figure><p>Recently, I worked on a solution to automate PostgreSQL user provisioning for Amazon Aurora PostgreSQL using Terraform, AWS Secrets Manager, EKS, and Kubernetes Jobs.</p><p>The goal was simple:</p><p>✅ No hardcoded passwords<br> ✅ No direct database connectivity from CI/CD pipelines<br> ✅ Fully automated and repeatable user creation<br> ✅ Secure credential storage and rotation-ready architecture</p><p>Here’s how we designed it.</p><h3>The Challenge</h3><p>We needed to create and manage PostgreSQL users across multiple Aurora clusters:</p><ul><li>Application runtime users</li><li>Read-only developer users</li><li>Development admin users</li></ul><p>Traditionally, this could be done using the Terraform PostgreSQL provider.</p><p>However, there was one problem.</p><p>The GitLab runners executing Terraform did not have direct connectivity to the Aurora clusters.</p><pre>GitLab Runner<br>      ❌<br> No Route to Aurora</pre><p>Meanwhile, EKS workloads already had internal connectivity.</p><p>Instead of opening additional network paths, we decided to execute the database bootstrap process directly from Kubernetes.</p><h3>High-Level Architecture</h3><pre>Terraform<br>    │<br>    ├── Creates Secrets Manager Secrets for Psql Users<br>    ├── Creates ConfigMap (SQL Script)<br>    └── Creates Kubernetes Job<br>                │<br>                ▼<br>     ┌─────────────────────┐<br>     │ Init Container      │<br>     │ amazon/aws-cli      │<br>     └─────────────────────┘<br>                │<br>     Fetch Secrets Manager Credentials<br>                │<br>                ▼<br>     Memory-backed Volume (tmpfs)<br>                │<br>                ▼<br>     ┌─────────────────────┐<br>     │ Main Container      │<br>     │ postgres:17         │<br>     └─────────────────────┘<br>                │<br>           Executes psql<br>                │<br>                ▼<br>      Aurora PostgreSQL Cluster</pre><h3>Why Kubernetes Jobs?</h3><p>Instead of giving Terraform direct access to Aurora, we leveraged EKS because:</p><ul><li>Pods already had network access to Aurora</li><li>Pod Identity provided secure AWS authentication</li><li>Jobs are easy to re-run</li><li>Terraform can wait for completion</li></ul><p>The Kubernetes Job became our database bootstrap engine.</p><h3>Password Generation</h3><p>Each database role receives its own password generated by Terraform.</p><pre>resource &quot;random_password&quot; &quot;rds_user&quot; {<br>  length  = 32<br>  special = true<br>}</pre><p>Passwords remain stable unless the resource is explicitly destroyed. This prevents unnecessary credential changes during routine deployments.</p><h3>Secure Credential Storage with Secrets Manager</h3><p>For every role and database pair, Terraform creates a dedicated secret.</p><p>Example:</p><pre>rds/api/app_user<br>rds/api/readonly_user<br>rds/api/dev_admin_user</pre><p>Secret structure:</p><pre>{<br>  &quot;username&quot;: &quot;app_user&quot;,<br>  &quot;password&quot;: &quot;********&quot;,<br>  &quot;engine&quot;: &quot;postgres&quot;,<br>  &quot;host&quot;: &quot;cluster.endpoint&quot;,<br>  &quot;port&quot;: 5432,<br>  &quot;dbname&quot;: &quot;app_db&quot;<br>}</pre><p>This structure aligns nicely with applications that consume credentials directly from AWS Secrets Manager.</p><h3>Retrieving Credentials Inside EKS</h3><p>The Kubernetes Job uses two containers.</p><h3>Container 1 — Fetch Credentials</h3><pre>amazon/aws-cli</pre><p>Responsibilities:</p><ul><li>Retrieve Aurora master credentials</li><li>Retrieve application user passwords</li><li>Store credentials in memory</li></ul><p>Example:</p><pre>aws secretsmanager get-secret-value</pre><p>The credentials are written to:</p><pre>/secrets/vars.sh</pre><h3>Why a Memory-Backed Volume?</h3><p>Instead of storing credentials on disk:</p><pre>empty_dir {<br>  medium = &quot;Memory&quot;<br>}</pre><p>This creates a tmpfs volume.</p><p>Benefits:</p><ul><li>Passwords never reach node storage</li><li>Data disappears when the pod terminates</li><li>Reduced credential exposure</li></ul><p>A small detail that significantly improves security posture.</p><h3>Executing SQL Securely</h3><p>The second container uses:</p><pre>postgres:17</pre><p>It loads credentials from the shared memory volume and executes the SQL bootstrap script.</p><pre>psql \<br>  --variable=&quot;app_user_password=$APP_PASS&quot; \<br>  --variable=&quot;readonly_user_password=$READONLY_PASS&quot;</pre><p>This approach avoids embedding passwords inside SQL files.</p><h3>Idempotent SQL Design</h3><p>One of the key requirements was safe re-execution.</p><p>Every role creation follows this pattern:</p><pre>DO $$<br>BEGIN<br>  IF NOT EXISTS (<br>      SELECT 1<br>      FROM pg_roles<br>      WHERE rolname = &#39;app_user&#39;<br>  ) THEN<br>      CREATE ROLE app_user WITH LOGIN;<br>  END IF;<br>END<br>$$;</pre><p>Password updates happen separately:</p><pre>ALTER ROLE app_user<br>WITH PASSWORD :&#39;app_user_password&#39;;</pre><p>This means:</p><p>ScenarioResultFirst deploymentRole createdSubsequent deploymentPassword updatedRe-run JobSafe</p><p>The process becomes completely repeatable.</p><h3>Role Design</h3><h3>app_user</h3><p>Application runtime account.</p><p>Permissions:</p><pre>SELECT<br>INSERT<br>UPDATE<br>DELETE</pre><p>No schema modifications allowed.</p><p>Perfect for Spring Boot applications.</p><h3>readonly_user</h3><p>Developer and support access.</p><p>Permissions:</p><pre>SELECT only</pre><p>No data modification.</p><h3>dev_admin_user</h3><p>Development environments only.</p><p>Permissions:</p><pre>ALL PRIVILEGES</pre><p>Useful for troubleshooting and testing.</p><h3>Waiting for Success</h3><p>Terraform waits until the Job finishes.</p><pre>wait_for_completion = true</pre><p>Benefits:</p><ul><li>Immediate feedback</li><li>Failed SQL fails the deployment</li><li>Easier troubleshooting</li></ul><p>If something goes wrong:</p><pre>kubectl logs &lt;pod-name&gt;</pre><p>Provides the full execution output.</p><h3>Security Benefits</h3><p>This design provides several advantages:</p><h3>No Hardcoded Passwords</h3><p>Passwords exist only in:</p><ul><li>Secrets Manager</li><li>Memory-backed volumes</li><li>Aurora</li></ul><h3>No CI/CD Database Connectivity</h3><p>GitLab never talks directly to Aurora.</p><p>This reduces attack surface and simplifies network design.</p><h3>Principle of Least Privilege</h3><p>Each role receives only the permissions required for its function.</p><p>Application users cannot perform schema changes.</p><p>Developers cannot accidentally modify production data.</p><h3>Ready for Rotation</h3><p>Since passwords originate in Secrets Manager, future rotation workflows become significantly easier.</p><h3>Lessons Learned</h3><p>A few principles stood out during implementation:</p><ol><li>Use Kubernetes Jobs for operational tasks that require VPC access.</li><li>Keep credentials in memory whenever possible.</li><li>Make SQL idempotent.</li><li>Separate runtime, migration, and administrative users.</li><li>Store all credentials in Secrets Manager rather than Terraform variables.</li></ol><p>These small architectural decisions create a solution that is secure, scalable, and easy to maintain.</p><h3>Final Thoughts</h3><p>Managing database users often becomes an afterthought in cloud-native environments. However, treating database identities the same way we treat infrastructure — as code, automated, auditable, and secure — provides significant operational and security benefits.</p><p>By combining:</p><ul><li>Amazon Aurora PostgreSQL</li><li>AWS Secrets Manager</li><li>Amazon EKS</li><li>Terraform</li><li>Kubernetes Jobs</li></ul><p>we created a fully automated database user provisioning workflow that requires no manual intervention and aligns with modern cloud security practices.</p><p>If you’re running Aurora in a multi-account AWS environment, this pattern can be a simple yet powerful way to standardize database access management across teams and environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa65dc8b2a1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Transit Gateway Security Group Referencing — Lessons Learned, Limitations, and Troubleshooting]]></title>
            <link>https://medium.com/@pnkjofficial/aws-transit-gateway-security-group-referencing-lessons-learned-limitations-and-troubleshooting-74d514cbc22d?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/74d514cbc22d</guid>
            <category><![CDATA[aws-security-group]]></category>
            <category><![CDATA[aws-landing-zone]]></category>
            <category><![CDATA[aws-transit-gateway]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 17:33:06 GMT</pubDate>
            <atom:updated>2026-06-03T17:33:06.400Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I was working on a multi-account AWS architecture where traffic needed to flow securely between workloads hosted in different AWS accounts through AWS Transit Gateway (TGW).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-fLZaZ2SwvSFwjubr858g.png" /></figure><p>The goal was straightforward:</p><pre>Account A<br>----------<br>Internal ALB<br>   ↓<br>Transit Gateway<br>   ↓<br>Account B<br>----------<br>Internal NLB</pre><p>Instead of managing CIDRs or prefix lists, I wanted to leverage AWS Transit Gateway Security Group Referencing to allow traffic based on Security Group membership.</p><p>While the feature looked promising, I encountered some unexpected limitations that are worth sharing.</p><h3>What is Transit Gateway Security Group Referencing?</h3><p>Traditionally, Security Group references only worked within the same VPC or in limited peering scenarios.</p><p>AWS introduced Security Group Referencing for Transit Gateway, allowing Security Groups in one VPC to reference Security Groups attached to resources in another VPC connected through the same Transit Gateway.</p><p>Benefits include:</p><ul><li>Reduced dependency on CIDR-based rules</li><li>Easier security management</li><li>Dynamic access control based on Security Groups</li><li>Simplified multi-account architectures</li></ul><h3>My Architecture</h3><p>The setup looked like this:</p><pre>Account A<br>----------<br>Internal ALB<br>SG: alb-sg<br>   ↓<br>AWS Network Firewall<br>   ↓<br>Transit Gateway<br>   ↓<br>Account B<br>----------<br>Internal NLB<br>SG: nlb-sg</pre><p>On the NLB Security Group, I created inbound rules:</p><pre>Port 80  -&gt; Source: alb-sg<br>Port 443 -&gt; Source: alb-sg</pre><p>The Transit Gateway attachments had Security Group Referencing enabled. Everything appeared correctly configured.</p><h3>The Problem</h3><p>Traffic consistently failed.</p><p>VPC Flow Logs on the NLB ENI showed:</p><pre>Source IP = ALB Private IP<br>Action    = REJECT</pre><p>Interestingly:</p><pre>Source = Prefix List      → Works<br>Source = ALB Security Group → Fails</pre><p>This immediately suggested that routing was not the issue.</p><h3>What I Verified</h3><h3>Transit Gateway Settings</h3><p>Verified on both VPC attachments:</p><pre>Security Group Referencing Support = Enabled</pre><h3>Security Group Rules</h3><p>The Security Group rule was confirmed as a valid SG reference:</p><pre>&quot;ReferencedGroupInfo&quot;: {<br>  &quot;GroupId&quot;: &quot;sg-xxxxxxxx&quot;,<br>  &quot;VpcId&quot;: &quot;vpc-xxxxxxxx&quot;<br>}</pre><p>This ruled out:</p><ul><li>Incorrect SG IDs</li><li>Invalid SG references</li><li>CIDR-based misconfigurations</li></ul><h3>Routing</h3><p>Confirmed:</p><ul><li>TGW route tables</li><li>VPC route tables</li><li>Return paths</li></ul><p>Traffic was reaching the NLB VPC successfully.</p><h3>NACLs</h3><p>Verified that required ports and ephemeral return traffic were allowed.</p><h3>The Root Cause</h3><p>The key discovery came from the AWS documentation.</p><p>AWS explicitly states:</p><p><strong><em>Security group referencing through Transit Gateway does not work across AWS Network Firewall or Gateway Load Balancer inspection paths.</em></strong></p><p>In our environment, traffic traversed AWS Network Firewall before reaching the Transit Gateway.</p><p>As a result:</p><pre>ALB SG Reference<br>       ↓<br>Not Evaluated Successfully<br>       ↓<br>Traffic Rejected</pre><p>Even though:</p><ul><li>TGW SG Referencing was enabled</li><li>Security Group references were valid</li><li>Routing was correct</li></ul><p>The inspection path introduced a limitation that prevented the feature from functioning as expected.</p><h3>Why Prefix Lists Worked</h3><p>A Prefix List rule evaluates:</p><pre>Source IP Address</pre><p>Whereas Security Group Referencing evaluates:</p><pre>Source Security Group Membership</pre><p>Because Prefix Lists rely only on IP matching, they continued to function correctly even when traffic traversed AWS Network Firewall.</p><h3>Recommended Workaround</h3><p>For architectures involving:</p><pre>ALB<br> ↓<br>AWS Network Firewall<br> ↓<br>Transit Gateway<br> ↓<br>NLB</pre><p>Use:</p><ul><li>Managed Prefix Lists</li><li>Source subnet CIDRs</li><li>Source VPC CIDRs</li></ul><p>instead of Security Group references.</p><p>Example:</p><pre>NLB Security Group<br>  Port 443<br>  Source = Managed Prefix List</pre><p><strong>This approach proved reliable and production-ready.</strong></p><h3>Key Takeaways</h3><p>Before implementing Transit Gateway Security Group Referencing:</p><h3>Verify TGW Configuration</h3><ul><li>TGW Security Group Referencing enabled</li><li>VPC Attachment Security Group Referencing enabled</li></ul><h3>Validate Security Group References</h3><p>Use:</p><pre>aws ec2 describe-security-group-rules</pre><p>and confirm:</p><pre>&quot;ReferencedGroupInfo&quot;</pre><p>exists.</p><h3>Check Flow Logs</h3><p>If you see:</p><pre>Traffic reaches destination ENI<br>Action = REJECT</pre><p>the issue is likely Security Group evaluation rather than routing.</p><h3>Understand the Limitation</h3><p>Security Group Referencing through Transit Gateway does not work across:</p><ul><li>AWS Network Firewall inspection paths</li><li>Gateway Load Balancer inspection paths</li></ul><p><strong><em>This limitation can be easy to miss during design reviews.</em></strong></p><h3>Final Thoughts</h3><p>Transit Gateway Security Group Referencing is a powerful feature for multi-account AWS environments. However, like many networking features, the implementation details matter.</p><p>If your architecture includes AWS Network Firewall or Gateway Load Balancer inspection VPCs, plan on using Prefix Lists or CIDR-based controls instead of Security Group references.</p><p>A few hours of troubleshooting can often be saved by understanding these limitations upfront.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74d514cbc22d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking About the Right Multi-Account Strategy for Containerized Applications on AWS: Scale…]]></title>
            <link>https://medium.com/@pnkjofficial/thinking-about-the-right-multi-account-strategy-for-containerized-applications-on-aws-scale-51684e6f9e0a?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/51684e6f9e0a</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[conatiner]]></category>
            <category><![CDATA[governance]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 17:57:31 GMT</pubDate>
            <atom:updated>2026-06-02T17:57:31.083Z</atom:updated>
            <content:encoded><![CDATA[<h3>Thinking About the Right Multi-Account Strategy for Containerized Applications on AWS: Scale, Security, and Governance</h3><p><em>Designing an enterprise-grade AWS container platform with centralized networking, Transit Gateway, Network Firewall, EKS Auto Mode, centralized logging, and hybrid connectivity.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAsYh_VTT76ZTEF0AVRWkQ.png" /></figure><p>In this article, I’ll walk through an enterprise-grade AWS container platform architecture designed around AWS Organizations, Amazon EKS Auto Mode, centralized networking, shared security controls, and centralized logging.</p><p>The goal of this architecture is simple:</p><p>• <em>Strong security boundaries<br></em>• <em>Clear separation of responsibilities<br></em>• <em>Scalability across environments and teams<br></em>• <em>Centralized governance<br></em>• <em>Reduced operational overhead<br></em>• <em>Platform self-service capabilities</em></p><h3>The Challenge</h3><p>Most AWS container deployments follow a simple pattern:</p><pre>Internet<br>   |<br> ALB<br>   |<br> EKS<br>   |<br>Database</pre><p>While this works for small workloads, it creates challenges at enterprise scale:</p><p>• Shared blast radius<br>• Complex network management<br>• Lack of centralized security controls<br>• Inconsistent governance<br>• Difficult auditing and compliance<br>• Operational overhead across multiple teams</p><p><em>To address these challenges, we adopted a multi-account architecture built around AWS Organizations.</em></p><h3>High-Level Architecture</h3><p>The platform consists of four primary accounts under single/multiple OUs -</p><h4>Edge Account</h4><p>Responsible for all internet-facing services.</p><h4>Services Hosted</h4><p>• AWS WAF<br>• Amazon CloudFront<br>• Amazon Route 53<br>• Static Website Hosting (Amazon S3)<br>• DNS Security Controls</p><h4>Responsibilities</h4><p>• Global traffic management<br>• DDoS protection<br>• Web application protection<br>• SSL/TLS termination<br>• Content delivery acceleration</p><p>Traffic enters through CloudFront, where WAF policies inspect requests before forwarding them to internal services.</p><h4>Benefits</h4><p>• Reduced attack surface<br>• Centralized internet exposure<br>• Improved performance through edge caching<br>• Consistent security enforcement</p><h4>Network Account</h4><p>Acts as the centralized hub for networking and connectivity.</p><p>Rather than allowing every workload account to manage its own networking, all shared network services are centralized.</p><h4>Transit Gateway Architecture</h4><p>A central AWS Transit Gateway (TGW) connects all participating accounts.</p><pre>Transit Gateway<br>                        |<br> -------------------------------------------------<br> |               |             |                |<br>Edge         Network      Workload          Logging</pre><p>Using AWS Resource Access Manager (RAM), the Transit Gateway is shared across accounts.</p><p>• Simplified VPC connectivity.<br>• Centralized route management.<br>• Easier account onboarding.<br>• Reduced network complexity.</p><p>Instead of managing dozens of VPC peering connections, all communication flows through the Transit Gateway.</p><p>One of the most important design decisions was ensuring that all traffic is inspected before entering or leaving workload environments.</p><p>To achieve this, AWS Network Firewall is deployed inside the Network Account.</p><p>For the corporate connectivity, Site2Site VPN can be deployed.</p><h4>Shared Services Inside the Network Account</h4><p>The Network Account also hosts shared platform services.</p><p>These services are consumed by workload accounts through private connectivity.</p><p>• Reverse Proxy Services<br>• Shared Internal Services<br>• PrivateLink Endpoints<br>• Common Networking Components</p><h4>Workload Account</h4><p>The Workload Account hosts all business applications and supporting services.</p><p><strong>Compute Layer:</strong> Built using Amazon EKS Auto Mode.</p><p>• EKS Auto Mode<br>• NLB Integration<br>• System Workloads<br>• Containerized Applications</p><p><strong><em>By leveraging EKS Auto Mode, platform teams can reduce node management complexity while maintaining Kubernetes flexibility.</em></strong></p><p><strong>Container Registry:</strong> Application images are stored in</p><p><strong>Data Layer:</strong> The architecture includes dedicated database services.<br><strong><em>Database traffic remains private and never traverses public networks.</em></strong></p><p><strong>Other Services:</strong> To reduce duplication across workloads.<br>AWS Secrets Manager, AWS Certificate Manager, Amazon CloudWatch, S3 Buckets, SNS, SES, Etc</p><h4>Logging Account</h4><p>Centralizes audit, operational, and security logs.</p><p>To address this, all logs are centralized into a dedicated Logging Account.</p><h3>Log Sources</h3><p>• CloudTrail<br>• CloudWatch Logs<br>• VPC Flow Logs<br>• EKS Control Plane Logs<br>• Application Logs<br>• WAF Logs<br>• Load Balancer Logs</p><h3>Why Centralized Logging Matters</h3><p>Imagine a workload account is compromised.</p><p>If logs reside in the same account, an attacker may attempt to delete evidence.</p><p>By centralizing logs into a dedicated account:</p><p>• Audit trails remain protected<br>• Security investigations become easier<br>• Compliance requirements are simplified<br>• Long-term retention is centralized</p><h3>Security Considerations</h3><p>Security is built into every layer of the platform.</p><h4>Identity Management</h4><p>AWS IAM Identity Center provides:</p><p>• Centralized authentication<br>• Role-based access control<br>• Least-privilege permissions<br>• Enterprise SSO integration</p><h4>Network Security</h4><p>Security controls include:</p><p>• AWS WAF<br>• AWS Network Firewall<br>• Security Groups<br>• Transit Gateway segmentation<br>• PrivateLink connectivity</p><h4>Secrets Management</h4><p>Sensitive information is never stored in code repositories. All secrets are managed through AWS Secrets Manager.</p><h4>Encryption</h4><p>All services use encryption at rest and in transit.</p><p>Examples include:</p><p>• Aurora Encryption<br>• EBS Encryption<br>• ECR Encryption<br>• TLS Everywhere</p><h3>Operational Benefits</h3><p>This architecture delivers several key advantages.</p><h4>Scalability</h4><p>New environments can be onboarded rapidly without redesigning networking or security controls.</p><h4>Governance</h4><p>Centralized controls ensure consistent security and compliance standards across teams.</p><h4>Reduced Blast Radius</h4><p>Issues within one account remain isolated from others.</p><h4>Simplified Operations</h4><p>Shared networking and logging reduce duplicated effort.</p><h4>Platform Standardization</h4><p>Development teams consume a standardized platform rather than building infrastructure independently.</p><h3>Lessons Learned</h3><p>Building an enterprise container platform is not simply about deploying Kubernetes.</p><p>Success depends on designing around:</p><p>• Security boundaries<br>• Governance<br>• Shared services<br>• Observability<br>• Network segmentation<br>• Operational ownership</p><p>The most successful platforms treat Kubernetes as one component of a larger ecosystem rather than the center of the architecture.</p><h3>Final Thoughts</h3><p>This multi-account AWS architecture provides a secure, scalable, and operationally efficient foundation for running containerized workloads at enterprise scale.</p><p>By separating responsibilities across Edge, Network, Workload, and Logging accounts, organizations can achieve:</p><p>✅ Strong security isolation<br>✅ Centralized governance<br>✅ Simplified networking<br>✅ Scalable Kubernetes operations<br>✅ Improved observability<br>✅ Enterprise-grade compliance readiness</p><p>As organizations continue adopting platform engineering practices, architectures like this help bridge the gap between cloud infrastructure and developer self-service, enabling teams to innovate faster while maintaining security and control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51684e6f9e0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why AWS EKS Auto Mode Is a Game Changer for Kubernetes Operations]]></title>
            <link>https://medium.com/@pnkjofficial/why-aws-eks-auto-mode-is-a-game-changer-for-kubernetes-operations-ed1a00234d1f?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed1a00234d1f</guid>
            <category><![CDATA[awscommunitybuilder]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws-eks-auto-mode]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[cloud-native]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Wed, 27 May 2026 17:51:08 GMT</pubDate>
            <atom:updated>2026-05-27T17:51:08.500Z</atom:updated>
            <content:encoded><![CDATA[<p>For years, running Kubernetes on AWS meant one thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpaP0_6fmutkQgaQJ5k_rA.png" /></figure><p>Managing infrastructure complexity. Even with Amazon EKS, platform teams still had to handle:</p><p>◉ Node Groups<br>◉ Auto Scaling Groups<br>◉ AMIs<br>◉ Cluster Autoscaler<br>◉ Karpenter<br>◉ Capacity management<br>◉ Instance patching<br>◉ Worker node upgrades<br>◉ Networking optimization<br>◉ Scaling policies</p><p>And while Kubernetes simplified application orchestration, infrastructure management itself remained operationally heavy.</p><p><strong><em>That’s exactly where </em>AWS EKS Auto Mode<em> changes the game.</em></strong></p><h3>What Is AWS EKS Auto Mode?</h3><p>AWS EKS Auto Mode is a fully managed Kubernetes compute experience where AWS automatically manages:</p><p>◉ Worker nodes<br>◉ Scaling<br>◉ Compute provisioning<br>◉ Capacity optimization<br>◉ Lifecycle management<br>◉ Patching<br>◉ Node replacement</p><p>Instead of manually defining EC2 worker nodes, you simply define workloads and AWS handles the infrastructure behind the scenes.</p><p>Think of it like:</p><p><strong><em>“Fargate flexibility with EC2-like Kubernetes compatibility.”</em></strong></p><h3>Traditional EKS vs EKS Auto Mode</h3><h4>Traditional EKS</h4><p>In traditional EKS, platform teams manage:</p><p>◉ Managed Node Groups<br>◉ Karpenter<br>◉ EC2 Launch Templates<br>◉ Cluster Autoscaler<br>◉ Instance types<br>◉ Spot strategy<br>◉ Capacity balancing</p><pre>eks_managed_node_groups = {<br>  general = {<br>    instance_types = [&quot;t3.medium&quot;]<br>    desired_size   = 2<br>  }<br>}</pre><p>This gives flexibility, but also creates operational overhead.</p><h4>EKS Auto Mode</h4><p>With Auto Mode:</p><pre>compute_config = {<br>  enabled    = true<br>  node_pools = [&quot;general-purpose&quot;]<br>}</pre><p>That’s it.</p><p>AWS dynamically decides:</p><p>◉ Instance family<br>◉ Scaling<br>◉ Capacity<br>◉ Lifecycle<br>◉ Placement<br>◉ Replacement</p><p>You focus on Kubernetes workloads instead of compute management.</p><h3>Key Benefits of EKS Auto Mode</h3><h3>1. Massive Reduction in Operational Overhead</h3><p>No more:</p><p>◉ Managing node groups<br>◉ Patching AMIs<br>◉ Upgrading workers<br>◉ Tuning autoscalers<br>◉ Handling scaling events manually</p><p><strong><em>AWS manages all of it.</em></strong></p><p>This is a huge win for:</p><p>◉ Small platform teams<br>◉ Fast-moving startups<br>◉ Enterprise internal platforms</p><h3>2. Better Resource Optimization</h3><p>AWS dynamically chooses the best infrastructure based on:</p><p>◉ CPU requests<br>◉ Memory requests<br>◉ Cluster demand<br>◉ AZ capacity<br>◉ Fleet availability</p><p><strong>This often leads to:<br></strong>◉ Better utilization<br>◉ Lower waste<br>◉ Improved scaling efficiency</p><h3>3. Faster Kubernetes Adoption</h3><p>Teams can now focus on:</p><p>◉ Deployments<br>◉ Ingress<br>◉ Security<br>◉ GitOps<br>◉ Observability<br>◉ Application reliability</p><p>instead of EC2 infrastructure management.</p><h3>4. Native AWS Scaling Intelligence</h3><p>Unlike traditional autoscaling approaches, AWS controls:</p><p>◉ Scheduling intelligence<br>◉ Capacity provisioning<br>◉ Infrastructure lifecycle</p><p>This gives AWS much deeper optimization capabilities internally.</p><h3>5. Cleaner Platform Architecture</h3><p>Old architecture:</p><pre>Kubernetes<br>  -&gt; Node Groups<br>      -&gt; ASGs<br>          -&gt; EC2</pre><p>New architecture:</p><pre>Kubernetes<br>  -&gt; AWS Managed Compute</pre><p>Much simpler operational model.</p><h3>Terraform Deployment Example</h3><h3>Basic EKS Auto Mode Configuration</h3><pre>module &quot;eks&quot; {<br>  source  = &quot;terraform-aws-modules/eks/aws&quot;<br>  version = &quot;~&gt; 21.22&quot;<br>  name               = &quot;eks-auto-mode&quot;<br>  kubernetes_version = &quot;1.35&quot;<br>  authentication_mode = &quot;API&quot;<br>  compute_config = {<br>    enabled    = true<br>    node_pools = [&quot;general-purpose&quot;]<br>  }<br>  vpc_id     = module.vpc.vpc_id<br>  subnet_ids = module.vpc.private_subnets<br>  enable_irsa = true<br>  endpoint_public_access = true<br>  addons = {<br>    vpc-cni = {<br>      most_recent = true<br>    }<br>    kube-proxy = {<br>      most_recent = true<br>    }<br>    eks-pod-identity-agent = {<br>      most_recent = true<br>    }<br>  }<br>}</pre><p>This completely removes:</p><p>◉ Managed Node Groups<br>◉ Launch Templates<br>◉ Autoscaling Groups<br>◉ Cluster Autoscaler</p><p>from your Terraform stack.</p><h3>Security Improvements</h3><p>EKS Auto Mode integrates very well with:</p><p>◉ IAM Roles for Service Accounts (IRSA)<br>◉ Pod Identity<br>◉ KMS<br>◉ Security Groups<br>◉ Private networking</p><p>This allows cleaner enterprise-grade platform security architectures.</p><h3>Cost Optimization Benefits</h3><p>EKS Auto Mode can reduce costs through:</p><p>◉ Better infrastructure packing<br>◉ Dynamic scaling<br>◉ Smarter capacity selection<br>◉ Reduced idle nodes<br>◉ Operational efficiency savings</p><p>Many organizations underestimate the hidden engineering cost of Kubernetes operations.</p><p>Reducing infrastructure management itself is often a larger saving than EC2 optimization alone.</p><h3>Real Enterprise Use Cases</h3><p>EKS Auto Mode is excellent for:</p><p>✅ Internal developer platforms<br>✅ Microservices platforms<br>✅ Dynamic environments<br>✅ Development clusters<br>✅ Shared Kubernetes platforms<br>✅ GitOps-based environments<br>✅ Rapid platform deployments</p><h3>Important Limitations</h3><p>EKS Auto Mode is powerful, but not perfect for every workload.</p><h3>Limited Infrastructure Control</h3><p>You cannot tightly control:</p><p>◉ Exact EC2 family<br>◉ Dedicated node types<br>◉ GPU optimization<br>◉ ARM-only enforcement<br>◉ Custom AMIs</p><p>For example:</p><pre>node_pools = [&quot;general-purpose&quot;]</pre><p>does NOT mean:</p><pre>Use t4g.small</pre><p>AWS chooses compute dynamically.</p><h3>When NOT To Use EKS Auto Mode</h3><p>You may still prefer:</p><p>◉ Managed Node Groups<br>◉ Karpenter</p><p>for:</p><p>◉ GPU workloads<br>◉ Dedicated infra isolation<br>◉ Specialized compute<br>◉ Compliance-heavy environments<br>◉ Performance-sensitive systems<br>◉ Custom AMIs<br>◉ Graviton-only clusters</p><h3>Final Thoughts</h3><p>AWS EKS Auto Mode represents a major evolution in Kubernetes operations.</p><p>For years, Kubernetes infrastructure management itself became a platform engineering problem.</p><p>Now AWS is moving infrastructure ownership deeper into the managed service layer.</p><p>The result:</p><p>◉ Less operational overhead<br>◉ Faster platform delivery<br>◉ Simpler Kubernetes management<br>◉ Better scaling experience<br>◉ Reduced infrastructure complexity</p><p>EKS Auto Mode won’t replace every Kubernetes architecture overnight.</p><p>But it absolutely changes how modern AWS platform teams think about Kubernetes infrastructure.</p><p>And honestly, that shift is long overdue.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed1a00234d1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Challenges of AWS Control Tower Nobody Talks About]]></title>
            <link>https://medium.com/@pnkjofficial/the-hidden-challenges-of-aws-control-tower-nobody-talks-about-07b30fed8c2e?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/07b30fed8c2e</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-landing-zone]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[aws-control-tower]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Tue, 26 May 2026 17:21:48 GMT</pubDate>
            <atom:updated>2026-05-26T17:21:48.801Z</atom:updated>
            <content:encoded><![CDATA[<p>The Dark Side of AWS Control Tower (And How We Solved It)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnVB_MWSoQfS5KmMNatgJA.png" /></figure><p>When most engineers talk about AWS Control Tower, the conversation usually ends at “landing zone setup completed successfully.”</p><p>But the real challenges begin after the deployment.</p><p>At a small scale, AWS Control Tower feels clean and manageable. At enterprise scale — with multiple OUs, SCPs, AFT pipelines, IAM Identity Center integrations, and Terraform automation — things become far more complicated.</p><p>Over the last few months, while implementing and automating AWS account provisioning using AWS Control Tower and Account Factory for Terraform (AFT), we encountered several operational challenges that documentation rarely talks about.</p><p>This article covers some of the biggest hidden challenges we faced and the lessons we learned while running AWS Control Tower in production.</p><h4>① — Drift Becomes a Silent Operational Problem</h4><p>One of the biggest surprises with AWS Control Tower was how frequently configuration drift can happen across accounts.</p><p>At the beginning, everything looks standardized:</p><p>⦿ <em>Guardrails are enabled<br></em>⦿ <em>SCPs are attached<br></em>⦿ <em>Baselines are configured<br></em>⦿ <em>IAM Identity Center permissions are working</em></p><p>But over time, manual changes inside member accounts slowly create inconsistencies.</p><p>Examples we encountered:</p><p>⦿ <em>IAM roles modified manually<br></em>⦿ <em>CloudTrail configuration drift<br></em>⦿ <em>Security services were disabled accidentally<br></em>⦿ <em>SCPs detached temporarily and never reattached<br></em>⦿ <em>Networking resources modified outside Terraform</em></p><p>The difficult part is that drift is often invisible until something breaks.</p><p>⦿ <em>A deployment suddenly fails.<br></em>⦿ <em>A permission stops working.<br></em>⦿ <em>A security audit identifies missing controls.</em></p><p>And then the investigation begins.</p><p>One important lesson we learned:<br>Control Tower provides governance, but it does not eliminate operational discipline.</p><p>Terraform, GitOps workflows, periodic drift detection, and strict change management are still necessary.</p><h4>②— SCPs Can Break More Than You Expect</h4><p>Service Control Policies (SCPs) are incredibly powerful — and also one of the easiest ways to accidentally break cloud operations.</p><p>During implementation, we experienced several situations where SCPs blocked:</p><p>⦿ <em>Terraform deployments<br></em>⦿ <em>IAM role assumptions<br></em>⦿ <em>AWS service integrations<br></em>⦿ <em>Lambda execution<br></em>⦿ <em>Security tooling<br></em>⦿ <em>Cross-account automation</em></p><p>The hardest part about SCP troubleshooting is that the error messages are rarely clear.</p><p>Most failures simply show:<br>“<strong>Access Denied</strong>”</p><p>Without directly indicating:</p><p>⦿ <em>Which SCP caused the issue<br></em>⦿ <em>Which inherited OU policy blocked the action<br></em>⦿ <em>Which explicit denial was triggered</em></p><p>In large AWS Organizations with nested OUs, troubleshooting SCP inheritance becomes extremely difficult.</p><p>One important operational lesson:<br>Never deploy SCPs directly to production OUs without testing them first in lower environments.</p><p>We also learned that overly restrictive SCP strategies slow down platform engineering teams significantly if not designed carefully.</p><h4>③— Moving AWS Accounts Between OUs Is More Complicated Than Expected</h4><p>On paper, moving AWS accounts between Organizational Units (OUs) looks simple.</p><p>In reality, it introduces several hidden operational risks.</p><p>When accounts move between OUs:</p><p>⦿ <em>Different SCPs get applied<br></em>⦿ <em>New guardrails become active<br></em>⦿ <em>Existing permissions may stop working<br></em>⦿ <em>Terraform pipelines may fail<br></em>⦿ <em>IAM Identity Center assignments may behave differently</em></p><p><strong><em>One challenge we faced was automating account movement dynamically without manually updating Terraform code every time a new account was created.</em></strong></p><p>At smaller scale, manual account mapping works. At enterprise scale, it quickly becomes unmanageable.</p><p>We eventually started dynamically fetching AWS account IDs from Organizational Units and automating policy assignments based on OU membership instead of maintaining static account lists.</p><p><strong><em>That significantly reduced operational overhead and made the platform more scalable.</em></strong></p><h4>④<strong> — IAM Identity Center Adds Complexity at Scale</strong></h4><p>AWS IAM Identity Center simplifies centralized authentication, but operational complexity increases rapidly in multi-account environments.</p><p>Some challenges we encountered:</p><p>⦿ <em>Permission set propagation delays<br></em>⦿ <em>Cross-account assignment inconsistencies<br></em>⦿ <em>Terraform provider authentication issues<br></em>⦿ <em>Session expiration during automation<br></em>⦿ <em>Confusing permission troubleshooting</em></p><p>One particularly frustrating issue was timing delays.</p><p><strong><em>Sometimes permission assignments would appear successful, but users still could not access accounts immediately because propagation across AWS Organizations was delayed.</em></strong></p><p>This became especially problematic in CI/CD automation workflows where timing consistency matters.</p><p>Another challenge was Terraform integration.</p><p>Managing IAM Identity Center resources through Terraform across multiple accounts and environments required careful provider configurations and dependency handling.</p><p><strong><em>At enterprise scale, authentication architecture becomes just as important as infrastructure architecture.</em></strong></p><h4>⑤<strong>— AFT Is Powerful — But Not Fully Flexible</strong></h4><p>AWS Account Factory for Terraform (AFT) provides a strong foundation for AWS account provisioning automation.</p><p>But once customization requirements increase, limitations start appearing.</p><p>Some areas where we faced challenges:</p><p>⦿ <em>Custom workflow integrations<br></em>⦿ <em>Multi-stage approval handling<br></em>⦿ <em>External CI/CD integration<br></em>⦿ <em>Dynamic OU logic<br></em>⦿ <em>Advanced account lifecycle management</em></p><p>By default, AFT expects a relatively opinionated workflow. However, enterprise environments often require:</p><p>⦿ <em>GitLab integration<br></em>⦿ <em>Custom branching models<br></em>⦿ <em>External approvals<br></em>⦿ <em>Additional compliance validations<br></em>⦿ <em>Dynamic policy assignment logic</em></p><p>We eventually had to build additional automation layers around AFT to achieve the flexibility we needed.</p><p>AFT accelerates adoption significantly, but most enterprises will still need custom engineering around it. Terraform State Handling Becomes Critical</p><h4><strong>⑥— Terraform State Handling Becomes Critical</strong></h4><p>Terraform works extremely well in AWS Control Tower environments — until state management becomes fragmented.</p><p>As the number of AWS accounts and Terraform pipelines grows, state handling becomes one of the most critical operational concerns.</p><p>Some common problems we faced:</p><p>⦿ <em>State locking conflicts<br></em>⦿ <em>Cross-account provider complexity<br></em>⦿ <em>Remote state dependency issues<br></em>⦿ <em>CI/CD race conditions<br></em>⦿ <em>Manual state recovery situations</em></p><p>One failed pipeline can leave infrastructure in partially applied states, creating difficult recovery scenarios.</p><p>Another hidden challenge is provider authentication.</p><p>When Terraform manages resources across multiple AWS accounts with IAM Identity Center or assumed roles, provider configurations become increasingly complex.</p><p>At enterprise scale, Terraform architecture matters just as much as Terraform code itself.</p><p>Proper backend isolation, state locking, reusable modules, and strong pipeline governance become essential for long-term stability.</p><h4><strong>⑦— Final Thoughts</strong></h4><p>AWS Control Tower is an excellent platform for building multi-account AWS environments.</p><p>But the real engineering challenge is not deployment. It is long-term operational management. The biggest lesson we learned is this:</p><p>Cloud governance is not a one-time setup. It is an ongoing platform engineering problem.</p><p>Drift management, SCP strategy, account lifecycle automation, authentication design, Terraform architecture, and CI/CD governance all become critical as organizations scale.</p><p>The AWS documentation explains how to deploy Control Tower.</p><p>Operational experience teaches you how to survive it.</p><p>If you are planning to implement AWS Control Tower at enterprise scale, invest early in:</p><p>⦿ <em>Automation<br></em>⦿ <em>Standardization<br></em>⦿ <em>Drift detection<br></em>⦿ <em>CI/CD governance<br></em>⦿ <em>Terraform architecture<br></em>⦿ <em>SCP testing strategies</em></p><p>It will save you significant operational pain later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07b30fed8c2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating AWS Account Factory for Terraform (AFT) Deployment Using GitLab CI/CD and Terraform]]></title>
            <link>https://medium.com/@pnkjofficial/automating-aws-account-factory-for-terraform-aft-deployment-using-gitlab-ci-cd-and-terraform-a6c1b272ecc1?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6c1b272ecc1</guid>
            <category><![CDATA[aws-account-factory]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-control-tower]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Fri, 22 May 2026 18:12:11 GMT</pubDate>
            <atom:updated>2026-05-22T18:12:11.319Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing AWS multi-account environments manually becomes difficult as organizations scale. Recently, we implemented a fully automated deployment process for AWS Account Factory for Terraform (AFT) using GitLab CI/CD and Terraform to simplify provisioning, governance, and infrastructure management across AWS accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Shd-Ll7yikHuEENO_fFzBQ.png" /><figcaption>AFT Deployment</figcaption></figure><p>In this article, I’ll share the overall setup and the Terraform + GitLab CI/CD implementation we used to automate AFT deployment.</p><h3>Why We Chose AFT?</h3><p>As our AWS environment continued growing, we needed:</p><ul><li>Automated AWS account provisioning</li><li>Standardized infrastructure deployment</li><li>CI/CD-driven automation</li><li>Scalable multi-account management</li></ul><p>AWS AFT helped us achieve this by integrating AWS Control Tower with Terraform-based account provisioning and customization.</p><h3>Prerequisites for AFT Deployment</h3><p>Before deploying AWS AFT, a few foundational services and configurations must already exist.</p><p><strong><em>A dedicated AWS account within the AWS Control Tower environment will be used to manage AFT.</em></strong></p><ul><li>AWS Control Tower should be deployed.</li><li>An AWS Account should be created manually for AFT.</li><li><a href="https://medium.com/@pnkjofficial/from-static-aws-keys-to-gitlab-oidc-building-a-secure-terraform-ci-cd-pipeline-on-aws-bdac4314a05d">OIDC </a>should be configured to run the GitLab pipeline for AFT.</li><li>Admin Privilege required to deploy/manage AFT.</li></ul><h4>Required AWS Accounts</h4><p>The following accounts were already available through the AWS Control Tower setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*slSaV-BpwfYpcW5fy2WjGA.png" /></figure><h3>AFT Module Deployment</h3><p>First, it needs to be deployed using AWS AFT with the official Terraform module.</p><p><strong><em>Note:</em></strong><em> AFT deployment should be executed from the AWS Control Tower management account. Make sure the Terraform provider is configured accordingly for the Control Tower environment.</em></p><pre>module &quot;aft&quot; {<br>  source  = &quot;aws-ia/control_tower_account_factory/aws&quot;<br>  version = &quot;1.20.0&quot;<br>  ct_management_account_id    = var.management_account_id<br>  log_archive_account_id      = var.log_archive_account_id<br>  audit_account_id            = var.audit_account_id<br>  aft_management_account_id   = var.aft_management_account_id<br>  ct_home_region              = &quot;us-east-1&quot;<br>  terraform_version           = &quot;1.8.5&quot;<br>  aft_feature_cloudtrail_data_events = true<br>}</pre><h3>Account Provisioning Using AFT</h3><p>Once AFT was deployed successfully, new AWS accounts could be provisioned automatically using Terraform.</p><h4>AFT Repository Structure</h4><p>AWS AFT creates and manages multiple repositories for account provisioning and customization workflows.</p><p><strong><em>Below are the primary repositories used during the implementation. If you are using the CI/CD pipeline, you can clone these repositories into a new project to manage AWS account provisioning through GitLab commits. By default, AFT automatically creates repositories in AWS CodeCommit; however, to establish a streamlined workflow from GitLab, you can configure repository mirroring so that every commit in GitLab automatically triggers and updates the corresponding CodeCommit repository.</em></strong></p><p><strong>Repo Download Link</strong> — <a href="https://github.com/aws-ia/terraform-aws-control_tower_account_factory/tree/main/sources/aft-customizations-repos">https://github.com/aws-ia/terraform-aws-control_tower_account_factory/tree/main/sources/aft-customizations-repos</a></p><h4><strong>1. aft-account-request</strong></h4><p>This repository is responsible for creating new AWS account requests using Terraform.</p><h4>Purpose</h4><p>➜ Provision new AWS accounts<br>➜ Define account metadata<br>➜ Configure OU placement<br>➜ Add account tags</p><p>Example Account Request</p><pre>module &quot;sandbox_account&quot; {<br>  source = &quot;./modules/aft-account-request&quot;<br>  control_tower_parameters = {<br>    AccountEmail              = &quot;sandbox-account@company.com&quot;<br>    AccountName               = &quot;Sandbox-Account&quot;<br>    ManagedOrganizationalUnit = &quot;Sandbox&quot;<br>    SSOUserEmail              = &quot;cloudadmin@company.com&quot;<br>    SSOUserFirstName          = &quot;Cloud&quot;<br>    SSOUserLastName           = &quot;Admin&quot;<br>  }<br>  account_tags = {<br>    Environment = &quot;Sandbox&quot;<br>    ManagedBy   = &quot;Terraform&quot;<br>  }<br>}</pre><h4>2. aft-account-customizations</h4><p>This repository is used for account-level customizations after account provisioning.</p><h4>Purpose</h4><p>➜ Deploy IAM roles<br>➜ Configure SCPs<br>➜ Enable security tooling<br>➜ Deploy baseline infrastructure</p><h4>3. aft-account-provisioning-customizations</h4><p>This repository manages provisioning-time customizations.</p><h4>Purpose</h4><p>➜ Execute bootstrap actions<br>➜ Configure networking<br>➜ Apply mandatory configurations immediately after provisioning</p><h4>4. aft-global-customizations</h4><p>This repository handles organization-wide configurations shared across all AWS accounts.</p><h4>Purpose -</h4><p>➜ Global IAM policies<br>➜ Organization-wide security controls<br>➜ Shared monitoring integrations<br>➜ Compliance configurations</p><h4><strong>This enabled fully automated onboarding of AWS accounts directly via GitLab pipelines, without manual Control Tower interaction.</strong></h4><h3>Benefits Achieved</h3><p>After implementing the automation, we achieved:</p><p>➜Faster AWS account provisioning<br>➜Reduced manual operational effort<br>➜Better governance across AWS accounts<br>➜Improved deployment consistency<br>➜Easier onboarding of new AWS accounts</p><p>The GitLab CI/CD integration significantly simplified operational management for our platform team</p><h3>Final Thoughts</h3><p>Automating AWS AFT deployment using Terraform and GitLab CI/CD helped us build a scalable and governed AWS multi-account environment with minimal manual intervention.</p><p>Although setting up AFT requires careful planning around Control Tower, Terraform modules, IAM permissions, and pipeline orchestration, the long-term operational benefits are significant.</p><p>For organizations managing multiple AWS accounts, automating AFT deployments can greatly improve governance, scalability, and infrastructure consistency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6c1b272ecc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform State Migration for AWS AFT Separation Without Resource Recreation]]></title>
            <link>https://medium.com/@pnkjofficial/terraform-state-migration-for-aws-aft-separation-without-resource-recreation-80130cedfde0?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/80130cedfde0</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[dev-sec]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Thu, 21 May 2026 17:34:53 GMT</pubDate>
            <atom:updated>2026-05-21T17:34:53.003Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Solving AWS AFT and Terraform State Separation Challenges in Enterprise CI/CD</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRHklU12WA7UB_U2Hg8wlQ.png" /><figcaption>TF STATE SEPRATION</figcaption></figure><p>Recently, I had to separate an existing AWS Account Factory for Terraform (AFT) deployment from a shared Terraform governance state into its own isolated Terraform state and pipeline.</p><p>The challenge was:</p><p>→ Existing infrastructure was already deployed<br>→ AFT resources were mixed with:<br>→ OU management<br>→ SCP policies<br>→ IAM Identity Center resources<br>→ Moving aft.tf into a separate folder could accidentally trigger:<br>→ Resource recreation<br>→ Drift<br>→ Destroy operations</p><p>The goal was to safely split the Terraform state without impacting live AWS infrastructure.</p><h3>Existing Structure</h3><p>Initial repository structure:</p><pre>terraform/<br>├── account-assignments.tf<br>├── backend.tf<br>├── context.tf<br>├── ous.tf<br>├── scps.tf<br>├── permission-sets.tf<br>├── providers.tf<br>├── users_groups.tf<br>├── aft.tf</pre><p>All resources were managed using a single Terraform state.</p><h3>Problem</h3><p>Every governance change triggered the entire Terraform execution, including AFT.</p><p>This caused:</p><p>→ Slow CI/CD pipelines<br>→ Unnecessary AFT validation<br>→ Large Terraform plans<br>→ Increased state lock duration</p><p>To optimize this, AFT needed:</p><p>→ Separate Terraform state<br>→ Separate CI stage<br>→ Isolated execution</p><h3>Final Target Architecture</h3><pre>terraform/<br>├── account-assignments.tf<br>├── backend.tf<br>├── context.tf<br>├── ous.tf<br>├── scps.tf<br>├── permission-sets.tf<br>├── providers.tf<br>├── users_groups.tf<br>├── aft_enablement_tf/<br>    └── aft.tf<br>    ├── backend.tf<br>    ├── providers.tf<br>    └── versions.tf</pre><p>With:</p><p>→ Independent state files<br>→ Isolated pipeline execution<br>→ No resource recreation</p><h3>Important Learning</h3><p><em>Never do all of these together:</em></p><p>→ Move Terraform code<br>→ Change backend<br>→ Change provider<br>→ Apply immediately</p><p><strong><em>That is the fastest path to accidental resource destruction.</em></strong></p><p>The safest approach is:</p><ol><li>Split state first</li><li>Verify plans</li><li>Then isolate backend and pipelines</li></ol><h3>Step 1 — Download Existing Terraform State</h3><p>Download the current Terraform state locally from S3:</p><pre>aws s3 cp s3://YOUR_BUCKET/YOUR_KEY/main.tfstate .</pre><p>Always create backups first:</p><pre>cp main.tfstate main.tfstate.backup</pre><h3>Step 2 — Create Empty AFT State File</h3><p>Create a new empty Terraform state:</p><pre>echo &#39;{&quot;version&quot;:4,&quot;resources&quot;:[]}&#39; &gt; aft.tfstate</pre><h3>Step 3 — Identify AFT Resources</h3><p>List all AFT resources from the existing state:</p><pre>terraform state list -state=main.tfstate | grep module.aft</pre><p>Example output:</p><pre>module.aft.aws_s3_bucket.example<br>module.aft.module.vpc.aws_vpc.main<br>module.aft.aws_codepipeline.pipeline</pre><p>This avoids manual JSON editing.</p><h3>Step 4 — Move AFT Resources Into New State</h3><p>Use Terraform state migration commands locally:</p><pre>for r in $(terraform state list -state=main.tfstate | grep module.aft); do<br>  terraform state mv \<br>    -state=main.tfstate \<br>    -state-out=aft.tfstate \<br>    &quot;$r&quot; &quot;$r&quot;<br>done</pre><p>This safely:</p><p>→ Removes AFT resources from the original state<br>→ Moves them into a new state<br>→ Preserves resource IDs<br>→ Avoids recreation</p><p>Terraform automatically creates backup files during migration. That is expected behavior.</p><h3>Step 5 — Verify Both States</h3><h4>Old State</h4><p>Verify AFT resources are removed:</p><pre>terraform state list -state=main.tfstate | grep module.aft</pre><p>Expected output:</p><pre>(no output)</pre><h4>AFT State</h4><p>Verify only AFT resources exist:</p><pre>terraform state list -state=aft.tfstate</pre><p>Expected output:</p><pre>module.aft.*</pre><h3>Step 6 — Upload Updated States to S3</h3><p>Upload Old state:</p><pre>aws s3 cp main.tfstate s3://YOUR_BUCKET/old_terraform.tfstate</pre><p>Upload AFT state:</p><pre>aws s3 cp aft.tfstate s3://YOUR_BUCKET/new_aft.tfstate</pre><h3>Step 7 — Configure Separate Backends</h3><h3>OLD Backend</h3><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;YOUR_BUCKET&quot;<br>    key    = &quot;old_terraform.tfstate&quot;<br>    region = &quot;eu-central-1&quot;<br>  }<br>}</pre><h3>AFT Backend</h3><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;YOUR_BUCKET&quot;<br>    key    = &quot;new_aft.tfstate&quot;<br>    region = &quot;eu-central-1&quot;<br>  }<br>}</pre><h3>Step 8 — Validate Terraform Plans</h3><p>Before applying anything: Run Terraform plan for both stacks. Expected result:</p><pre>No changes</pre><p>This confirms:</p><p>→ State migration succeeded<br>→ Terraform recognizes existing infrastructure<br>→ No recreation or destroy operations will occur</p><h3>CI/CD Pipeline Optimization</h3><p>After separating the state, the pipeline was split into:</p><ul><li>Auto Terraform execution</li><li>Manual AFT execution (Because it would be run very rarely)</li></ul><p>This significantly reduced:</p><ul><li>Pipeline duration</li><li>Terraform initialization time</li><li>Unnecessary Control Tower/AFT validations</li></ul><h3>Key Takeaways</h3><ul><li>Separate Terraform states for governance, and AFT is a best practice</li><li>Use terraform state mv instead of manual JSON editing</li><li>Always verify plans before applying</li><li>Never migrate the state and backend blindly in one step</li><li>Backup Terraform state before every migration</li></ul><p>This approach enabled a clean enterprise-grade Terraform separation without impacting existing AWS resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80130cedfde0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Stopped Rotating IAM Keys Manually — Here’s the AWS Framework We Built]]></title>
            <link>https://medium.com/@pnkjofficial/we-stopped-rotating-iam-keys-manually-heres-the-aws-framework-we-built-19f5215d6013?source=rss-2c3532758bc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/19f5215d6013</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Pankaj Gupta]]></dc:creator>
            <pubDate>Wed, 20 May 2026 18:09:19 GMT</pubDate>
            <atom:updated>2026-05-20T18:09:19.900Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Building an Enterprise-Scale AWS IAM Access Key Rotation Framework Across Multiple AWS Accounts</em></strong></p><p>Managing AWS IAM access keys across multiple AWS accounts can quickly become a security and operational nightmare. As organizations scale their cloud footprint, manually rotating access keys becomes inefficient, error-prone, and difficult to audit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ab6Z2ltsGRCpORuav6Wt_A.png" /></figure><p>To solve this challenge, I designed and implemented a centralized AWS-native automation framework that securely rotates IAM access keys across all child AWS accounts from a central management account.</p><p>The entire solution was built using serverless and Infrastructure-as-Code principles, leveraging:</p><p>➡️ <em>AWS Lambda<br></em>➡️ <em>AWS STS AssumeRole<br></em>➡️ <em>AWS Organizations<br></em>➡️ <em>AWS Secrets Manager<br></em>➡️ <em>Amazon SES<br></em>➡️ <em>CloudWatch<br></em>➡️ <em>CloudFormation StackSets<br></em>➡️ <em>Terraform</em></p><p>This solution automated the complete IAM access key lifecycle while maintaining centralized governance, auditability, and security compliance.</p><h3>The Problem</h3><p>In enterprise AWS environments, IAM access keys are still widely used for:</p><p>➡️ Legacy applications<br>➡️ CI/CD pipelines<br>➡️ Automation scripts<br>➡️ External integrations<br>➡️ Third-party tools</p><p><strong><em>However, managing these keys manually introduces several problems:</em></strong></p><p>➔ Old keys remain active indefinitely<br>➔ Keys are shared insecurely<br>➔ Manual rotation is operationally difficult<br>➔ Audit findings increase over time<br>➔ Compliance enforcement becomes inconsistent</p><h4><strong>The challenge becomes even more complex in a multi-account AWS Organization.</strong></h4><p>The objective was clear:</p><p>✅ Centralize IAM key rotation<br>✅ Automate the full lifecycle<br>✅ Avoid permanent credentials<br>✅ Securely distribute new keys<br>✅ Scale across all AWS accounts<br>✅ Enforce compliance automatically</p><h3>High-Level Architecture</h3><p>The architecture was designed around a centralized security account responsible for managing IAM key rotation across all customer or child AWS accounts.</p><h3>Core Components</h3><h3>1. KeyRotationLambda</h3><p>The primary Lambda function is responsible for:</p><p>‣ <em>Fetching all active child accounts from AWS Organizations<br>‣ Assuming IAM roles in child accounts using STS<br>‣ Identifying IAM users eligible for rotation<br>‣ Generating new access keys<br>‣ Inactivating old keys<br>‣ Deleting expired keys<br>‣ Storing keys securely in AWS Secrets Manager<br>‣ Sending success responses to EmailLambda</em></p><p><strong>This Lambda acted as the orchestration engine of the entire solution.</strong></p><pre># ============================================================<br># Lambda Function 1 : KeyRotationLambda<br># ============================================================<br># Features:<br># - Fetch child AWS accounts from OU<br># - Assume cross-account IAM role<br># - Rotate IAM access keys<br># - Store keys in Secrets Manager<br># - Trigger Email Lambda<br># ============================================================<br><br>import boto3<br>import json<br>import os<br>from datetime import datetime, timezone<br><br>ROTATION_DAYS = int(os.environ.get(&quot;ROTATION_DAYS&quot;, 90))<br>INACTIVE_DAYS = int(os.environ.get(&quot;INACTIVE_DAYS&quot;, 100))<br>DELETE_DAYS = int(os.environ.get(&quot;DELETE_DAYS&quot;, 120))<br><br>ROLE_NAME = os.environ.get(&quot;ROLE_NAME&quot;, &quot;KeyRotationRole&quot;)<br>EMAIL_LAMBDA = os.environ.get(&quot;EMAIL_LAMBDA&quot;)<br><br>organizations = boto3.client(&quot;organizations&quot;)<br>sts = boto3.client(&quot;sts&quot;)<br>lambda_client = boto3.client(&quot;lambda&quot;)<br><br><br>def lambda_handler(event, context):<br><br>    accounts = get_all_accounts()<br><br>    for account in accounts:<br>        account_id = account[&quot;Id&quot;]<br><br>        print(f&quot;Processing Account : {account_id}&quot;)<br><br>        try:<br>            creds = assume_role(account_id)<br><br>            iam = boto3.client(<br>                &quot;iam&quot;,<br>                aws_access_key_id=creds[&quot;AccessKeyId&quot;],<br>                aws_secret_access_key=creds[&quot;SecretAccessKey&quot;],<br>                aws_session_token=creds[&quot;SessionToken&quot;]<br>            )<br><br>            secretsmanager = boto3.client(<br>                &quot;secretsmanager&quot;,<br>                aws_access_key_id=creds[&quot;AccessKeyId&quot;],<br>                aws_secret_access_key=creds[&quot;SecretAccessKey&quot;],<br>                aws_session_token=creds[&quot;SessionToken&quot;]<br>            )<br><br>            users = iam.list_users()[&quot;Users&quot;]<br><br>            for user in users:<br><br>                username = user[&quot;UserName&quot;]<br><br>                if not should_rotate_user(user):<br>                    continue<br><br>                print(f&quot;Checking user : {username}&quot;)<br><br>                keys = iam.list_access_keys(UserName=username)[&quot;AccessKeyMetadata&quot;]<br><br>                for key in keys:<br><br>                    access_key_id = key[&quot;AccessKeyId&quot;]<br>                    create_date = key[&quot;CreateDate&quot;]<br><br>                    age = (datetime.now(timezone.utc) - create_date).days<br><br>                    print(f&quot;Key Age : {age}&quot;)<br><br>                    # ROTATE KEY<br>                    if age &gt;= ROTATION_DAYS and key[&quot;Status&quot;] == &quot;Active&quot;:<br><br>                        new_key = iam.create_access_key(<br>                            UserName=username<br>                        )[&quot;AccessKey&quot;]<br><br>                        secret_name = f&quot;{username}-access-key&quot;<br><br>                        secret_value = {<br>                            &quot;AccessKeyId&quot;: new_key[&quot;AccessKeyId&quot;],<br>                            &quot;SecretAccessKey&quot;: new_key[&quot;SecretAccessKey&quot;]<br>                        }<br><br>                        store_secret(<br>                            secretsmanager,<br>                            secret_name,<br>                            secret_value<br>                        )<br><br>                        invoke_email_lambda(<br>                            username,<br>                            account_id,<br>                            secret_name<br>                        )<br><br>                        print(f&quot;New key created for {username}&quot;)<br><br>                    # INACTIVATE KEY<br>                    if age &gt;= INACTIVE_DAYS and key[&quot;Status&quot;] == &quot;Active&quot;:<br><br>                        iam.update_access_key(<br>                            UserName=username,<br>                            AccessKeyId=access_key_id,<br>                            Status=&quot;Inactive&quot;<br>                        )<br><br>                        print(f&quot;Key Inactivated : {access_key_id}&quot;)<br><br>                    # DELETE KEY<br>                    if age &gt;= DELETE_DAYS and key[&quot;Status&quot;] == &quot;Inactive&quot;:<br><br>                        iam.delete_access_key(<br>                            UserName=username,<br>                            AccessKeyId=access_key_id<br>                        )<br><br>                        print(f&quot;Key Deleted : {access_key_id}&quot;)<br><br>        except Exception as e:<br>            print(f&quot;Error processing account {account_id} : {str(e)}&quot;)<br><br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: &quot;IAM Key Rotation Completed&quot;<br>    }<br><br><br># ============================================================<br># Get AWS Accounts<br># ============================================================<br><br>def get_all_accounts():<br><br>    paginator = organizations.get_paginator(&quot;list_accounts&quot;)<br><br>    accounts = []<br><br>    for page in paginator.paginate():<br><br>        for account in page[&quot;Accounts&quot;]:<br><br>            if account[&quot;Status&quot;] == &quot;ACTIVE&quot;:<br>                accounts.append(account)<br><br>    return accounts<br><br><br># ============================================================<br># Assume Cross Account Role<br># ============================================================<br><br>def assume_role(account_id):<br><br>    role_arn = f&quot;arn:aws:iam::{account_id}:role/{ROLE_NAME}&quot;<br><br>    response = sts.assume_role(<br>        RoleArn=role_arn,<br>        RoleSessionName=&quot;KeyRotationSession&quot;<br>    )<br><br>    return response[&quot;Credentials&quot;]<br><br><br># ============================================================<br># Store Secret<br># ============================================================<br><br>def store_secret(client, secret_name, secret_value):<br><br>    try:<br><br>        client.describe_secret(<br>            SecretId=secret_name<br>        )<br><br>        client.update_secret(<br>            SecretId=secret_name,<br>            SecretString=json.dumps(secret_value)<br>        )<br><br>        print(f&quot;Secret Updated : {secret_name}&quot;)<br><br>    except client.exceptions.ResourceNotFoundException:<br><br>        client.create_secret(<br>            Name=secret_name,<br>            SecretString=json.dumps(secret_value)<br>        )<br><br>        print(f&quot;Secret Created : {secret_name}&quot;)<br><br><br># ============================================================<br># Invoke Email Lambda<br># ============================================================<br><br>def invoke_email_lambda(username, account_id, secret_name):<br><br>    payload = {<br>        &quot;username&quot;: username,<br>        &quot;account_id&quot;: account_id,<br>        &quot;secret_name&quot;: secret_name<br>    }<br><br>    lambda_client.invoke(<br>        FunctionName=EMAIL_LAMBDA,<br>        InvocationType=&quot;Event&quot;,<br>        Payload=json.dumps(payload)<br>    )<br><br><br># ============================================================<br># User Rotation Filter<br># ============================================================<br><br>def should_rotate_user(user):<br><br>    tags = user.get(&quot;Tags&quot;, [])<br><br>    for tag in tags:<br><br>        if tag[&quot;Key&quot;] == &quot;RotateKeys&quot; and tag[&quot;Value&quot;] == &quot;true&quot;:<br>            return True<br><br>    return False</pre><h3>2. EmailLambda</h3><p>A secondary Lambda function responsible for customer notifications.</p><p>Once KeyRotationLambda successfully rotated keys, EmailLambda was triggered to:</p><p>➡️ Send email notifications to registered customers<br>➡️ Include Secret Manager URLs in the email body<br>➡️ Provide instructions for retrieving the newly rotated keys</p><p>Amazon SES was used as the email gateway service. But it&#39;s up to you to use any other email services.</p><pre># ============================================================<br># Lambda Function 2 : EmailLambda<br># ============================================================<br># Features:<br># - Send Email Notification<br># - Share Secret Manager URL<br># - Uses Amazon SES<br># ============================================================<br><br>import boto3<br>import os<br><br>ses = boto3.client(&quot;ses&quot;)<br><br>SENDER = os.environ.get(&quot;SENDER_EMAIL&quot;)<br><br><br>def lambda_handler(event, context):<br><br>    username = event[&quot;username&quot;]<br>    account_id = event[&quot;account_id&quot;]<br>    secret_name = event[&quot;secret_name&quot;]<br><br>    recipient = get_user_email(username)<br><br>    secret_url = (<br>        f&quot;https://console.aws.amazon.com/secretsmanager/&quot;<br>        f&quot;home?region=us-east-1#/secret?name={secret_name}&quot;<br>    )<br><br>    subject = &quot;AWS IAM Access Key Rotation Notification&quot;<br><br>    body = f&quot;&quot;&quot;<br>Hello {username},<br><br>Your AWS IAM Access Key has been rotated successfully.<br><br>Account ID : {account_id}<br><br>Secret Name : {secret_name}<br><br>Secret URL :<br>{secret_url}<br><br>Please retrieve the new access keys securely from AWS Secrets Manager.<br><br>Regards,<br>Cloud Security Team<br>&quot;&quot;&quot;<br><br>    response = ses.send_email(<br>        Source=SENDER,<br>        Destination={<br>            &quot;ToAddresses&quot;: [recipient]<br>        },<br>        Message={<br>            &quot;Subject&quot;: {<br>                &quot;Data&quot;: subject<br>            },<br>            &quot;Body&quot;: {<br>                &quot;Text&quot;: {<br>                    &quot;Data&quot;: body<br>                }<br>            }<br>        }<br>    )<br><br>    print(response)<br><br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: &quot;Email Sent&quot;<br>    }<br><br><br># ============================================================<br># Mock User Email Lookup<br># ============================================================<br><br>def get_user_email(username):<br><br>    return f&quot;{@company.com&quot;&gt;username}@company.com&quot;</pre><h3>3. AWS Secrets Manager</h3><p>Secrets Manager played a central role in securely storing credentials.</p><p>The solution automatically:</p><p>➡️ Created secrets if they did not exist<br>➡️ Stored both old and newly generated access keys<br>➡️ Updated secrets during rotation cycles<br>➡️ Cleaned up secrets when keys were deleted</p><p><strong><em>Each customer account maintained its own secret for isolation and security.</em></strong></p><p><strong>Customers received the Secret URL through email notifications and could retrieve the rotated credentials securely.</strong></p><h3>4. Cross-Account IAM Role</h3><p>To avoid storing permanent credentials, the solution used STS AssumeRole for secure cross-account access.</p><p>A dedicated IAM role was deployed into every child account with:</p><p>➡️ Trust relationship to the central Lambda execution role<br>➡️ Minimal IAM permissions required for key management</p><p>Permissions included:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br><br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;organizations:ListAccounts&quot;,<br>        &quot;organizations:ListAccountsForParent&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    },<br><br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;sts:AssumeRole&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    },<br><br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;lambda:InvokeFunction&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    },<br><br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;logs:CreateLogGroup&quot;,<br>        &quot;logs:CreateLogStream&quot;,<br>        &quot;logs:PutLogEvents&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    }<br>  ]<br>}</pre><p>This ensured a secure and scalable cross-account operational model.</p><h3>5. CloudFormation StackSets</h3><p>CloudFormation StackSets were used to deploy the custom IAM AssumeRole into all child accounts automatically.</p><p>This standardized:</p><p>➡️ IAM role creation<br>➡️ Trust policies<br>➡️ Permission boundaries<br>➡️ Cross-account access configuration</p><p><em>As new AWS accounts were added to the organization, they automatically became compliant through the deployment mechanism.</em></p><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Description: &gt;<br>  Cross Account IAM Role for Centralized IAM Key Rotation Lambda<br><br>Parameters:<br><br>  MasterAccountId:<br>    Type: String<br>    Description: Master / Central AWS Account ID<br><br>  LambdaRoleName:<br>    Type: String<br>    Default: KeyRotationLambdaRole<br>    Description: Lambda Execution Role Name in Master Account<br><br>  CrossAccountRoleName:<br>    Type: String<br>    Default: KeyRotationRole<br>    Description: Cross Account IAM Role Name<br><br><br>Resources:<br><br># ============================================================<br># Cross Account IAM Role<br># ============================================================<br><br>  KeyRotationCrossAccountRole:<br>    Type: AWS::IAM::Role<br>    Properties:<br>      RoleName: !Ref CrossAccountRoleName<br><br>      AssumeRolePolicyDocument:<br>        Version: &#39;2012-10-17&#39;<br>        Statement:<br><br>          - Effect: Allow<br>            Principal:<br>              AWS: !Sub arn:aws:iam::${MasterAccountId}:role/${LambdaRoleName}<br>            Action: sts:AssumeRole<br><br>      Path: /<br><br>      ManagedPolicyArns:<br>        - arn:aws:iam::aws:policy/SecretsManagerReadWrite<br><br>      Policies:<br><br>        - PolicyName: KeyRotationPolicy<br><br>          PolicyDocument:<br>            Version: &#39;2012-10-17&#39;<br><br>            Statement:<br><br># ============================================================<br># IAM Permissions<br># ============================================================<br><br>              - Sid: IAMKeyRotationPermissions<br><br>                Effect: Allow<br><br>                Action:<br>                  - iam:ListUsers<br>                  - iam:GetUser<br>                  - iam:ListAccessKeys<br>                  - iam:CreateAccessKey<br>                  - iam:UpdateAccessKey<br>                  - iam:DeleteAccessKey<br>                  - iam:ListUserTags<br><br>                Resource: &quot;*&quot;<br><br># ============================================================<br># Secrets Manager Permissions<br># ============================================================<br><br>              - Sid: SecretsManagerPermissions<br><br>                Effect: Allow<br><br>                Action:<br>                  - secretsmanager:CreateSecret<br>                  - secretsmanager:UpdateSecret<br>                  - secretsmanager:DescribeSecret<br>                  - secretsmanager:GetSecretValue<br>                  - secretsmanager:PutSecretValue<br>                  - secretsmanager:DeleteSecret<br><br>                Resource: &quot;*&quot;<br><br># ============================================================<br># CloudWatch Logs Permissions<br># ============================================================<br><br>              - Sid: CloudWatchLogsPermissions<br><br>                Effect: Allow<br><br>                Action:<br>                  - logs:CreateLogGroup<br>                  - logs:CreateLogStream<br>                  - logs:PutLogEvents<br><br>                Resource: &quot;*&quot;<br><br><br># ============================================================<br># Optional Secret Creation<br># ============================================================<br><br>  InitialSecret:<br>    Type: AWS::SecretsManager::Secret<br>    Properties:<br>      Name: Initial-IAM-Key-Secret<br>      Description: Placeholder Secret for IAM Key Rotation<br>      SecretString: |<br>        {<br>          &quot;AccessKeyId&quot;: &quot;PLACEHOLDER&quot;,<br>          &quot;SecretAccessKey&quot;: &quot;PLACEHOLDER&quot;<br>        }<br><br><br>Outputs:<br><br>  CrossAccountRoleArn:<br>    Description: ARN of Cross Account Role<br>    Value: !GetAtt KeyRotationCrossAccountRole.Arn<br><br>  CrossAccountRoleName:<br>    Description: Name of Cross Account Role<br>    Value: !Ref KeyRotationCrossAccountRole</pre><h3>6. Terraform</h3><p>Terraform was used as the Infrastructure-as-Code engine to deploy and manage:</p><p>➡️ Lambda functions<br>➡️ IAM policies<br>➡️ EventBridge schedules<br>➡️ CloudWatch log groups<br>➡️ SES configurations<br>➡️ StackSet orchestration<br>➡️ Secrets Manager configurations</p><p>This made the entire solution reproducible, scalable, and version-controlled.</p><h3>Detailed Workflow</h3><h3>Step 1 — Fetch Child Accounts</h3><p>The KeyRotationLambda uses the AWS Organizations client to retrieve all active child accounts under a specified Organizational Unit (OU).</p><h3>Step 2 — Assume Cross-Account Role</h3><p>Using AWS STS, the Lambda assumes the custom IAM role deployed in each child account.</p><h3>Step 3 — Evaluate Access Keys</h3><p>The Lambda inspects IAM users and evaluates access keys based on configurable lifecycle periods:</p><h4>Rotation Period (90 Days)</h4><p>Keys older than the rotation threshold are rotated.</p><h4>Inactive Period (100 Days)</h4><p>Old active keys are marked inactive after a defined period.</p><h4>Retention Period (110 Days)</h4><p>Inactive keys exceeding the retention threshold are deleted permanently.</p><h3>Step 4 — Store Keys in Secrets Manager</h3><p>Once new keys are generated:</p><p>‣ Secrets are created if missing<br>‣ Existing secrets are updated<br>‣ Old key metadata is retained temporarily<br>‣ Secrets cleanup occurs during deletion events</p><p>This ensured centralized and secure secret management.</p><h3>Step 5 — Trigger Email Notifications</h3><p>Upon successful rotation:</p><p>‣ EmailLambda is triggered<br>‣ SES sends email notifications<br>‣ Customers receive:<br>‣ Secret URL<br>‣ Retrieval instructions<br>‣ Rotation status details</p><p>This eliminated manual credential distribution.</p><h3>Compliance Enforcement</h3><p>One of the strongest features of the solution was automatic compliance onboarding.</p><p>New AWS accounts automatically became compliant through:</p><ul><li>StackSet-based IAM role deployment</li><li>Tag-based enforcement mechanisms</li></ul><p>This meant newly onboarded accounts immediately followed the organization’s IAM key rotation policies.</p><p>However, proper tagging of IAM users remained essential for the automation workflow.</p><h3>Challenges Faced During Implementation</h3><h3>Managing AWS Two-Key Limitation</h3><p>IAM users can only maintain two active access keys simultaneously.</p><p>The Lambda required careful logic to:</p><ul><li>Create new keys safely</li><li>Avoid accidental lockouts</li><li>Ensure applications had transition time</li></ul><h3>Cross-Account Permission Complexity</h3><p>Trust relationships between accounts required precise IAM configurations. Small mistakes in trust policies could break automation entirely.</p><h3>Safe Secret Rotation</h3><p>Ensuring applications could transition smoothly to new credentials required staged deactivation and cleanup.</p><h3>Scaling Across Multiple Accounts</h3><p>As account volume increased:</p><ul><li>API throttling</li><li>Lambda execution timing</li><li>Error isolation became an important optimization area.</li></ul><h3>Final Outcome</h3><p>The final solution delivered:</p><p>✅ Fully automated IAM key rotation<br>✅ Centralized governance from a single AWS account<br>✅ Secure cross-account operations using STS<br>✅ Automated secret management using Secrets Manager<br>✅ Email-based credential delivery using SES<br>✅ Infrastructure-as-Code deployment using Terraform and CloudFormation<br>✅ Automatic compliance onboarding for new AWS accounts<br>✅ Reduced manual effort and operational risk</p><h3>Final Thoughts</h3><p>This project started as a security compliance initiative but evolved into a scalable cloud governance framework.</p><p>The biggest lesson from this implementation was simple:</p><p>As cloud environments scale, security operations must become automated, centralized, and policy-driven.</p><p>Manual IAM key management simply does not scale in modern multi-account AWS architectures.</p><p>By combining AWS native services with Infrastructure-as-Code and serverless automation, it is possible to build secure, scalable, and fully automated governance solutions with minimal operational overhead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19f5215d6013" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>