<?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 Ranjanabha Bhattacharya on Medium]]></title>
        <description><![CDATA[Stories by Ranjanabha Bhattacharya on Medium]]></description>
        <link>https://medium.com/@ranjanabhabhattacharya?source=rss-87d60615e8d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XVi9Cxu8bIAxplKOldf69A.jpeg</url>
            <title>Stories by Ranjanabha Bhattacharya on Medium</title>
            <link>https://medium.com/@ranjanabhabhattacharya?source=rss-87d60615e8d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:34:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ranjanabhabhattacharya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a GCP to AWS Site-to-Site VPN with Terraform — Fully Automated]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/building-a-gcp-to-aws-site-to-site-vpn-with-terraform-fully-automated-1ef5148c975f?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ef5148c975f</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 13:52:04 GMT</pubDate>
            <atom:updated>2026-04-06T13:54:39.023Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to connecting Google Cloud and Amazon Web Services over an encrypted HA VPN tunnel, with zero manual steps using Terraform’s dependency graph</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ACs9QiwMgPraEKq8A4ULA.png" /></figure><h3>Introduction</h3><p>Multi-cloud is no longer a future aspiration — it’s a present-day reality for many engineering teams. Whether you’re migrating workloads, distributing services across providers, or simply avoiding vendor lock-in, the need to establish private, encrypted connectivity between GCP and AWS is increasingly common.</p><p>The challenge is that setting it up manually is painful. You need to copy IPs and pre-shared keys between two cloud consoles, navigate a strict dependency order, and get every BGP inside address exactly right — one wrong character and your tunnels silently fail.</p><p>This article walks through how to automate the entire setup with Terraform in a single terraform apply — no manual console steps, no hardcoded secrets, no copying values between tabs.</p><h3>Architecture Overview</h3><p>The setup creates a <strong>High Availability (HA) Site-to-Site VPN</strong> between GCP and AWS using four IPSec tunnels, BGP dynamic routing, and full redundancy across two VPN connections.</p><p>![Architecture Diagram showing GCP VPC on the left with public and private subnets, connected via 4 tunnels to AWS VPC on the right with public and private subnets. GCP side shows a Cloud Router and HA VPN Gateway. AWS side shows a Virtual Private Gateway connecting to two Customer Gateways.]</p><h3>Network Layout</h3><p>Cloud VPC CIDR Public Subnet Private Subnet GCP 172.0.0.0/16 172.0.1.0/24 172.0.2.0/24 AWS 10.0.0.0/16 10.0.10.0/24 10.0.20.0/24</p><h3>Why Four Tunnels?</h3><p>AWS Site-to-Site VPN creates <strong>two tunnels per VPN connection</strong> for redundancy. Since GCP’s HA VPN Gateway exposes <strong>two interfaces</strong> (two public IPs), the correct HA pattern is:</p><pre>GCP Interface 0 ──── Tunnel 1 ──── AWS VPN Connection 1, Tunnel 1<br>GCP Interface 0 ──── Tunnel 2 ──── AWS VPN Connection 1, Tunnel 2<br>GCP Interface 1 ──── Tunnel 3 ──── AWS VPN Connection 2, Tunnel 1<br>GCP Interface 1 ──── Tunnel 4 ──── AWS VPN Connection 2, Tunnel 2</pre><p>This gives you <strong>two separate VPN connections to two separate AWS VPN endpoints</strong>, meaning a failure of any single tunnel or endpoint maintains connectivity through the remaining paths.</p><h3>The Chicken-and-Egg Problem</h3><p>Before diving into the code, it’s worth understanding why automating this is non-trivial.</p><p>The manual setup requires this order:</p><ol><li><strong>Create GCP HA VPN Gateway</strong> → get 2 public IPs</li><li><strong>Go to AWS</strong> → create Customer Gateways using those IPs → create VPN Connections → download config file → get 4 tunnel IPs + 4 pre-shared keys</li><li><strong>Go back to GCP</strong> → create tunnels using the PSKs and BGP inside IPs from step 2</li></ol><p>Steps 1, 2, and 3 depend on each other in a chain that requires human intervention between each cloud. Terraform solves this because it builds a <strong>dependency graph</strong> across all resources — it knows it must create the GCP HA VPN gateway first, then use its output IPs to create the AWS Customer Gateways, then use the AWS VPN connection outputs to configure the GCP tunnels. All of this happens in one apply.</p><p>Below video shows how it is achieved manually</p><p><a href="https://www.youtube.com/watch?v=h6YuZ9k9nzo">https://www.youtube.com/watch?v=h6YuZ9k9nzo</a></p><h3>Module Structure</h3><p>The code is organised into five modules, each with a clear single responsibility:</p><pre>root/<br>├── main.tf           # Orchestration — wires all modules together<br>├── provider.tf       # AWS + GCP provider declarations<br>├── output.tf         # VM private IPs for connectivity testing<br>└── modules/<br>    ├── gcp-vpc/      # GCP VPC, subnets, firewall rules<br>    ├── gcp-network/  # HA VPN Gateway, Cloud Router, tunnels, BGP<br>    ├── gcp-ec2/      # GCP VM instance<br>    ├── vpc/          # AWS VPC, subnets, IGW, NAT, CGWs, VGW, VPN connections<br>    └── ec2/          # AWS EC2 instance + security group</pre><p>The split between gcp-vpc and gcp-network is deliberate and important — it breaks the circular dependency. gcp-vpc has no inputs from AWS (it just creates the network), while gcp-network takes AWS VPN outputs as inputs. This clean separation is what allows Terraform to resolve the dependency chain automatically.</p><h3>Step 1: Providers</h3><p>Both providers are declared at the <strong>root level only</strong>. This is a common mistake — placing provider blocks inside child modules causes Terraform to error or behave unpredictably.</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 6.0&quot;<br>    }<br>    google = {<br>      source  = &quot;hashicorp/google&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;eu-west-2&quot;<br>}<br>provider &quot;google&quot; {<br>  project = &quot;your-gcp-project-id&quot;<br>  region  = &quot;us-central1&quot;<br>  zone    = &quot;us-central1-a&quot;<br>}</pre><h3>Step 2: GCP VPC (gcp-vpc module)</h3><p>This module creates the GCP network infrastructure with no dependency on AWS. It runs first and its outputs feed into the AWS module.</p><pre>resource &quot;google_compute_network&quot; &quot;vpc_network&quot; {<br>  name                    = &quot;my-custom-vpc&quot;<br>  auto_create_subnetworks = false<br>}<br><br>resource &quot;google_compute_subnetwork&quot; &quot;my_public_subnet&quot; {<br>  name          = &quot;my-custom-public-subnet&quot;<br>  ip_cidr_range = &quot;172.0.1.0/24&quot;<br>  region        = &quot;us-central1&quot;<br>  network       = google_compute_network.vpc_network.id<br>}<br>resource &quot;google_compute_subnetwork&quot; &quot;my_private_subnet&quot; {<br>  name          = &quot;my-custom-private-subnet&quot;<br>  ip_cidr_range = &quot;172.0.2.0/24&quot;<br>  region        = &quot;us-central1&quot;<br>  network       = google_compute_network.vpc_network.id<br>}</pre><p>The firewall rule allows all traffic (TCP, UDP, ICMP) from any source. In production you would tighten source_ranges to your AWS VPC CIDR only.</p><pre>resource &quot;google_compute_firewall&quot; &quot;allow_ssh&quot; {<br>  name    = &quot;allow-ssh&quot;<br>  network = google_compute_network.vpc_network.name<br>  allow { protocol = &quot;tcp&quot; }<br>  allow { protocol = &quot;icmp&quot; }<br>  allow { protocol = &quot;udp&quot; }<br>  source_ranges = [&quot;0.0.0.0/0&quot;]<br>}</pre><p>The module outputs the VPC ID, which is consumed by gcp-network:</p><pre>output &quot;gcp_vpc_id&quot; {<br>  value = google_compute_network.vpc_network.id<br>}</pre><h3>Step 3: AWS VPC and VPN (vpc module)</h3><p>This module creates the full AWS network stack and — critically — the VPN connections. It takes the GCP HA VPN gateway IPs as input variables for the Customer Gateways.</p><h3>VPC and Networking</h3><pre>resource &quot;aws_vpc&quot; &quot;my_aws_vpc&quot; {<br>  cidr_block           = var.vpc_cidr<br>  enable_dns_hostnames = true<br>  enable_dns_support   = true<br>}<br><br>resource &quot;aws_subnet&quot; &quot;my_aws_public_subnet&quot; {<br>  vpc_id                  = aws_vpc.my_aws_vpc.id<br>  cidr_block              = var.vpc_public_subnet<br>  map_public_ip_on_launch = true<br>  availability_zone       = var.availabilty_zone<br>}<br>resource &quot;aws_subnet&quot; &quot;my_aws_private_subnet&quot; {<br>  vpc_id     = aws_vpc.my_aws_vpc.id<br>  cidr_block = var.vpc_private_subnet<br>}</pre><p>A NAT Gateway is included so instances in the private subnet can reach the internet for updates without being directly exposed:</p><pre>resource &quot;aws_nat_gateway&quot; &quot;nat_gateway&quot; {<br>  allocation_id = aws_eip.eip.id<br>  subnet_id     = aws_subnet.my_aws_public_subnet.id<br>  depends_on    = [aws_internet_gateway.igw]<br>}</pre><h3>Customer Gateways</h3><p>The two Customer Gateways use the GCP HA VPN gateway IPs passed in as variables. These IPs are only known after GCP resources are created — Terraform handles this ordering automatically.</p><pre>resource &quot;aws_customer_gateway&quot; &quot;gateway1&quot; {<br>  bgp_asn    = 64514             # Must match GCP Cloud Router ASN<br>  ip_address = var.gcp_vpn_gateway_ipaddress1<br>  type       = &quot;ipsec.1&quot;<br>}<br><br>resource &quot;aws_customer_gateway&quot; &quot;gateway2&quot; {<br>  bgp_asn    = 64514<br>  ip_address = var.gcp_vpn_gateway_ipaddress2<br>  type       = &quot;ipsec.1&quot;<br>}</pre><h3>Virtual Private Gateway</h3><p>The VGW is the AWS-side VPN endpoint. It gets attached to the VPC and its ASN (64512) must match what GCP expects as peer_asn on the BGP peers.</p><pre>resource &quot;aws_vpn_gateway&quot; &quot;vpn_gw&quot; {<br>  vpc_id = aws_vpc.my_aws_vpc.id<br>}</pre><h3>VPN Connections with Explicit IKEv2 Settings</h3><p>This is the most important part. By default, AWS VPN connections use IKEv1 and DH Group 2. GCP Cloud VPN only supports IKEv2 and does not support DH Group 2. Without explicitly setting these, the tunnels will silently fail — AWS sends no error response at all, leaving you with unexplained IKE retransmits in GCP logs.</p><pre>resource &quot;aws_vpn_connection&quot; &quot;vpn_connection1&quot; {<br>  vpn_gateway_id      = aws_vpn_gateway.vpn_gw.id<br>  customer_gateway_id = aws_customer_gateway.gateway1.id<br>  type                = &quot;ipsec.1&quot;<br>  static_routes_only  = false   # false = use BGP dynamic routing<br><br>tunnel1_ike_versions                 = [&quot;ikev2&quot;]<br>  tunnel1_phase1_encryption_algorithms = [&quot;AES256&quot;]<br>  tunnel1_phase1_integrity_algorithms  = [&quot;SHA2-256&quot;]<br>  tunnel1_phase1_dh_group_numbers      = [14]<br>  tunnel1_phase2_encryption_algorithms = [&quot;AES256&quot;]<br>  tunnel1_phase2_integrity_algorithms  = [&quot;SHA2-256&quot;]<br>  tunnel1_phase2_dh_group_numbers      = [14]<br>  tunnel1_startup_action               = &quot;start&quot;<br>  tunnel2_ike_versions                 = [&quot;ikev2&quot;]<br>  tunnel2_phase1_encryption_algorithms = [&quot;AES256&quot;]<br>  tunnel2_phase1_integrity_algorithms  = [&quot;SHA2-256&quot;]<br>  tunnel2_phase1_dh_group_numbers      = [14]<br>  tunnel2_phase2_encryption_algorithms = [&quot;AES256&quot;]<br>  tunnel2_phase2_integrity_algorithms  = [&quot;SHA2-256&quot;]<br>  tunnel2_phase2_dh_group_numbers      = [14]<br>  tunnel2_startup_action               = &quot;start&quot;<br>}</pre><p>The same block is repeated for vpn_connection2 targeting gateway2.</p><p>Setting tunnel1_startup_action = &quot;start&quot; tells AWS to actively initiate the IKE negotiation rather than waiting for GCP to knock first. This prevents both sides from sitting idle waiting for the other to go first.</p><h3>Route Propagation</h3><p>Route propagation is enabled on <strong>both</strong> route tables. Without propagating to the private route table, EC2 instances in the private subnet would have no route back to GCP even though the tunnel is up.</p><pre>resource &quot;aws_vpn_gateway_route_propagation&quot; &quot;public_subnet_propagation&quot; {<br>  vpn_gateway_id = aws_vpn_gateway.vpn_gw.id<br>  route_table_id = aws_route_table.public.id<br>}<br><br>resource &quot;aws_vpn_gateway_route_propagation&quot; &quot;private_subnet_propagation&quot; {<br>  vpn_gateway_id = aws_vpn_gateway.vpn_gw.id<br>  route_table_id = aws_route_table.private.id<br>}</pre><h3>VPN Connection Outputs — The Secret Sauce</h3><p>The aws_vpn_connection resource exposes all the information GCP needs as readable Terraform attributes. This is the key mechanism that makes full automation possible — no downloading config files, no copying secrets by hand.</p><pre># Pre-shared keys — auto-generated by AWS, read back as attributes<br>output &quot;vpn1_tunnel1_psk&quot; {<br>  value     = aws_vpn_connection.vpn_connection1.tunnel1_preshared_key<br>  sensitive = true<br>}<br><br># Tunnel outside IPs - where GCP sends IKE packets<br>output &quot;vpn_connection1_tunnel_ips&quot; {<br>  value = [<br>    aws_vpn_connection.vpn_connection1.tunnel1_address,<br>    aws_vpn_connection.vpn_connection1.tunnel2_address<br>  ]<br>}<br># BGP inside IPs - used for router interfaces and peer configuration<br>output &quot;vpn1_tunnel1_cgw1_inside_ip&quot; {<br>  value = aws_vpn_connection.vpn_connection1.tunnel1_cgw_inside_address<br>}<br>output &quot;vpn1_tunnel1_vgw1_inside_ip&quot; {<br>  value = aws_vpn_connection.vpn_connection1.tunnel1_vgw_inside_address<br>}</pre><p>tunnel1_cgw_inside_address returns the GCP-side BGP IP (e.g. 169.254.73.238) — just the bare IP, no prefix length. The /30 is appended in the GCP module since AWS always assigns /30 subnets for VPN inside CIDRs.</p><p>tunnel1_preshared_key is marked sensitive = true so it never appears in plan output or logs. It flows directly into the GCP tunnel shared_secret without ever touching a human.</p><h3>Step 4: GCP HA VPN and BGP (gcp-network module)</h3><p>This module takes all the AWS VPN outputs as inputs and creates the GCP side of the tunnels.</p><h3>HA VPN Gateway</h3><p>GCP automatically assigns two public IP addresses to the HA VPN Gateway — one per interface. These are what become the AWS Customer Gateway IPs.</p><pre>resource &quot;google_compute_ha_vpn_gateway&quot; &quot;ha_gateway&quot; {<br>  name    = &quot;my-ha-vpn-gw&quot;<br>  network = var.vpc_id<br>  region  = &quot;us-central1&quot;<br>}</pre><p>The output that feeds into the AWS Customer Gateways:</p><pre>output &quot;vpn_gateway_ips&quot; {<br>  value = [<br>    for interface in google_compute_ha_vpn_gateway.ha_gateway.vpn_interfaces :<br>    interface.ip_address<br>  ]<br>}</pre><h3>Cloud Router</h3><p>The Cloud Router manages BGP sessions over each tunnel. The ASN 64514 is the GCP-side ASN and must match what was configured in the AWS Customer Gateways.</p><pre>resource &quot;google_compute_router&quot; &quot;cloud_router&quot; {<br>  name    = &quot;gcp-cloud-router&quot;<br>  network = var.vpc_id<br>  region  = &quot;us-central1&quot;<br><br>bgp {<br>    asn = 64514<br>  }<br>}</pre><h3>External VPN Gateway</h3><p>This resource represents the AWS side — it holds the four AWS tunnel outside IPs so GCP knows where to send traffic.</p><pre>resource &quot;google_compute_external_vpn_gateway&quot; &quot;aws_gateway&quot; {<br>  name            = &quot;aws-side-gateway&quot;<br>  redundancy_type = &quot;FOUR_IPS_REDUNDANCY&quot;<br><br>  interface { id = 0; ip_address = var.tunnel1_ip1 }<br>  interface { id = 1; ip_address = var.tunnel1_ip2 }<br>  interface { id = 2; ip_address = var.tunnel2_ip1 }<br>  interface { id = 3; ip_address = var.tunnel2_ip2 }<br>}</pre><h3>VPN Tunnels</h3><p>Each tunnel maps a GCP gateway interface to an AWS tunnel endpoint. The shared_secret comes directly from the AWS VPN connection output — no manual copying.</p><pre>resource &quot;google_compute_vpn_tunnel&quot; &quot;tunnel_1&quot; {<br>  name                            = &quot;aws-tunnel-1&quot;<br>  region                          = &quot;us-central1&quot;<br>  vpn_gateway                     = google_compute_ha_vpn_gateway.ha_gateway.id<br>  peer_external_gateway           = google_compute_external_vpn_gateway.aws_gateway.id<br>  peer_external_gateway_interface = 0<br>  vpn_gateway_interface           = 0<br>  shared_secret                   = var.tunnel1_presared_key<br>  router                          = google_compute_router.cloud_router.id<br>}</pre><p>Tunnels 2, 3, and 4 follow the same pattern with incrementing interface numbers. Interface 0 and 1 on the GCP side correspond to the two HA VPN gateway interfaces, while interfaces 0–3 on the peer_external_gateway correspond to the four AWS tunnel endpoints.</p><h3>Router Interfaces and BGP Peers</h3><p>For each tunnel, GCP needs two things: a router interface (with the GCP-side BGP IP) and a BGP peer (pointing at the AWS-side BGP IP). The inside IPs come from the AWS VPN connection outputs — all 169.254.x.x/30 ranges that AWS assigns automatically.</p><pre>resource &quot;google_compute_router_interface&quot; &quot;if_1&quot; {<br>  name       = &quot;if-tunnel-1&quot;<br>  router     = google_compute_router.cloud_router.name<br>  region     = &quot;us-central1&quot;<br>  ip_range   = &quot;${var.tunnel1_cgw1_inside_address}/30&quot;  # e.g. 169.254.73.238/30<br>  vpn_tunnel = google_compute_vpn_tunnel.tunnel_1.name<br>}<br><br>resource &quot;google_compute_router_peer&quot; &quot;peer_1&quot; {<br>  name            = &quot;peer-tunnel-1&quot;<br>  router          = google_compute_router.cloud_router.name<br>  region          = &quot;us-central1&quot;<br>  peer_asn        = 64512                                # AWS VGW ASN<br>  peer_ip_address = var.tunnel1_vgw1_inside_address     # e.g. 169.254.73.237<br>  interface       = google_compute_router_interface.if_1.name<br>}</pre><p>This pattern repeats for all four tunnels. The result is four BGP sessions — one per tunnel — and GCP will use ECMP to distribute traffic across all active sessions.</p><h3>Step 5: Root Orchestration (main.tf)</h3><p>The root module is where the dependency chain is made explicit. Terraform reads the dependency graph and determines the correct apply order automatically.</p><pre># Step 1: GCP VPC — no AWS dependency, runs first<br>module &quot;gcp-vpc&quot; {<br>  source = &quot;./modules/gcp-vpc&quot;<br>}<br><br># Step 2: AWS VPC + VPN - reads GCP gateway IPs, creates VPN connections<br>module &quot;vpc&quot; {<br>  source                     = &quot;./modules/vpc&quot;<br>  vpc_cidr                   = &quot;10.0.0.0/16&quot;<br>  vpc_public_subnet          = &quot;10.0.10.0/24&quot;<br>  vpc_private_subnet         = &quot;10.0.20.0/24&quot;<br>  availabilty_zone           = &quot;eu-west-2a&quot;<br>  gcp_vpn_gateway_ipaddress1 = module.gcp-network.vpn_gateway_ips[0]<br>  gcp_vpn_gateway_ipaddress2 = module.gcp-network.vpn_gateway_ips[1]<br>}<br># Step 3: GCP tunnels + BGP - reads AWS VPN PSKs and inside IPs<br>module &quot;gcp-network&quot; {<br>  source                      = &quot;./modules/gcp-network&quot;<br>  vpc_id                      = module.gcp-vpc.gcp_vpc_id<br>  # AWS tunnel outside IPs<br>  tunnel1_ip1 = module.vpc.vpn_connection1_tunnel_ips[0]<br>  tunnel1_ip2 = module.vpc.vpn_connection1_tunnel_ips[1]<br>  tunnel2_ip1 = module.vpc.vpn_connection2_tunnel_ips[0]<br>  tunnel2_ip2 = module.vpc.vpn_connection2_tunnel_ips[1]<br>  # PSKs - read directly from aws_vpn_connection, never hardcoded<br>  tunnel1_presared_key = module.vpc.vpn1_tunnel1_psk<br>  tunnel2_presared_key = module.vpc.vpn1_tunnel2_psk<br>  tunnel3_presared_key = module.vpc.vpn1_tunnel3_psk<br>  tunnel4_presared_key = module.vpc.vpn1_tunnel4_psk<br>  # BGP inside IPs<br>  tunnel1_cgw1_inside_address = module.vpc.vpn1_tunnel1_cgw1_inside_ip<br>  tunnel1_vgw1_inside_address = module.vpc.vpn1_tunnel1_vgw1_inside_ip<br>  tunnel1_cgw2_inside_address = module.vpc.vpn1_tunnel1_cgw2_inside_ip<br>  tunnel1_vgw2_inside_address = module.vpc.vpn1_tunnel1_vgw2_inside_ip<br>  tunnel2_cgw1_inside_address = module.vpc.vpn1_tunnel2_cgw1_inside_ip<br>  tunnel2_vgw1_inside_address = module.vpc.vpn1_tunnel2_vgw1_inside_ip<br>  tunnel2_cgw2_inside_address = module.vpc.vpn1_tunnel2_cgw2_inside_ip<br>  tunnel2_vgw2_inside_address = module.vpc.vpn1_tunnel2_vgw2_inside_ip<br>}<br># Compute instances<br>module &quot;ec2&quot; {<br>  source        = &quot;./modules/ec2&quot;<br>  ec2_subnet_id = module.vpc.public_subnet_id<br>  ec2_vpc       = module.vpc.vpc_id<br>}<br>module &quot;gcp-ec2&quot; {<br>  source        = &quot;./modules/gcp-ec2&quot;<br>  ec2_subnet_id = module.gcp-vpc.public_subnet_id<br>}</pre><h3>Step 6: Outputs</h3><p>After apply, you can immediately get the private IPs needed for connectivity testing:</p><pre>output &quot;gcp_vm_private_ip&quot; {<br>  value = module.gcp-ec2.gcp_private_ip<br>}<br><br>output &quot;aws_ec2_private_ip&quot; {<br>  value = module.ec2.ec2_private_ip<br>}</pre><h3>Deploying</h3><pre># Authenticate to both clouds<br>gcloud auth application-default login<br>aws configure<br><br># Deploy everything in one command<br>terraform init<br>terraform apply</pre><p>Terraform will create approximately 35 resources across both clouds. The total apply time is typically 8–12 minutes, dominated by the AWS NAT Gateway and VPN Connection provisioning.</p><h3>Verifying Connectivity</h3><p>Once apply completes, grab the IPs and test:</p><pre># Get IPs<br>GCP_IP=$(terraform output -raw gcp_vm_private_ip)<br>AWS_IP=$(terraform output -raw aws_ec2_private_ip)<br><br># SSH into GCP VM<br>ssh user@$(terraform output -raw gcp_vm_public_ip)<br># From inside GCP VM, ping the AWS private IP<br>ping $AWS_IP</pre><p>A successful ping confirms that IPSec tunnels are up, BGP has established, and routes have been exchanged between both clouds.</p><h3>Lessons Learned</h3><p><strong>IKEv2 must be explicit.</strong> AWS defaults to IKEv1 + DH Group 2. GCP only supports IKEv2 and rejects DH Group 2. Without setting tunnel1_ike_versions = [&quot;ikev2&quot;] and tunnel1_phase1_dh_group_numbers = [14] explicitly, the tunnels fail silently — AWS drops the GCP IKE_SA_INIT packets without any error response.</p><p><strong>PSKs are Terraform attributes.</strong> aws_vpn_connection.vpn_connection1.tunnel1_preshared_key gives you the auto-generated PSK directly. Mark it sensitive = true and wire it to the GCP tunnel shared_secret. No downloading config files, no copy-paste errors.</p><p><strong>Providers belong at root only.</strong> Placing provider blocks inside child modules causes Terraform to error or produce unpredictable behaviour. All provider declarations live in the root provider.tf.</p><p><strong>Route propagation covers both route tables.</strong> AWS VGW route propagation only applies to the specific route table you attach it to. If you only propagate to the public route table, instances in the private subnet have no route back to GCP.</p><p><strong>The circular dependency is solved by module splitting.</strong> The GCP VPC/gateway resources have no dependency on AWS. The GCP tunnel/BGP resources depend on AWS VPN outputs. Keeping them in separate modules (gcp-vpc and gcp-network) breaks the cycle and lets Terraform resolve the graph.</p><h3>Conclusion</h3><p>What previously required three browser tabs, a config file download, manual copy-pasting of secrets, and careful ordering across two cloud consoles now runs in a single terraform apply. The key insight is that Terraform&#39;s dependency graph, combined with the AWS provider&#39;s ability to expose auto-generated PSKs and BGP IPs as resource attributes, makes full automation possible without any custom scripts or external tooling.</p><p>The full source code for this setup is available with all five modules ready to use. Update the GCP project ID and AWS region in the providers, run terraform apply, and you&#39;ll have a production-grade HA VPN between GCP and AWS in under 15 minutes.</p><p>Full code available at -&gt; <a href="https://github.com/ranjan-portfolio/site-to-site-connectivity-aws-gcp.git">https://github.com/ranjan-portfolio/site-to-site-connectivity-aws-gcp.git</a></p><p><em>Tags: Terraform, AWS, GCP, VPN, Multi-Cloud, Infrastructure as Code, Networking, Site-to-Site VPN, BGP</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ef5148c975f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Observability to a Serverless Weather App: CloudWatch, X-Ray, and Alarms with Terraform]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/adding-observability-to-a-serverless-weather-app-cloudwatch-x-ray-and-alarms-with-terraform-9b404de09004?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b404de09004</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 23:14:18 GMT</pubDate>
            <atom:updated>2026-03-27T23:14:18.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*G6Z5l4nnAcVW33ctof7NGw.png" /></figure><p><em>In the previous two articles I walked through building a fully serverless weather application on AWS — eight layers of infrastructure provisioned manually through the console — and then automating all of it with Terraform. This article covers the next logical step: you can’t operate what you can’t see.</em></p><h3>Why Observability Comes Next</h3><p>The Terraform setup from the last article gave us a reproducible, version-controlled stack: Route 53 → WAF → ACM → CloudFront → S3 for the frontend, and API Gateway → Lambda → Secrets Manager for the backend. Deploying it takes three commands. Tearing it down takes one.</p><p>But deploying reliably and <em>operating</em> reliably are two different problems. Once real traffic hits the API, questions start stacking up fast. Is the Lambda function cold-starting frequently? Are there 5XX errors spiking after a deployment? How long does the full request round-trip take — from API Gateway to Lambda to the OpenWeatherMap API and back? Is WAF silently blocking legitimate traffic?</p><p>Without structured logging, distributed tracing, and automated alerting, the answers to all of those questions are buried somewhere in raw CloudWatch metrics, if they exist at all. The upgrade in this article changes that. Three new capabilities land as first-class Terraform modules:</p><ul><li><strong>Structured access logging</strong> on API Gateway, with a custom JSON format capturing latency, trace IDs, and error messages per request</li><li><strong>AWS X-Ray tracing</strong> across the API Gateway → Lambda boundary, giving end-to-end visibility into request lifecycle</li><li><strong>CloudWatch Logs</strong> for both API Gateway and Lambda, with controlled retention periods</li><li><strong>A CloudWatch Metric Alarm</strong> wired to SNS, firing whenever the 5XX error rate exceeds the threshold</li></ul><p>The architecture diagram above shows how these components slot in alongside the existing stack. Everything in the dashed amber region is new.</p><h3>What Changed in the Project Structure</h3><p>The updated Terraform project adds two new modules and modifies three existing ones:</p><pre>weather-app/<br>├── main.tf                  # Updated: wires in cloudwatch + waf modules<br>└── modules/<br>    ├── cloudwatch/          # NEW: IAM role, metric alarm, SNS wiring<br>    │   ├── main.tf<br>    │   ├── data.tf<br>    │   ├── output.tf<br>    │   └── variable.tf<br>    ├── waf/                 # NEW: WAFv2 Web ACL in us-east-1<br>    │   ├── main.tf<br>    │   ├── output.tf<br>    │   └── var.tf<br>    ├── gateway/             # UPDATED: X-Ray on, access logs, method settings<br>    ├── lambda/              # UPDATED: X-Ray IAM policy, CloudWatch log group<br>    └── cloudfront/          # UPDATED: Logging bucket, WAF attachment, correlation function</pre><p>The root main.tf wires everything together. The CloudWatch module outputs an IAM role ARN that both the gateway and cloudfront modules consume:</p><pre>module &quot;cloudwatch&quot; {<br>  source = &quot;./modules/cloudwatch&quot;<br>}<br>module &quot;gateway&quot; {<br>  source              = &quot;./modules/gateway&quot;<br>  lambda_invoke_arn   = module.lambda.lambda_invoke_arn<br>  cloudwatch_role_arn = module.cloudwatch.cloudwatch_policy_arn<br>}<br>module &quot;waf&quot; {<br>  providers = {<br>    aws           = aws<br>    aws.us_east_1 = aws.us_east_1<br>  }<br>  source = &quot;./modules/waf&quot;<br>}<br>module &quot;cloudfront&quot; {<br>  source                             = &quot;./modules/cloudfront&quot;<br>  s3_domain_name                     = module.aws_s3_bucket.bucket_domain_name<br>  cloudfront_alternate_domain        = &quot;test.rancher-ranjanaws.com&quot;<br>  aws_acm_certificate_validation_arn = module.weatherapp_certificate.cert_validation_arn<br>  aws_cloudwatch_distribution_arn    = module.cloudwatch.cloudwatch_policy_arn<br>  aws_wafv2_web_acl_arn              = module.waf.web_acl_arn<br>}</pre><p>Two things are worth noting here. First, the WAF module uses the same cross-region provider aliasing pattern as ACM — CloudFront WAF ACLs must be provisioned in us-east-1, full stop. Second, the CloudWatch IAM role ARN flows into both gateway and cloudfront because both services need permission to push logs to CloudWatch.</p><h3>The CloudWatch Module</h3><p>This is the new foundation that everything else builds on. It does three things: creates an IAM role for API Gateway to assume when writing logs, attaches the AWS-managed policy for that purpose, and creates the metric alarm.</p><pre>resource &quot;aws_iam_role&quot; &quot;cloudwatch_role&quot; {<br>  name               = &quot;cloudwatch_access_role&quot;<br>  assume_role_policy = data.aws_iam_policy_document.cloudwatch_role_permission.json<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;cloudwatch_policy_attachment&quot; {<br>  role       = aws_iam_role.cloudwatch_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs&quot;<br>}</pre><p>The data.tf file defines the trust policy that allows the apigateway.amazonaws.com service principal to assume this role — the standard pattern for granting AWS services permission to write on your behalf.</p><h3>The Metric Alarm</h3><pre>resource &quot;aws_cloudwatch_metric_alarm&quot; &quot;k6_failure_alarm&quot; {<br>  alarm_name          = &quot;k6-failure-rate-30s&quot;<br>  comparison_operator = &quot;GreaterThanThreshold&quot;<br>  evaluation_periods  = &quot;1&quot;<br>  metric_name         = &quot;5XXError&quot;<br>  namespace           = &quot;AWS/ApiGateway&quot;<br>  period              = &quot;30&quot;<br>  statistic           = &quot;Average&quot;<br>  threshold           = &quot;2&quot;<br>  treat_missing_data  = &quot;breaching&quot;<br>  alarm_description   = &quot;Triggered when k6 error rate exceeds 5% in a 30s test&quot;<br>  alarm_actions       = [&quot;arn:aws:sns:eu-west-2:588578924488:Default_CloudWatch_Alarms_Topic&quot;]<br>}</pre><p>A few deliberate choices here worth unpacking.</p><p>The period = &quot;30&quot; is a high-resolution evaluation window. For a production API under sustained load, a 5-minute period makes more sense — it smooths over transient spikes. The 30-second window was tuned for load testing with k6, where a single test run might last less than a minute. You want the alarm to fire <em>during</em> the test, not ten minutes after it finishes.</p><p>The treat_missing_data = &quot;breaching&quot; setting is the one that catches people off guard. By default, CloudWatch treats missing data as &quot;not breaching&quot; — if there are no requests, there are no errors, so the alarm stays green. For this setup, missing data is treated as a signal that something is wrong: either the API is not receiving traffic it should be receiving, or the metric stream has broken. It is a stricter posture and appropriate for an API that should always be responding.</p><h3>It actually works — proof from the inbox</h3><p>Rather than leaving this as theory, here is what the SNS → email integration looks like when it fires in production.</p><p><strong>Alarm 1: </strong><strong>k6-failure-rate-30s — INSUFFICIENT_DATA → ALARM (18:28 UTC)</strong></p><p>This fired first, triggered not by actual errors but by the treat_missing_data = &quot;breaching&quot; behaviour described above. The notification read:</p><blockquote>“Threshold Crossed: no datapoints were received for 1 period and 1 missing datapoint was treated as [Breaching].”</blockquote><p>This is exactly the alarm working as designed. No traffic was flowing through API Gateway at that moment, so no 5XX metrics were being emitted. CloudWatch had no datapoints to evaluate — and rather than treating silence as healthy, the alarm escalated to ALARM state. The SNS topic delivered the notification to the subscribed email address within seconds of the state transition.</p><p>The alarm details confirmed the configuration end-to-end: namespace AWS/ApiGateway, metric 5XXError, threshold GreaterThanThreshold 2.0, period 30 seconds.</p><p><strong>Alarm 2: </strong><strong>Lambda Error — OK → ALARM (19:36 UTC)</strong></p><p>About an hour later, a second alarm fired — this one on a separate AWS/Lambda Errors metric scoped to the weather-api-test function. The reason was unambiguous: 39 Lambda errors were recorded in a single 5-minute period, crossing the threshold of 1.</p><blockquote>“Threshold Crossed: 1 out of the last 1 datapoints [39.0 (27/03/26 19:31:00)] was greater than the threshold (1.0).”</blockquote><p>This is a genuine error spike — 39 invocations failed within a single evaluation window. The alarm transitioned cleanly from OK → ALARM and the SNS notification arrived with the full context: alarm name, ARN, timestamp, AWS account, and a direct deep-link into the CloudWatch console for the Lambda Error alarm.</p><p><strong>What these two notifications confirm</strong></p><p>Both emails arrived from no-reply@sns.amazonaws.com, confirming the full chain — CloudWatch metric → alarm state transition → SNS topic → email subscription — is wired and working. The first alarm validates the treat_missing_data configuration. The second validates that real Lambda errors are being caught and surfaced within one evaluation period. Neither required any manual intervention to trigger; the infrastructure reported itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*pDHVbnu9-_n49HGRP44lug.png" /></figure><h3>Updating API Gateway: Access Logs and X-Ray</h3><p>The gateway module picks up two significant additions: structured access logging and X-Ray tracing enabled at the stage level.</p><pre>resource &quot;aws_api_gateway_stage&quot; &quot;name&quot; {<br>  deployment_id = aws_api_gateway_deployment.deployment.id<br>  rest_api_id   = aws_api_gateway_rest_api.weather_api.id<br>  stage_name    = &quot;prod&quot;<br>  xray_tracing_enabled = true<br>  access_log_settings {<br>    destination_arn = aws_cloudwatch_log_group.apigw_logs.arn<br>    format = jsonencode({<br>      requestId          = &quot;$context.requestId&quot;<br>      ip                 = &quot;$context.identity.sourceIp&quot;<br>      requestTime        = &quot;$context.requestTime&quot;<br>      httpMethod         = &quot;$context.httpMethod&quot;<br>      resourcePath       = &quot;$context.resourcePath&quot;<br>      status             = &quot;$context.status&quot;<br>      protocol           = &quot;$context.protocol&quot;<br>      responseLength     = &quot;$context.responseLength&quot;<br>      errorMessage       = &quot;$context.error.message&quot;<br>      integrationLatency = &quot;$context.integrationLatency&quot;<br>      responseLatency    = &quot;$context.responseLatency&quot;<br>      xrayTraceId        = &quot;$context.xrayTraceId&quot;<br>    })<br>  }<br>  depends_on = [aws_api_gateway_account.main]<br>}<br>resource &quot;aws_cloudwatch_log_group&quot; &quot;apigw_logs&quot; {<br>  name              = &quot;/aws/apigateway/weather-api&quot;<br>  retention_in_days = 14<br>}</pre><p>The access_log_settings block is what transforms API Gateway from a black box into something you can actually debug. Each request now produces a structured JSON log entry with the fields above. The xrayTraceId field is particularly useful — it lets you pivot directly from a slow or failed request in the access log to the full X-Ray trace, which shows exactly where in the call chain the time was spent.</p><p>The integrationLatency vs responseLatency distinction matters in practice. integrationLatency is the time API Gateway waited for Lambda to respond. responseLatency includes that plus the overhead API Gateway adds for processing. If responseLatency - integrationLatency is large, the bottleneck is in API Gateway itself, not Lambda.</p><p>The aws_api_gateway_account resource — which sets the CloudWatch role at the account level — needs to exist before the stage is created. The depends_on makes that sequencing explicit.</p><p>Method-level metrics are also enabled:</p><pre>resource &quot;aws_api_gateway_method_settings&quot; &quot;all&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.weather_api.id<br>  stage_name  = aws_api_gateway_stage.name.stage_name<br>  method_path = &quot;*/*&quot;<br>settings {<br>    metrics_enabled    = true<br>    logging_level      = &quot;INFO&quot;<br>    data_trace_enabled = true<br>  }<br>}</pre><p>A word of caution on data_trace_enabled = true: this logs the full request and response payload to CloudWatch. For a weather API this is harmless — the payloads are small and contain no PII. For anything handling personal data, sensitive fields, or payment information, set this to false. The debug value is real, but so is the compliance risk.</p><h3>Updating Lambda: X-Ray and CloudWatch Permissions</h3><p>Lambda picks up two new IAM policy statements and a managed log group.</p><pre>resource &quot;aws_iam_role_policy&quot; &quot;lambda_logging&quot; {<br>  name = &quot;lambda_logging_policy&quot;<br>  role = aws_iam_role.lambda_role.id<br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [<br>          &quot;logs:CreateLogGroup&quot;,<br>          &quot;logs:CreateLogStream&quot;,<br>          &quot;logs:PutLogEvents&quot;<br>        ]<br>        Resource = &quot;arn:aws:logs:*:*:*&quot;<br>      },<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [<br>          &quot;xray:PutTraceSegments&quot;,<br>          &quot;xray:PutTelemetryRecords&quot;<br>        ]<br>        Resource = &quot;*&quot;<br>      }<br>    ]<br>  })<br>}<br>resource &quot;aws_cloudwatch_log_group&quot; &quot;lambda_logs&quot; {<br>  name              = &quot;/aws/lambda/${aws_lambda_function.weather_lambda.function_name}&quot;<br>  retention_in_days = 3<br>}</pre><p>The log group name follows the AWS convention (/aws/lambda/&lt;function-name&gt;) so that Lambda can find and write to it automatically. Creating it explicitly via Terraform — rather than letting Lambda create it on first invocation — gives you control over the retention period. Three days is intentionally short here; the access log detail from API Gateway captures the structured diagnostics you actually need, and Lambda logs are mostly invocation noise.</p><p>The X-Ray permissions (PutTraceSegments, PutTelemetryRecords) allow the Lambda runtime to emit trace segments back to X-Ray. With xray_tracing_enabled = true set on the API Gateway stage and these permissions in place, the full trace from the API Gateway invocation through Lambda execution appears in the X-Ray console as a single connected service map.</p><p>Watch trace map generated by X-Ray</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*sOiEjc_bqeJuy_fA6JxXhg.png" /></figure><p>Application map generating summary of request flowing into app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*tVbOrIWULpGkbuH7wOzvPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*cINbtE8khvRyxjuypvTBYQ.png" /></figure><p>Digging into each trace id provides where the request has failed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8L_u-fJy_uUXIhUJn-lDg.png" /></figure><h3>WAF as a Terraform Module</h3><p>WAF was present in the original manual setup and mentioned in the previous Terraform article as a gap. It is now a first-class module.</p><pre>resource &quot;aws_wafv2_web_acl&quot; &quot;main&quot; {<br>  provider = aws.us_east_1<br>  name     = &quot;cloudfront-waf&quot;<br>  scope    = &quot;CLOUDFRONT&quot;<br>default_action { allow {} }<br>  rule {<br>    name     = &quot;AWS-AWSManagedRulesCommonRuleSet&quot;<br>    priority = 10<br>    override_action { none {} }<br>    statement {<br>      managed_rule_group_statement {<br>        name        = &quot;AWSManagedRulesCommonRuleSet&quot;<br>        vendor_name = &quot;AWS&quot;<br>      }<br>    }<br>    visibility_config {<br>      cloudwatch_metrics_enabled = true<br>      metric_name                = &quot;aws-common-rules&quot;<br>      sampled_requests_enabled   = true<br>    }<br>  }<br>  rule {<br>    name     = &quot;AWS-AWSManagedRulesAmazonIpReputationList&quot;<br>    priority = 15<br>    override_action { none {} }<br>    statement {<br>      managed_rule_group_statement {<br>        name        = &quot;AWSManagedRulesAmazonIpReputationList&quot;<br>        vendor_name = &quot;AWS&quot;<br>      }<br>    }<br>    visibility_config {<br>      cloudwatch_metrics_enabled = true<br>      metric_name                = &quot;aws-ip-reputation&quot;<br>      sampled_requests_enabled   = true<br>    }<br>  }<br>  rule {<br>    name     = &quot;IPRateLimit&quot;<br>    priority = 20<br>    action { block {} }<br>    statement {<br>      rate_based_statement {<br>        limit              = 1000<br>        aggregate_key_type = &quot;IP&quot;<br>      }<br>    }<br>    visibility_config {<br>      cloudwatch_metrics_enabled = true<br>      metric_name                = &quot;ip-rate-limit&quot;<br>      sampled_requests_enabled   = true<br>    }<br>  }<br>  visibility_config {<br>    cloudwatch_metrics_enabled = true<br>    metric_name                = &quot;cloudfront-waf-main&quot;<br>    sampled_requests_enabled   = true<br>  }<br>}</pre><p>Three rules, in priority order. The Common Rule Set (priority 10) blocks OWASP Top 10 patterns — SQL injection, XSS, known bad user agents. The IP Reputation List (priority 15) blocks IPs that AWS has flagged as malicious across its global network. The rate limiter (priority 20) blocks any single IP making more than 1,000 requests in a rolling 5-minute window.</p><p>The visibility_config on each rule is what connects WAF to CloudWatch. Every rule emits its own metric — aws-common-rules, aws-ip-reputation, ip-rate-limit — and the WAF ACL itself emits cloudfront-waf-main. These can be charted in CloudWatch dashboards or used as sources for additional alarms.</p><p>The scope = &quot;CLOUDFRONT&quot; requirement is why this module uses provider = aws.us_east_1. Like ACM certificates, WAF ACLs associated with CloudFront must live in us-east-1 — regardless of where the rest of your infrastructure is deployed.</p><h3>CloudFront: Logging Bucket and Correlation Header</h3><p>Two additions land in the CloudFront module: an access log bucket and a CloudFront Function that injects a correlation ID.</p><h3>Access Log Bucket</h3><pre>resource &quot;aws_s3_bucket&quot; &quot;cloudfront_logs&quot; {<br>  bucket        = &quot;weather-app-cloudfront-logs321&quot;<br>  force_destroy = true<br>}<br><br>resource &quot;aws_s3_bucket_lifecycle_configuration&quot; &quot;logs&quot; {<br>  bucket = aws_s3_bucket.cloudfront_logs.id<br>  rule {<br>    id     = &quot;expire-logs&quot;<br>    status = &quot;Enabled&quot;<br>    expiration { days = 14 }<br>  }<br>}</pre><p>The 14-day lifecycle rule keeps costs under control — CloudFront access logs can accumulate quickly under real traffic, and there is no value in keeping raw edge logs indefinitely once they have been ingested into CloudWatch or a SIEM.</p><p>The bucket ownership and ACL configuration (BucketOwnerPreferred, private ACL) is required for CloudFront to write logs to the bucket. CloudFront&#39;s logging service uses a legacy bucket ACL mechanism that requires the bucket to accept ACL-based grants.</p><h3>Correlation Header Injection</h3><pre>resource &quot;aws_cloudfront_function&quot; &quot;inject_trace_header&quot; {<br>  name    = &quot;inject-trace-header&quot;<br>  runtime = &quot;cloudfront-js-2.0&quot;<br>  publish = true<br>  code = &lt;&lt;-EOF<br>    async function handler(event) {<br>      var request = event.request;<br>      var headers = request.headers;<br>      var edgeRequestId = headers[&#39;x-edge-request-id&#39;]<br>        ? headers[&#39;x-edge-request-id&#39;].value<br>        : &#39;unknown&#39;;<br>      headers[&#39;x-correlation-id&#39;] = { value: edgeRequestId };<br>      return request;<br>    }<br>  EOF<br>}</pre><p>This CloudFront Function runs at the edge on every request. It reads the x-edge-request-id header that CloudFront generates internally — a unique ID for each request at the edge — and copies it into an x-correlation-id header before forwarding the request downstream.</p><p>The value of this becomes clear when you are debugging a specific user complaint. The x-edge-request-id appears in CloudFront access logs. The x-correlation-id — propagated from CloudFront into API Gateway and then into Lambda — appears in the API Gateway access log and in the Lambda log. You can trace a single user request across all three layers using one ID.</p><p>This is the same principle as distributed tracing, but implemented at the edge layer where X-Ray does not reach. X-Ray picks up at API Gateway; the correlation header bridges the gap from CloudFront to API Gateway.</p><h3>Connecting the Dots: What You Can See Now</h3><p>Before this upgrade, debugging a slow or failed request meant:</p><ol><li>Checking API Gateway metrics (coarse-grained, no per-request detail)</li><li>Hoping Lambda logs captured something useful (only if the function actually ran)</li><li>Guessing whether WAF was involved</li></ol><p>After this upgrade, a single request leaves a trail across four systems:</p><p><strong>CloudFront access log</strong> → x-edge-request-id tells you the request hit the edge and which PoP handled it.</p><p><strong>API Gateway access log</strong> → xrayTraceId connects this request to an X-Ray trace. integrationLatency tells you how long Lambda took. status tells you what the response code was. errorMessage tells you what went wrong if it did.</p><p><strong>X-Ray service map</strong> → shows the full graph: API Gateway → Lambda → Secrets Manager → external call to weatherapi.com. Each segment has its own duration, so you can see at a glance whether slowness is in Lambda initialization, Secrets Manager retrieval, or the external API.</p><p><strong>CloudWatch Logs Insights</strong> → query across API Gateway and Lambda logs in a single query using the trace ID as the join key.</p><p><strong>CloudWatch Alarm</strong> → if any of this goes wrong at scale, the 5XX alarm fires to SNS within 30 seconds.</p><h3>Key Takeaways</h3><p><strong>CloudWatch log groups should be created explicitly.</strong> If you let Lambda or API Gateway auto-create their log groups on first invocation, you have no control over retention. Explicitly provisioning them in Terraform with a short retention period keeps storage costs predictable.</p><p><strong>treat_missing_data = &quot;breaching&quot; is the right default for an API.</strong> An API with no traffic is not healthy — it either means the alarm itself is broken, or the traffic has stopped. Either way you want to know.</p><p><strong>Correlation IDs at the edge close the observability gap.</strong> X-Ray covers API Gateway to Lambda. CloudFront access logs cover the edge. The correlation header function is the glue that lets you connect a user-visible request to both sides of that boundary.</p><p><strong>WAF visibility config is not optional.</strong> Without cloudwatch_metrics_enabled = true on each rule, you have no way to tell whether WAF is silently blocking legitimate traffic. The metrics are cheap; the blind spot is expensive.</p><p><strong>30-second alarm periods are for testing.</strong> In production, 1-minute or 5-minute evaluation periods give you a more stable signal and fewer false positives from transient spikes.</p><h3>What Comes Next</h3><p>The observability foundation is in place — and as the alarm emails above show, SNS notification delivery is already working. Natural next steps:</p><ul><li><strong>CI/CD pipeline</strong> — terraform plan on pull requests, terraform apply on merge, with the alarm serving as a post-deploy health signal</li></ul><p>The full source, including the new cloudwatch and waf modules and all updates to gateway, lambda, and cloudfront, is available in the project repository: <a href="https://github.com/ranjanportfolio/Terraform.git">https://github.com/ranjanportfolio/Terraform.git</a></p><p><em>Tags: AWS · Terraform · CloudWatch · X-Ray · Serverless · Observability · Lambda · API Gateway · WAF · DevOps · Infrastructure as Code</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b404de09004" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Serverless AWS Weather App with Terraform]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/automating-serverless-aws-weather-app-with-terraform-9d128b1a03ad?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d128b1a03ad</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 17:17:11 GMT</pubDate>
            <atom:updated>2026-03-20T17:17:11.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*y5WjU2UDBe_UkVrA.png" /></figure><h3>From ClickOps to Infrastructure as Code</h3><p><em>Previously, I walked through the complete serverless architecture of a weather application built on AWS — Route 53, WAF, ACM, CloudFront, S3, API Gateway, Lambda, and Secrets Manager — all configured manually through the console. In this article, I will show you how I automated that entire infrastructure using Terraform, turning eight layers of manual configuration into reproducible, version-controlled code.</em></p><h3>Why Terraform?</h3><p>After building the architecture by hand, the next question is always the same: <em>what happens when you need to recreate it?</em> Whether that is a new environment, a disaster recovery scenario, or simply onboarding a team member, manual steps are slow, error-prone, and invisible to version control.</p><p>Terraform solves this cleanly. It is declarative — you describe the desired state, and it figures out how to get there. Every resource, every dependency, every permission is expressed as code that can be reviewed, tested, and reused.</p><h3>Project Structure</h3><p>The Terraform project follows a modular pattern, with each AWS service encapsulated in its own module:</p><pre>weather-app/<br>├── main.tf          # Root module — wires all modules together<br>├── provider.tf      # AWS provider config + remote state backend<br>├── output.tf        # Root-level outputs<br>└── modules/<br>    ├── acm/         # TLS certificate + DNS validation<br>    ├── cloudfront/  # CDN distribution + OAC<br>    ├── dns/         # Route 53 records<br>    ├── gateway/     # API Gateway REST API<br>    ├── lambda/      # Lambda function + IAM role + permissions<br>    └── s3/          # S3 bucket + policy + frontend upload</pre><p>This structure mirrors the layered architecture itself — each module is independently readable, and the root main.tf acts as the composition layer, wiring outputs from one module into inputs of another.</p><h3>Provider and Remote State</h3><p>The foundation is provider.tf, which configures two things: the AWS provider and a remote state backend.</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket       = &quot;terrafrom-weather-app-backend&quot;<br>    key          = &quot;terraform.tfstate&quot;<br>    region       = &quot;eu-west-2&quot;<br>    use_lockfile = true<br>    encrypt      = true<br>  }<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 6.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;eu-west-2&quot;<br>}<br>provider &quot;aws&quot; {<br>  alias  = &quot;us_east_1&quot;<br>  region = &quot;us-east-1&quot;<br>}</pre><p>There are two things worth noting here. First, the remote backend stores Terraform state in S3 with encryption and native S3 locking enabled via use_lockfile = true — this replaces the older DynamoDB locking pattern introduced in Terraform 1.10. Second, there are two provider configurations: the primary eu-west-2 for all resources, and an aliased us-east-1 provider. The alias is required because ACM certificates for CloudFront must be provisioned in us-east-1 regardless of where the rest of your infrastructure lives — a sharp edge that catches many people off-guard.</p><h3>Root Module: Wiring Everything Together</h3><p>The main.tf at the root level calls all six modules and passes outputs between them. This is where the dependency graph becomes explicit:</p><pre>module &quot;aws_s3_bucket&quot; {<br>  source                = &quot;./modules/s3&quot;<br>  bucket_name           = &quot;weather-app-bucket&quot;<br>  cloudfront_domain_arn = module.cloudfront.cloudfront_domain_arn<br>}<br><br>module &quot;cloudfront&quot; {<br>  source                             = &quot;./modules/cloudfront&quot;<br>  s3_domain_name                     = module.aws_s3_bucket.bucket_domain_name<br>  cloudfront_alternate_domain        = &quot;test.rancher-ranjanaws.com&quot;<br>  aws_acm_certificate_validation_arn = module.weatherapp_certificate.cert_validation_arn<br>}<br>module &quot;weatherapp_dns&quot; {<br>  source            = &quot;./modules/dns&quot;<br>  hosted_zone       = &quot;rancher-ranjanaws.com&quot;<br>  weatherapp_record = &quot;test.rancher-ranjanaws.com&quot;<br>  weatherapp_ttl    = 60<br>  weatherapp_value  = [module.cloudfront.cloudfront_domain_name]<br>}<br>module &quot;weatherapp_certificate&quot; {<br>  source = &quot;./modules/acm&quot;<br>  providers = {<br>    aws           = aws<br>    aws.us_east_1 = aws.us_east_1<br>  }<br>  domain_name = &quot;test.rancher-ranjanaws.com&quot;<br>}<br>module &quot;gateway&quot; {<br>  source            = &quot;./modules/gateway&quot;<br>  lambda_invoke_arn = module.lambda.lambda_invoke_arn<br>}<br>module &quot;lambda&quot; {<br>  source                = &quot;./modules/lambda&quot;<br>  gateway_execution_arn = module.gateway.gateway_execution_arn<br>}</pre><p>Notice that cloudfront depends on both s3 (for its origin domain) and acm (for its certificate), while dns depends on cloudfront (for the distribution domain name). The gateway and lambda modules have a circular-looking dependency — but it is resolved correctly: gateway needs lambda&#39;s invoke ARN to create the integration, while lambda needs gateway&#39;s execution ARN to scope the permission.</p><h3>Module Deep Dives</h3><h3>ACM — TLS Certificate with Automatic DNS Validation</h3><pre>resource &quot;aws_acm_certificate&quot; &quot;cert&quot; {<br>  provider          = aws.us_east_1<br>  domain_name       = var.domain_name<br>  validation_method = &quot;DNS&quot;<br>}<br><br>resource &quot;aws_route53_record&quot; &quot;acm_record&quot; {<br>  for_each = {<br>    for dvo in aws_acm_certificate.cert.domain_validation_options : dvo.domain_name =&gt; {<br>      name   = dvo.resource_record_name<br>      record = dvo.resource_record_value<br>      type   = dvo.resource_record_type<br>    }<br>  }<br>  allow_overwrite = true<br>  name            = each.value.name<br>  records         = [each.value.record]<br>  ttl             = 60<br>  type            = each.value.type<br>  zone_id         = data.aws_route53_zone.hosted_zone.zone_id<br>}<br>resource &quot;aws_acm_certificate_validation&quot; &quot;cert_validation&quot; {<br>  provider                = aws.us_east_1<br>  certificate_arn         = aws_acm_certificate.cert.arn<br>  validation_record_fqdns = [for record in aws_route53_record.acm_record : record.fqdn]<br>}</pre><p>This module handles the full certificate lifecycle: request, DNS CNAME validation record creation, and validation confirmation. The for_each on domain_validation_options is the standard pattern for handling DNS validation — ACM returns the required CNAME records dynamically, and this block creates them in Route 53 automatically. The cert_validation resource acts as a synchronisation point: Terraform will wait here until ACM confirms the certificate is fully issued before any dependent resource (CloudFront) proceeds. The provider = aws.us_east_1 on both ACM resources ensures they land in the correct region.</p><h3>S3 — Private Static Hosting with CloudFront-Only Access</h3><pre>resource &quot;aws_s3_bucket&quot; &quot;bucket&quot; {<br>  bucket        = &quot;weather-app-bucket-test&quot;<br>  force_destroy = true<br>  tags = {<br>    project_name = var.bucket_name<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;bucket&quot; {<br>  bucket                  = aws_s3_bucket.bucket.id<br>  block_public_acls       = true<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}<br>resource &quot;aws_s3_bucket_policy&quot; &quot;bucket&quot; {<br>  bucket = aws_s3_bucket.bucket.id<br>  policy = data.aws_iam_policy_document.origin_bucket_policy.json<br>}<br>resource &quot;aws_s3_object&quot; &quot;index&quot; {<br>  bucket       = aws_s3_bucket.bucket.id<br>  key          = &quot;index.html&quot;<br>  source       = &quot;${path.module}/index.html&quot;<br>  content_type = &quot;text/html&quot;<br>  etag         = filemd5(&quot;${path.module}/index.html&quot;)<br>}</pre><p>The bucket is created with all four public access block settings enabled — this is the bucket equivalent of a deny-all firewall rule. Access is granted exclusively to CloudFront through the IAM policy document:</p><pre>data &quot;aws_iam_policy_document&quot; &quot;origin_bucket_policy&quot; {<br>  statement {<br>    sid    = &quot;AllowCloudFrontServicePrincipalReadWrite&quot;<br>    effect = &quot;Allow&quot;<br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;cloudfront.amazonaws.com&quot;]<br>    }<br>    actions   = [&quot;s3:GetObject&quot;, &quot;s3:PutObject&quot;]<br>    resources = [&quot;${aws_s3_bucket.bucket.arn}/*&quot;]<br>    condition {<br>      test     = &quot;StringEquals&quot;<br>      variable = &quot;AWS:SourceArn&quot;<br>      values   = [var.cloudfront_domain_arn]<br>    }<br>  }<br>}</pre><p>The condition block tying the policy to a specific CloudFront distribution ARN is a critical security detail. Without it, <em>any</em> CloudFront distribution in the account could access the bucket. The etag = filemd5(...) on the S3 object ensures that whenever index.html changes on disk, Terraform detects the diff and re-uploads it automatically — no manual file sync required.</p><h3>CloudFront — CDN with OAC and HTTPS Enforcement</h3><pre>resource &quot;aws_cloudfront_origin_access_control&quot; &quot;oac&quot; {<br>  name                              = &quot;my-oac&quot;<br>  description                       = &quot;cloudfront access to private s3 hosting weather app&quot;<br>  origin_access_control_origin_type = &quot;s3&quot;<br>  signing_behavior                  = &quot;always&quot;<br>  signing_protocol                  = &quot;sigv4&quot;<br>}<br><br>resource &quot;aws_cloudfront_distribution&quot; &quot;cdn&quot; {<br>  enabled             = true<br>  default_root_object = &quot;index.html&quot;<br>  aliases             = [var.cloudfront_alternate_domain]<br>  origin {<br>    domain_name              = var.s3_domain_name<br>    origin_id                = &quot;s3-origin&quot;<br>    origin_access_control_id = aws_cloudfront_origin_access_control.oac.id<br>  }<br>  default_cache_behavior {<br>    target_origin_id       = &quot;s3-origin&quot;<br>    viewer_protocol_policy = &quot;redirect-to-https&quot;<br>    allowed_methods        = [&quot;GET&quot;, &quot;HEAD&quot;]<br>    cached_methods         = [&quot;GET&quot;, &quot;HEAD&quot;]<br>    forwarded_values {<br>      query_string = false<br>      cookies { forward = &quot;none&quot; }<br>    }<br>  }<br>  viewer_certificate {<br>    acm_certificate_arn = var.aws_acm_certificate_validation_arn<br>    ssl_support_method  = &quot;sni-only&quot;<br>  }<br>  restrictions {<br>    geo_restriction { restriction_type = &quot;none&quot; }<br>  }<br>}</pre><p>The module uses Origin Access Control (OAC) rather than the older Origin Access Identity (OAI) approach. OAC uses SigV4 request signing (signing_protocol = &quot;sigv4&quot;, signing_behavior = &quot;always&quot;) which is AWS&#39;s recommended pattern for new deployments. The viewer_protocol_policy = &quot;redirect-to-https&quot; ensures that any HTTP request is automatically redirected to HTTPS — enforcing encryption for all users regardless of the protocol they initiate with. The acm_certificate_arn points to the <em>validation</em> resource output rather than the certificate itself, ensuring CloudFront only receives the ARN once the certificate is fully issued.</p><h3>Lambda — Function, IAM Role, and Scoped Permission</h3><pre>resource &quot;aws_lambda_function&quot; &quot;weather_lambda&quot; {<br>  function_name = &quot;weather-api-test&quot;<br>  filename      = &quot;./modules/lambda/function.zip&quot;<br>  handler       = &quot;lambda_function.lambda_handler&quot;<br>  runtime       = &quot;python3.11&quot;<br>  role          = aws_iam_role.lambda_role.arn<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;lambda_role&quot; {<br>  name = &quot;lambda_api_role&quot;<br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Action    = &quot;sts:AssumeRole&quot;<br>      Effect    = &quot;Allow&quot;<br>      Principal = { Service = &quot;lambda.amazonaws.com&quot; }<br>    }]<br>  })<br>}<br>resource &quot;aws_iam_role_policy&quot; &quot;lambda_secrets&quot; {<br>  name = &quot;lambda_secrets_policy&quot;<br>  role = aws_iam_role.lambda_role.id<br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Action   = [&quot;secretsmanager:GetSecretValue&quot;]<br>      Resource = &quot;*&quot;<br>      Effect   = &quot;Allow&quot;<br>    }]<br>  })<br>}<br>resource &quot;aws_lambda_permission&quot; &quot;apigw_lambda&quot; {<br>  statement_id  = &quot;AllowExecutionFromAPIGateway&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.weather_lambda.function_name<br>  principal     = &quot;apigateway.amazonaws.com&quot;<br>  source_arn    = &quot;${var.gateway_execution_arn}/*/*&quot;<br>}</pre><p>Three resources work together here. The IAM role grants Lambda’s service principal permission to assume it. The inline policy grants the function access to Secrets Manager — this is how the function retrieves the OpenWeatherMap API key at runtime without hardcoding it anywhere. The aws_lambda_permission resource grants API Gateway permission to invoke the function, scoped to ${gateway_execution_arn}/*/* — the wildcards cover all stages and all methods, which is the standard pattern for REST APIs.</p><p>A note for production: the Resource = &quot;*&quot; on the Secrets Manager policy should be tightened to the specific secret ARN for least-privilege access.</p><h3>API Gateway — REST API with Lambda Proxy Integration</h3><pre>resource &quot;aws_api_gateway_rest_api&quot; &quot;weather_api&quot; {<br>  name = &quot;weather-api-test&quot;<br>}<br><br>resource &quot;aws_api_gateway_resource&quot; &quot;weather_resource&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.weather_api.id<br>  parent_id   = aws_api_gateway_rest_api.weather_api.root_resource_id<br>  path_part   = &quot;weather-api-test&quot;<br>}<br>resource &quot;aws_api_gateway_method&quot; &quot;get_weather&quot; {<br>  rest_api_id   = aws_api_gateway_rest_api.weather_api.id<br>  resource_id   = aws_api_gateway_resource.weather_resource.id<br>  http_method   = &quot;ANY&quot;<br>  authorization = &quot;NONE&quot;<br>}<br>resource &quot;aws_api_gateway_integration&quot; &quot;lambda_integration&quot; {<br>  rest_api_id             = aws_api_gateway_rest_api.weather_api.id<br>  resource_id             = aws_api_gateway_resource.weather_resource.id<br>  http_method             = aws_api_gateway_method.get_weather.http_method<br>  integration_http_method = &quot;POST&quot;<br>  type                    = &quot;AWS_PROXY&quot;<br>  uri                     = var.lambda_invoke_arn<br>}<br>resource &quot;aws_api_gateway_deployment&quot; &quot;deployment&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.weather_api.id<br>  depends_on  = [aws_api_gateway_integration.lambda_integration]<br>}<br>resource &quot;aws_api_gateway_stage&quot; &quot;name&quot; {<br>  deployment_id = aws_api_gateway_deployment.deployment.id<br>  rest_api_id   = aws_api_gateway_rest_api.weather_api.id<br>  stage_name    = &quot;prod&quot;<br>}</pre><p>The type = &quot;AWS_PROXY&quot; integration is the key configuration — it passes the entire HTTP request (headers, query parameters, body, path) directly to Lambda as a structured event, and returns Lambda&#39;s response directly to the caller without any transformation. The integration_http_method = &quot;POST&quot; is intentional: regardless of what HTTP verb the client sends, API Gateway always calls Lambda via POST internally. The depends_on on the deployment resource is important — without it, Terraform might deploy before the integration exists, resulting in a broken API.</p><h3>DNS — Route 53 CNAME Record</h3><pre>resource &quot;aws_route53_record&quot; &quot;weather_app_cloudfront_dnsname&quot; {<br>  zone_id = &quot;Z04014681W7MWNSSOUZXJ&quot;<br>  name    = var.weatherapp_record<br>  type    = &quot;CNAME&quot;<br>  ttl     = var.weatherapp_ttl<br>  records = var.weatherapp_value<br>}</pre><p>This creates the CNAME pointing the custom domain to the CloudFront distribution domain, completing the DNS layer. The TTL of 60 seconds (passed in from the root module) keeps propagation fast without generating excessive resolver load. In a hardened setup, the zone_id would be passed in as a variable rather than hardcoded — this is a natural next improvement.</p><h3>Dependency Graph at a Glance</h3><p>The module dependencies flow as follows:</p><pre>acm ──────────────────────────────┐<br>                                  ▼<br>s3  ──── (bucket_domain_name) ──► cloudfront ──── (domain_name) ──► dns<br>          ◄── (distribution_arn) ──┘</pre><pre>lambda ◄──── (execution_arn) ──── gateway<br>       ────── (invoke_arn) ──────►</pre><p>Terraform resolves this graph automatically and parallelises independent operations — acm, lambda, and s3 can all be provisioned concurrently since they have no mutual dependencies at creation time.</p><h3>Deploying the Stack</h3><p>With the project cloned, the full stack is deployed in three commands:</p><pre>terraform init      # Initialises providers and configures the S3 backend<br>terraform plan      # Shows all resources to be created<br>terraform apply     # Provisions the entire infrastructure</pre><p>After apply completes, the API Gateway invocation URL is printed via the root output:</p><pre>output &quot;gateway_invocation_url&quot; {<br>  value = module.gateway.gateway_invocation_url<br>}</pre><p>To tear it all down: terraform destroy. Because the S3 bucket is created with force_destroy = true, Terraform will empty and delete it rather than failing on a non-empty bucket.</p><p>Full code is available in my Github weather-app <a href="https://github.com/ranjan-portfolio/Terraform.git">https://github.com/ranjan-portfolio/Terraform.git</a></p><h3>Key Takeaways</h3><p>Moving from manual console configuration to Terraform surfaced a few architectural insights worth calling out:</p><p><strong>OAC over OAI.</strong> The Terraform config uses the modern Origin Access Control pattern (SigV4 signing) rather than the legacy OAI approach. If you are starting fresh, OAC is the right choice.</p><p><strong>Certificate validation as a synchronisation primitive.</strong> Using aws_acm_certificate_validation as an output — rather than the certificate ARN directly — makes Terraform wait for full issuance before CloudFront attempts to attach it. This is a subtle but important sequencing detail.</p><p><strong>Remote state with S3 native locking.</strong> The use_lockfile = true parameter (available from Terraform 1.10+) eliminates the need for a separate DynamoDB table for state locking — simplifying the backend setup considerably.</p><p><strong>Cross-region provider aliasing.</strong> The aws.us_east_1 provider alias is a clean way to handle the ACM/CloudFront region requirement without duplicating provider configuration across modules. The root module passes the alias explicitly via the providers map.</p><h3>What I Would Add Next</h3><p>The Terraform setup provides a solid foundation, but there are several improvements worth pursuing:</p><ul><li><strong>Tighten the Secrets Manager IAM policy</strong> to the specific secret ARN rather than *</li><li><strong>Harden the DNS module</strong> by passing the hosted zone ID as a variable instead of hardcoding it</li><li><strong>Add WAF association</strong> — the manual setup had WAF configured on CloudFront, but this module is not yet represented in Terraform</li><li><strong>Remote state for the ACM module</strong> — currently the hosted zone ID is referenced directly, tying the module to a specific account; a data source lookup would make it portable</li><li><strong>CI/CD pipeline</strong> — run terraform plan on pull requests and terraform apply on merge to main for a full GitOps workflow</li></ul><h3>Conclusion</h3><p>Infrastructure as Code is not just about automation — it is about making your architecture <em>legible</em>. Every security decision, every dependency, every configuration choice is now visible in code rather than buried in console screenshots. The same architecture that took an hour to click through manually can now be reproduced in minutes, in any environment, by anyone on the team.</p><p>If you are building serverless applications on AWS and still relying on manual configuration, the Terraform module structure shown here is a practical starting point. The modular approach makes it easy to extend — add a new module, wire it into main.tf, and the rest of the infrastructure is untouched.</p><p>The full source is available in the project repository. If you have questions about any of the Terraform patterns here, drop them in the comments below.</p><p><em>Tags: Terraform · AWS · Infrastructure as Code · Serverless · CloudFront · Lambda · API Gateway · DevOps</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d128b1a03ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Fully Serverless Weather App on AWS: A Deep Dive into Cloud-Native Architecture]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/building-a-fully-serverless-weather-app-on-aws-a-deep-dive-into-cloud-native-architecture-e1c862416be6?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1c862416be6</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 22:40:20 GMT</pubDate>
            <atom:updated>2026-03-16T22:40:20.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFjzUi7OqhHg5EWLk83qEw.png" /></figure><p>How I designed a secure, scalable, and cost-efficient weather application using <strong>AWS WAF, CloudFront, S3, API Gateway, Lambda, and Secrets Manager</strong> — without managing a single server.</p><p><strong>Introduction</strong></p><p>Serverless architecture has fundamentally changed the way we think about building and deploying web applications. No virtual machines to provision, no operating systems to patch, no capacity planning nightmares — just code, configuration, and cloud-managed infrastructure that scales automatically with your workload.</p><p>In this article, I’ll walk you through the complete architecture of a weather web application I built entirely on AWS using serverless and managed services. This project was an exercise in applying real-world cloud design principles: security at every layer, minimal operational overhead, and a clean separation of concerns between the frontend delivery layer and the backend data-fetching logic.</p><p>By the end, you’ll understand not just what I built, but why each architectural decision was made — the trade-offs, the alternatives considered, and the lessons learned.</p><p><strong>Architecture Overview</strong></p><p>The application is accessible at<strong> </strong><a href="http://weatherapp.rancher-ranjanaws.com/"><strong>weatherapp.rancher-ranjanaws.com</strong></a> and delivers real-time weather data fetched from the OpenWeatherMap API. The architecture is composed of eight core AWS services, each playing a distinct role:</p><p><strong>• DNS → Amazon Route 53 — Domain resolution<br>• Security → AWS WAF — Web application firewall<br>• TLS → AWS Certificate Manager — HTTPS/SSL termination<br>• CDN → Amazon CloudFront — Content delivery + OAI<br>• Frontend → Amazon S3 — Static asset hosting<br>• API → Amazon API Gateway — REST endpoint exposure<br>• Compute → AWS Lambda — Business logic execution<br>• Secrets → AWS Secrets Manager — Secure API key retrieval</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*gLZDQLpsqdJFhbfjQgcI0A.png" /></figure><p>The diagram above illustrates the complete user request flow — from the browser hitting the domain all the way through to the external weather API and back.</p><p><strong>Layer 1: DNS Resolution with Amazon Route 53</strong></p><p>The entry point for every user is the custom domain weatherapp.rancher-ranjanaws.com, hosted in Amazon Route 53 — AWS’s highly available, globally distributed DNS service.</p><p>Route 53 is configured with an Alias record pointing to the CloudFront distribution. Unlike a standard CNAME, an Alias record is a Route 53-native concept that maps the apex domain directly to an AWS resource without additional DNS hops or TTL overhead — important for performance-sensitive applications where every millisecond of DNS resolution counts.</p><p>Beyond AWS-native integration, Route 53 offers health checks, latency-based routing, and geolocation routing — all of which can be leveraged as the application scales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*jIDCWUeq2yT1xuss3xINyQ.png" /></figure><p><strong>Layer 2: Security at the Edge with AWS WAF</strong></p><p>Before any request reaches the application, it passes through AWS WAF (Web Application Firewall), associated directly with the CloudFront distribution.</p><p>WAF operates at the network edge — in CloudFront’s globally distributed Points of Presence — meaning malicious traffic is blocked before it even reaches the origin. This eliminates unnecessary compute cost and reduces the attack surface significantly.</p><p><strong>The WAF configuration includes:</strong></p><p><strong>AWS Managed Rule Groups</strong> — Pre-built rules protecting against SQL injection, cross-site scripting (XSS), and known malicious IPs maintained by AWS Threat Intelligence.</p><p><strong>Rate-based rules </strong>— Throttle excessive requests from a single IP to mitigate brute force and DDoS attempts.</p><p><strong>Geo-blocking capability </strong>— The architecture supports restricting access to specific geographic regions if required.</p><p>Placing WAF at the CloudFront layer rather than at the origin is a deliberate edge-security strategy. It minimises the blast radius of any attack and keeps the origin completely shielded from unfiltered internet traffic.</p><p><strong>Layer 3: HTTPS Enforcement with AWS Certificate Manager</strong></p><p>All traffic is encrypted in transit using a TLS certificate provisioned through AWS Certificate Manager (ACM). ACM handles the full certificate lifecycle — issuance, DNS validation via Route 53, and automatic renewal — with zero manual intervention.</p><p>One constraint worth noting early in any AWS architecture: ACM certificates for CloudFront must be provisioned in the us-east-1 (N. Virginia) region, regardless of where your other resources are deployed. This is a CloudFront-specific requirement that catches many engineers off guard.</p><p>ACM certificates are free for use with AWS services and automatically renew before expiry. For a production workload, the operational simplicity is compelling.</p><p><strong>Layer 4: Content Delivery with Amazon CloudFront and OAI</strong></p><p>Amazon CloudFront sits at the heart of the frontend delivery architecture. It serves as the CDN, SSL termination point, WAF attachment target, and — critically — the access control boundary for the S3 bucket, connected via Origin Access Identity (OAI).</p><p><strong>What is OAI and why does it matter?</strong></p><p>Without OAI, you would either need to make your S3 bucket publicly accessible (a significant security anti-pattern) or manage complex bucket policies manually. OAI solves this elegantly:</p><p>1. A unique OAI identity is created and associated with the CloudFront distribution.<br>2. The S3 bucket policy is updated to allow only this OAI identity to read objects.<br>3. The bucket itself remains completely private — direct S3 URL access returns a 403 Forbidden.</p><p>Users can only access the frontend through CloudFront. This is the correct security posture for any production static site deployment.</p><p>Additional CloudFront benefits include edge caching at 400+ PoPs globally, automatic Gzip/Brotli compression, and selective cache invalidation on deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*vIcRcXpniU95kZfYrzGsew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*pZ7pODMWgQzMamwqCVjnew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*K4aVeSZ0AJ1_0LiRO4MuOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*CF7V3olp1D7QbS1enDbdpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*WpSAI2VrHiFdR6uEms43Gg.png" /></figure><p><strong>Layer 5: Static Frontend Hosting on Amazon S3</strong></p><p>The application’s frontend (index.jsp) is stored in a private Amazon S3 bucket, served exclusively through CloudFront. The bucket is configured with versioning enabled for rollback capability and server-side encryption at rest (SSE-S3).</p><p>Static website hosting is intentionally disabled on the bucket itself. Because CloudFront handles all routing, enabling it would be redundant — and would weaken the private-access-only security posture we’ve established with OAI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*fDE6s9-7zX-l8Ra9c92IpA.png" /></figure><pre>Bucket Policy<br><br>{<br>    &quot;Version&quot;: &quot;2008-10-17&quot;,<br>    &quot;Id&quot;: &quot;PolicyForCloudFrontPrivateContent&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;AllowCloudFrontServicePrincipal&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;Service&quot;: &quot;cloudfront.amazonaws.com&quot;<br>            },<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::weather-app-ranjan/*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;AWS:SourceArn&quot;: &quot;arn:aws:cloudfront::588578924488:distribution/E1QKY07SQM9OXS&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p><strong>Layer 6: API Exposure with Amazon API Gateway</strong></p><p>When the frontend loads and calls /getWeatherData, that request hits Amazon API Gateway. The API is configured as a REST API with Lambda proxy integration — meaning the full HTTP request context (method, headers, query parameters) is passed directly to Lambda as an event object.</p><p>This keeps the integration layer thin and puts full routing and response logic inside the Lambda function itself, where it can be version-controlled, tested, and deployed independently.</p><p>CORS headers are configured on the API to permit calls from the CloudFront domain, and default throttling limits protect the backend Lambda from unexpected traffic spikes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Ook79E5AASaWtQa7shDlwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*2KCxCJU8_Wryufl7ttRJfA.png" /></figure><p><strong>Layer 7: Business Logic in AWS Lambda</strong></p><p>AWS Lambda is the runtime core of the application. The function is structured across three Python modules, each with a single responsibility — mirroring the clean service-level separation at the infrastructure layer.</p><p><strong>Module 1: lambda_handler — The Entry Point</strong></p><p>The handler is invoked by API Gateway on every request. It demonstrates a clean pattern for handling both CORS preflight requests (OPTIONS) and live GET requests in a single function:</p><pre>from client.weather_api import get_weather_forecast<br>from typing import Dict, Any<br><br>def lambda_handler(event: Dict[str, Any], context: Any) -&gt; Dict[str, Any]:<br> query_params = event.get(&quot;queryStringParameters&quot;) or {}<br> city = query_params.get(&quot;city&quot;, &quot;London&quot;)<br>try:<br> if event[&quot;httpMethod&quot;] == &quot;OPTIONS&quot;:<br> return {<br> &quot;statusCode&quot;: 200,<br> &quot;headers&quot;: {<br> &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;,<br> &quot;Access-Control-Allow-Headers&quot;: &quot;x-api-key,Content-Type&quot;,<br> &quot;Access-Control-Allow-Methods&quot;: &quot;GET,OPTIONS&quot;<br> },<br> &quot;body&quot;: &quot;&quot;<br> }<br>data = get_weather_forecast(city)<br> return {<br> &quot;statusCode&quot;: 200,<br> &quot;headers&quot;: {<br> &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;,<br> &quot;Access-Control-Allow-Headers&quot;: &quot;x-api-key,Content-Type&quot;,<br> &quot;Access-Control-Allow-Methods&quot;: &quot;GET,OPTIONS&quot;<br> },<br> &quot;body&quot;: data<br> }<br>except Exception as e:<br> if args := getattr(e, &quot;args&quot;, None):<br> if args and len(args) &gt; 0:<br> data = args[0]<br> if isinstance(data, dict) and &#39;cod&#39; in data and &#39;message&#39; in data:<br> return {<br> &quot;statusCode&quot;: int(data[&#39;cod&#39;]),<br> &quot;body&quot;: &#39;error:&#39; + data[&#39;cod&#39;] + &#39;:&#39; + data[&#39;message&#39;]<br> }<br> return {<br> &quot;statusCode&quot;: 500,<br> &quot;body&quot;: &#39;error:500:Internal Server Error&#39;<br> }import requests<br>import json<br>from  secrets.secrets import get_secret<br>from to.forecast import Forecast<br>from typing import List, Dict, Any<br>import logging<br><br><br>forecast_list=[]<br><br>def get_weather_forecast(city:str)-&gt; str:<br> logging.info(&quot;Inside weather forecast&quot;)<br> data=call_weather_api(city)<br><br> if data[&quot;cod&quot;] == &quot;200&quot;:<br>  forecast_list.clear()<br>  for forecast_data in data[&quot;list&quot;]:<br>        date=forecast_data[&quot;dt_txt&quot;]<br>        actual_temp=forecast_data[&quot;main&quot;][&quot;temp&quot;]<br>        feels_like=forecast_data[&quot;main&quot;][&quot;feels_like&quot;]<br>        weather=forecast_data[&quot;weather&quot;][0][&quot;main&quot;]<br>        forecast_list.append(Forecast(date,actual_temp,feels_like,weather))<br><br>  json_data = json.dumps(<br>                   [f.to_dict() for f in forecast_list],<br>                   indent=2<br>             )<br>  return json_data<br> <br> else:<br>      raise requests.exceptions.HTTPError(data)<br><br>def call_weather_api(city:str)-&gt;Any:<br> logging.info(&quot;Inside call_weather_api&quot;)<br> key=get_secret()<br> url = &quot;https://api.openweathermap.org/data/2.5/forecast&quot;<br> params={<br>    &quot;q&quot;:city,<br>    &quot;appid&quot;:key,<br>    &quot;units&quot;:&quot;metric&quot;<br> }<br> response=requests.get(url=url,params=params)<br> data=response.json()<br> return dat</pre><p>Three design decisions stand out here:</p><p><strong>city defaults to “London” </strong>— The function degrades gracefully when no query parameter is provided, making it robust against malformed frontend calls.</p><p><strong>OPTIONS preflight handling </strong>— Browsers require a CORS preflight check before any cross-origin API call. Handling OPTIONS directly in Lambda (rather than relying solely on API Gateway CORS config) ensures the response is always consistent and correct.</p><p><strong>Structured error propagation </strong>— The exception handler inspects the error’s args for an HTTP error dict containing cod and message keys (from the OpenWeatherMap API), enabling the function to return the upstream error status code directly rather than always returning 500.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*mx0a-R9aZiVEZzImRGa8rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*tm2vezusFEFjq8XALmFJOw.png" /></figure><p><strong>Module 2: weather_api — The Data Fetching Layer</strong></p><p>This module is responsible for calling the OpenWeatherMap API and transforming the raw JSON response into a clean, serialisable list of forecast objects:</p><pre>import requests<br>import json<br>from secrets.secrets import get_secret<br>from to.forecast import Forecast<br>import logging<br><br>forecast_list = []<br><br>def get_weather_forecast(city: str) -&gt; str:<br> data = call_weather_api(city)<br>if data[&quot;cod&quot;] == &quot;200&quot;:<br> forecast_list.clear()<br> for forecast_data in data[&quot;list&quot;]:<br> date = forecast_data[&quot;dt_txt&quot;]<br> actual_temp = forecast_data[&quot;main&quot;][&quot;temp&quot;]<br> feels_like = forecast_data[&quot;main&quot;][&quot;feels_like&quot;]<br> weather = forecast_data[&quot;weather&quot;][0][&quot;main&quot;]<br> forecast_list.append(Forecast(date, actual_temp, feels_like, weather))<br>return json.dumps([f.to_dict() for f in forecast_list], indent=2)<br> else:<br> raise requests.exceptions.HTTPError(data)<br><br><br>def call_weather_api(city: str):<br> key = get_secret()<br> url = &quot;https://api.openweathermap.org/data/2.5/forecast&quot;<br> params = {&quot;q&quot;: city, &quot;appid&quot;: key, &quot;units&quot;: &quot;metric&quot;}<br> response = requests.get(url=url, params=params)<br> return response.json()</pre><p>Four design decisions are worth highlighting:</p><p><strong>call_weather_api and get_weather_forecast </strong>are deliberately separated. The first handles raw HTTP interaction; the second handles data transformation. This makes each function independently unit-testable and easy to mock.</p><p><strong>forecast_list.clear() </strong>before populating is a Lambda-specific consideration that many developers miss. Lambda execution environments are reused across invocations (warm starts), meaning module-level state persists between calls. Without clearing the list, stale data from a previous invocation would contaminate the current response.</p><p><strong>units=metric</strong> means temperature is returned in Celsius directly from the API, avoiding client-side unit conversion.</p><p>The Forecast data class abstracts the raw API fields (dt_txt, main.temp, main.feels_like, weather[0].main) into a clean object with a to_dict() method, decoupling the frontend from the upstream API’s response structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*KG91hZvgUcBzCK93tGiUMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*VaOpX4TQnV5ijv2GNxyKzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*2z4jvsKF0sIBFY5hnPwATA.png" /></figure><p><strong>Layer 8: Secrets Management with AWS Secrets Manager</strong></p><p>The OpenWeatherMap API key is retrieved at runtime via AWS Secrets Manager, called from within call_weather_api. The key is never hardcoded, never stored in a plaintext environment variable, and never committed to source control.</p><pre>import boto3<br>import json<br><br>def get_secret() -&gt; str:<br> client = boto3.client(&#39;secretsmanager&#39;)<br> response = client.get_secret_value(SecretId=&#39;weatherapp/apikey&#39;)<br> return json.loads(response[&#39;SecretString&#39;])[&#39;api_key&#39;]</pre><p>Every call to get_secret() retrieves a fresh value from Secrets Manager. This means if the API key is ever rotated, Lambda picks up the new value on the next invocation — with zero redeployment required.</p><p>Security properties of this approach:</p><p><strong>Encryption at rest — </strong>The secret is encrypted via AWS KMS by default.<br>IAM least-privilege — Only the Lambda execution role has secretsmanager:GetSecretValue permission for this specific secret ARN.<br>Full audit trail — Every retrieval is logged in AWS CloudTrail.</p><p><strong>End-to-End Request Flow</strong></p><p>Here is the complete journey of a single user request, from browser to weather data and back:</p><p>1. User navigates to weatherapp.rancher-ranjanaws.com<br>2. Route 53 resolves the domain to the CloudFront distribution<br>3. AWS WAF inspects the request — blocks SQLi, XSS, rate abuse<br>4. CloudFront terminates TLS (ACM cert), checks edge cache<br>5. Static request → S3 bucket via OAI → serves index.jsp<br>6. Page load triggers GET /getWeatherData?city=London to API Gateway<br>7. API Gateway invokes Lambda with full HTTP event<br>8. lambda_handler routes to get_weather_forecast(city)<br>9. call_weather_api fetches API key from Secrets Manager<br>10. Lambda calls OpenWeatherMap /forecast endpoint<br>11. Response is transformed into Forecast objects → JSON<br>12. JSON travels back through API Gateway → CloudFront → browser<br>13. Frontend renders the weather data</p><p><strong>Key Architectural Principles Applied</strong></p><p><strong>Zero Trust Security Model — </strong>Every component assumes all others could be compromised. S3 is private (OAI), the API key is never exposed (Secrets Manager), WAF blocks traffic before it reaches any origin, and IAM roles are least-privilege throughout.</p><p><strong>Defence in Depth </strong>— Security at multiple independent layers: WAF at the edge, HTTPS in transit (ACM), encryption at rest (S3 SSE + Secrets Manager KMS), and IAM at the compute and secrets layer.</p><p><strong>Operational Simplicity </strong>— No EC2 instances, no containers, no operating systems, no patching. Every service is fully managed by AWS. The operational burden is close to zero.</p><p><strong>Cost Efficiency </strong>— The entire stack runs pay-per-use. When no users are active, the cost is effectively zero. Lambda, API Gateway, and CloudFront are billed per request, not per hour.</p><p><strong>Separation of Concerns </strong>— The handler, API client, data model, and secrets layer are each a distinct module. This mirrors the clean service-level separation at the AWS infrastructure level, making every component independently replaceable and testable.</p><p><strong>What I Would Add Next</strong></p><p><strong>DynamoDB caching layer </strong>— Cache forecast responses by city and timestamp to reduce external API calls and improve response latency.</p><p><strong>CloudWatch dashboards and alarms </strong>— Operational visibility into Lambda error rates, API Gateway 4xx/5xx counts, and p95 latency metrics.</p><p><strong>Lambda@Edge </strong>— Move lightweight request processing to the CloudFront edge for even lower latency.</p><p><strong>Automated secret rotation </strong>— Configure Secrets Manager to rotate the OpenWeatherMap API key on a defined schedule, with zero Lambda redeployment required.</p><p><strong>AWS X-Ray tracing </strong>— Distributed tracing across API Gateway and Lambda to diagnose latency bottlenecks in production.</p><p><strong>Conclusion</strong></p><p>This weather application demonstrates that you can build a secure, globally distributed, fully managed web application on AWS without operating a single server. By composing purpose-built managed services — Route 53, WAF, ACM, CloudFront, S3, API Gateway, Lambda, and Secrets Manager — the result is an architecture that is simultaneously more secure, more scalable, and cheaper to operate than a traditional server-based equivalent.</p><p>The Lambda code reinforces this ethos at the application level: clean module separation, stateless-aware design (warm-start list clearing), structured error propagation, and runtime secret retrieval that supports zero-downtime key rotation.</p><p>The key takeaway is not the specific services chosen, but the principles that guided those choices: security at every layer, least-privilege access, managed services over self-managed infrastructure, and a clean separation of concerns. These principles apply regardless of the cloud provider or the application domain.</p><p>If you’re building something similar or have questions about any of the architectural decisions here, I’d love to connect — drop a comment below.</p><p><strong>#AWS #Serverless #Cloud Architecture #Lambda #CloudFront #Python #Infrastructure #Web Development</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1c862416be6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jenkins Installation and CI/CD Pipeline with Docker, Trivy, and Kubernetes]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/jenkins-installation-and-ci-cd-pipeline-with-docker-trivy-and-kubernetes-7a2eeb8d1e4b?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a2eeb8d1e4b</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 13:46:58 GMT</pubDate>
            <atom:updated>2026-03-14T13:46:58.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kGePYub_IppJ2jQSk_7pDw.png" /></figure><p>Continuous Integration and Continuous Deployment (CI/CD) are essential practices in modern DevOps workflows. Tools like Jenkins help automate building, testing, and deploying applications. In this article, we will walk through:</p><ul><li>Installing Jenkins</li><li>Configuring required tools</li><li>Creating a CI/CD pipeline</li><li>Building and scanning Docker images</li><li>Deploying applications to Kubernetes</li></ul><p>The pipeline uses tools such as:</p><ul><li>Docker</li><li>Trivy</li><li>Kubernetes</li><li>Helm</li><li>Kind</li><li>Git</li></ul><h3>1. Jenkins Installation</h3><h3>Install Java (Required)</h3><p>Jenkins requires Java.</p><pre>sudo apt update<br>sudo apt install openjdk-17-jdk -y</pre><p>Verify installation:</p><pre>java -version</pre><h3>Install Jenkins</h3><p>Add the Jenkins repository and install:</p><pre>curl -fsSL https://pkg.jenkins.io/debian/jenkins.io-2023.key | sudo tee \<br>  /usr/share/keyrings/jenkins-keyring.asc &gt; /dev/null</pre><pre>echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \<br>  https://pkg.jenkins.io/debian binary/ | sudo tee \<br>  /etc/apt/sources.list.d/jenkins.list &gt; /dev/null</pre><pre>sudo apt update<br>sudo apt install jenkins -y</pre><p>Start Jenkins:</p><pre>sudo systemctl start jenkins<br>sudo systemctl enable jenkins</pre><p>Access Jenkins in browser:</p><pre>http://&lt;server-ip&gt;:8080</pre><p>Retrieve initial admin password:</p><pre>sudo cat /var/lib/jenkins/secrets/initialAdminPassword</pre><h3>2. Install Required Jenkins Plugins</h3><p>Inside Jenkins, install the following plugins:</p><ul><li>Git Plugin</li><li>Pipeline Plugin</li><li>Docker Pipeline</li><li>Email Extension Plugin</li><li>Credentials Plugin</li></ul><p>These plugins enable Jenkins to integrate with source control, containers, and notification systems.</p><h3>3. Tools Used in the Pipeline</h3><p>This pipeline integrates several DevOps tools:</p><h3>Git</h3><p>Used to clone source code from GitHub.</p><h3>Docker</h3><p>Builds container images for application services.</p><h3>Trivy</h3><p>Performs vulnerability scanning on:</p><ul><li>source filesystem</li><li>Docker images</li></ul><h3>Kind</h3><p>Creates a local Kubernetes cluster for testing deployments.</p><h3>Helm</h3><p>Manages Kubernetes application deployments using charts.</p><h3>4. Pipeline Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFUBB_y4oFVMNI6xlA81pQ.png" /></figure><p>The pipeline performs the following steps:</p><ol><li>Clone source code from GitHub</li><li>Scan files for vulnerabilities</li><li>Build Docker images</li><li>Scan container images</li><li>Push images to Docker Hub</li><li>Create a Kubernetes cluster</li><li>Deploy application using Helm</li><li>Send email notification</li></ol><p>The pipeline is scheduled using a cron trigger.</p><pre>trigger{<br>    cron(&#39;H 9 * * 1-5&#39;)<br>}</pre><p>This runs the pipeline <strong>every weekday at 9 AM</strong>.</p><h3>5. Stage 1: Git Clone</h3><p>The first stage clones the project repository.</p><pre>stage(&#39;git clone&#39;){<br>    steps{<br>        git(<br>            url: &#39;https://github.com/ranjan-portfolio/Kubernetes.git&#39;,<br>            branch:&#39;main&#39;<br>        )<br>        sh &#39;ls -lart&#39;<br>    }<br>}</pre><p>This ensures Jenkins always works with the latest code.</p><h3>6. Stage 2: File System Security Scan</h3><p>The pipeline scans the repository using Trivy.</p><pre>trivy fs \<br>--severity CRITICAL \<br>--ignore-unfixed \<br>--exit-code 1 \<br>-f json \<br>-o trivy-report-fs.json .</pre><p>Key features:</p><ul><li>Detects <strong>critical vulnerabilities</strong></li><li>Generates <strong>JSON reports</strong></li><li>Fails the build if vulnerabilities exist</li></ul><p>This helps shift security <strong>left in the CI pipeline</strong>.</p><h3>7. Stage 3: Build and Push Docker Images</h3><p>The pipeline builds <strong>three application services</strong>:</p><ul><li>Vote service</li><li>Worker service</li><li>Result service</li></ul><p>Example Docker build:</p><pre>docker build -t ranjanabha/votingapp:${BUILD_NUMBER} ./voting-app/vote/</pre><p>Images are pushed to Docker Hub.</p><pre>docker push ranjanabha/votingapp:${BUILD_NUMBER}</pre><p>Credentials are securely stored using Jenkins credentials:</p><pre>withCredentials([string(credentialsId: &#39;DOCKER_TOKEN&#39;, variable: &#39;TOKEN&#39;)])</pre><h3>8. Parallel Builds</h3><p>To speed up execution, Jenkins runs builds in <strong>parallel stages</strong>.</p><pre>parallel{<br>    stage(&#39;build voteapp image&#39;)<br>    stage(&#39;build worker image&#39;)<br>    stage(&#39;build result image&#39;)<br>}</pre><p>Benefits:</p><ul><li>Faster pipeline execution</li><li>Better resource utilization</li><li>Independent microservice builds</li></ul><h3>9. Container Image Security Scan</h3><p>After building images, Trivy scans them for vulnerabilities.</p><p>Example:</p><pre>trivy image \<br>--severity=CRITICAL \<br>--ignore-unfixed \<br>ranjanabha/votingapp:${BUILD_NUMBER}</pre><p>If vulnerabilities are found, the build <strong>fails immediately</strong>.</p><h3>10. Create Local Kubernetes Cluster</h3><p>The pipeline checks if a cluster exists using Kind.</p><pre>kind get clusters | grep -q &quot;^dev$&quot;</pre><p>If not, it creates one:</p><pre>kind create cluster --name dev</pre><p>This allows developers to test deployments locally.</p><h3>11. Deploy Application Using Helm</h3><p>The deployment stage uses Helm:</p><pre>helm upgrade --install voting-app ./voting-app/chart-simple/.</pre><p>This command:</p><ul><li>installs the application if not present</li><li>upgrades existing deployment</li></ul><p>Helm simplifies Kubernetes deployments using reusable charts.</p><h3>12. Post Build Actions</h3><p>Jenkins performs post-build actions.</p><h3>Always</h3><pre>post{<br>    always{<br>        echo &#39;Deployment script executed&#39;<br>    }<br>}</pre><h3>On Success</h3><p>Jenkins sends an email notification:</p><pre>emailext(<br> subject: &quot;Build Successful&quot;<br>)</pre><h3>On Failure</h3><p>If the build fails, Jenkins notifies the team for investigation.</p><p>Finally the full script for everyones reference</p><pre>pipeline{<br>    agent any<br>    <br>    trigger{<br>        cron(&#39;H 9 * * 1-5&#39;)<br>    }<br>    stages{<br>        stage(&#39;git clone&#39;){<br>            steps{<br>                git(<br>                    url: &#39;https://github.com/ranjan-portfolio/Kubernetes.git&#39;,<br>                    branch:&#39;main&#39;<br>                )<br>                echo &#39;listing clone directories..&#39;<br>                sh &#39;ls -lart&#39;<br>            }<br>        }<br>        stage(&#39;file scan&#39;){<br>            steps{<br>                sh &#39;&#39;&#39;<br>                export PATH=\$PATH:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin<br>                /opt/homebrew/bin/trivy fs \<br>                --severity CRITICAL \<br>                --ignore-unfixed \<br>                --exit-code 1 \<br>                -f json \<br>                -o trivy-report-fs.json \<br>                --db-repository public.ecr.aws/aquasecurity/trivy-db \<br>                 .<br>                &#39;&#39;&#39;<br>            }<br>        }<br>        stage(&#39;build image &amp; push&#39;){<br>            <br>            parallel{<br>                stage(&#39;build voteapp image and push to docker&#39;){<br>                    steps{<br>                            echo &#39;building voteapp image ..&#39;<br>                            withCredentials([string(credentialsId: &#39;DOCKER_TOKEN&#39;, variable: &#39;TOKEN&#39;)]){<br>                                sh &#39;&#39;&#39;<br>                                    export DOCKER_CONFIG=$(mktemp -d)<br>                                    echo $TOKEN|/opt/homebrew/bin/docker login -u ranjanabha --password-stdin<br>                                    /opt/homebrew/bin/docker build -t ranjanabha/votingapp:${BUILD_NUMBER} ./voting-app/vote/<br>                                    /opt/homebrew/bin/trivy image --severity=CRITICAL --ignore-unfixed -f json -o trivy-image-report-vote-${BUILD_NUMBER}.json ranjanabha/votingapp:${BUILD_NUMBER} --exit-code 1<br>                                    /opt/homebrew/bin/docker push ranjanabha/votingapp:${BUILD_NUMBER} <br>                        <br>                                &#39;&#39;&#39;<br>                            }<br>                        }<br>                    }<br>                stage(&#39;build worker image and push to docker&#39;){<br>                    steps{<br>                        echo &#39;building image ..&#39;<br>                            withCredentials([string(credentialsId: &#39;DOCKER_TOKEN&#39;, variable: &#39;TOKEN&#39;)]){<br>                                sh &#39;&#39;&#39;<br>                                    export DOCKER_CONFIG=$(mktemp -d)<br>                                    echo $TOKEN|/opt/homebrew/bin/docker login -u ranjanabha --password-stdin<br>                                    /opt/homebrew/bin/docker build -t ranjanabha/worker:${BUILD_NUMBER} ./voting-app/worker/<br>                                    /opt/homebrew/bin/docker push ranjanabha/worker:${BUILD_NUMBER} <br>                        <br>                                &#39;&#39;&#39;<br>                            }<br>                    }<br><br>                }<br>                stage(&#39;build result image and push to docker&#39;){<br>                    steps{<br>                        echo &#39;building image ..&#39;<br>                            withCredentials([string(credentialsId: &#39;DOCKER_TOKEN&#39;, variable: &#39;TOKEN&#39;)]){<br>                                sh &#39;&#39;&#39;<br>                                    export DOCKER_CONFIG=$(mktemp -d)<br>                                    echo $TOKEN|/opt/homebrew/bin/docker login -u ranjanabha --password-stdin<br>                                    /opt/homebrew/bin/docker build -t ranjanabha/result:${BUILD_NUMBER} ./voting-app/result/<br>                                    /opt/homebrew/bin/trivy image --severity=CRITICAL --ignore-unfixed -f json -o trivy-image-report-result-${BUILD_NUMBER}.json ranjanabha/result:${BUILD_NUMBER} --exit-code 1<br>                                    /opt/homebrew/bin/docker push ranjanabha/result:${BUILD_NUMBER} <br>                        <br>                                &#39;&#39;&#39;<br>                            }<br>                    }<br>                }<br>            }<br>        }<br>        <br>        stage(&#39;spin local cluster&#39;){<br>            steps{<br>                <br>                sh &#39;&#39;&#39;<br>                      export PATH=$PATH:/opt/homebrew/bin<br>                      if ! /opt/homebrew/bin/kind get clusters|grep -q &quot;^dev$&quot; ; then<br>                           /opt/homebrew/bin/kind create cluster --name &quot;dev&quot;<br>                      fi<br>                &#39;&#39;&#39;<br>              <br>            }<br>        }<br>        <br>        stage(&#39;deployment&#39;){<br>            steps{<br>                sh &#39;&#39;&#39;<br>                 export PATH=$PATH:/opt/homebrew/bin<br>                  /opt/homebrew/bin/helm upgrade --install voting-app ./voting-app/chart-simple/.<br>                &#39;&#39;&#39;<br>            }<br>            <br>        }<br>        <br>    }<br>    <br>    <br>    post{<br>        always{<br>                echo &#39;Deployment script executed&#39;<br>        }<br>        success{<br>            echo &#39;Deployment successful&#39;<br>            emailext(<br>                subject: &quot;Build Successful: ${env.JOB_NAME} #${env.BUILD_NUMBER}&quot;,<br>                body: &quot;&quot;&quot;<br>                    Hello Team,<br><br>                    The build has success.<br><br>                    Job: ${env.JOB_NAME}<br>                    Build Number: ${env.BUILD_NUMBER}<br>                    Check details here: ${env.BUILD_URL}<br><br>                    Thanks,<br>                    Jenkins<br>                &quot;&quot;&quot;,<br>                to: &quot;ranjanabha@gmail.com&quot;<br>            )<br>        }<br>        failure{<br>            echo &#39;Deployment failed&#39;<br>            emailext(<br>                subject: &quot;Build Failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}&quot;,<br>                body: &quot;&quot;&quot;<br>                    Hello Team,<br><br>                    The build has failed.<br><br>                    Job: ${env.JOB_NAME}<br>                    Build Number: ${env.BUILD_NUMBER}<br>                    Check details here: ${env.BUILD_URL}<br><br>                    Please investigate.<br><br>                    Thanks,<br>                    Jenkins<br>                &quot;&quot;&quot;,<br>                to: &quot;ranjanabha@gmail.com&quot;<br>            )<br>        }<br>    }<br>}</pre><h3>13. Benefits of This Pipeline</h3><p>This CI/CD pipeline provides several advantages:</p><h3>Automated CI/CD</h3><p>No manual intervention required.</p><h3>Security Integration</h3><p>Trivy ensures vulnerabilities are detected early.</p><h3>Parallel Execution</h3><p>Faster build pipelines.</p><h3>Kubernetes Deployment</h3><p>Automated container orchestration.</p><h3>Monitoring and Notifications</h3><p>Email alerts for success or failure.</p><h3>Conclusion</h3><p>Using Jenkins as a CI/CD engine allows teams to automate complex workflows such as building images, scanning vulnerabilities, and deploying to Kubernetes.</p><p>By integrating tools like Docker, Trivy, Helm, and Kind, teams can build a <strong>secure and fully automated DevOps pipeline</strong>.</p><p>This approach ensures faster releases, improved security, and reliable deployments in modern cloud-native environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a2eeb8d1e4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Canary: Automating AKS Deployments with Terraform, Helm, and Argo Rollouts]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/from-zero-to-canary-automating-aks-deployments-with-terraform-helm-and-argo-rollouts-3fef39e4d653?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fef39e4d653</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 18:53:48 GMT</pubDate>
            <atom:updated>2026-01-04T18:53:48.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k79sywP2Cw_tkgLTUXD50g.jpeg" /></figure><p>Modern Kubernetes deployments demand safety, observability, and automation.</p><p>In my previous article, I demonstrated how to implement <strong>blue-green deployments on AKS</strong> using <strong>node pool isolation with taints, tolerations, and node affinity</strong>.</p><p>In this article, we go one step further and implement <strong>canary deployments using Argo Rollouts</strong>, fully automated using <strong>Shell scripts, Terraform, and Helm</strong> — without touching the Azure Portal.</p><p>By the end of this article, you’ll see how a single script can provision an AKS cluster, deploy an application with observability, and safely roll out changes using canary strategies driven by metrics.</p><blockquote><strong><em>Prerequisites:</em></strong><em> Basic Kubernetes, Helm, and Terraform knowledge</em></blockquote><p>Below is the unix script that does all the magic work.</p><ul><li>Logs into Azure and configures ARM credentials</li><li>Sets up a Terraform backend for state locking</li><li>Provisions an AKS cluster</li><li>Installs Argo Rollouts CRDs</li><li>Deploys the application, Prometheus, Grafana, and NGINX Ingress using Helm</li><li>Exposes application and dashboard URLs</li></ul><pre>#!/bin/sh<br><br>GREEN=&#39;\033[0;32m&#39;<br>RED=&#39;\033[0;31m&#39;<br>YELLOW=&#39;\033[1;33m&#39;<br>BLUE=&#39;\033[0;34m&#39;<br><br>echo &quot;${BLUE} Logging into Azure...&quot;<br># Section 1: Logs into Azure account and set environment variable<br>az login<br>SUBSCRIPTION_ID=$(az account show --query id -o tsv)<br>export ARM_SUBSCRIPTION_ID=$SUBSCRIPTION_ID<br>echo -e &quot;${GREEN} Azure login completed&quot;<br><br>echo -e &quot;${BLUE} Going to check terraform backend availability and create cluster...&quot;<br><br># Section 2: Creates Terraform back end for state managment and locking<br><br># Change directory first so subsequent paths work relative to aks-terraform<br>cd ../aks-terraform/<br><br>echo -e &quot;${BLUE} Checking if terraform backend is available...&quot;<br># Run the check command and use an &#39;if&#39; block immediately to capture success/failure<br>if az storage account show --name &quot;uniquestatesaname12345&quot; --resource-group &quot;TerraformStateRG&quot; --query location &gt; /dev/null 2&gt;&amp;1; then<br>    echo -e &quot;${BLUE} Backend storage account already exists.&quot;<br>else<br>    echo -e &quot;${RED} Backend storage account not found. Creating now...&quot;<br>    ./shell/configure-backend.sh<br>    if [ $? -ne 0 ]; then<br>        echo -e &quot;${RED} ERROR: configure-backend.sh failed. Exiting.&quot;<br>        exit 1<br>    fi<br>fi<br><br># Section 3: Uses Terraform to create AKS cluster<br><br># Initialize terraform (required to load backend config)<br>terraform init<br><br># Saves terraform plan<br>PLAN_FILE=&quot;./plan/plan_$(date +%Y-%m-%d_%H-%M-%S).tfplan&quot;<br>mkdir -p ./plan<br>echo -e &quot;${BLUE} Running terraform plan...&quot;<br>terraform plan -out &quot;$PLAN_FILE&quot;<br><br>echo -e &quot;${BLUE} Running terraform apply...&quot;<br>terraform apply --auto-approve &quot;$PLAN_FILE&quot;<br><br># Capture cluster details using the -raw flag for clean strings<br>cluster_name=$(terraform output -raw aks_cluster_name)<br>resource_group_name=$(terraform output -raw aks_resource_group_name)<br><br>if [ -z &quot;$cluster_name&quot; ]; then<br>    echo -e &quot;${RED}❌ Terraform encountered issue while creating cluster or output is empty.&quot;<br>    exit 1<br>else<br>    echo -e &quot;${GREEN} ✅  Kubernetes cluster created: Name is $cluster_name&quot;<br>fi<br><br>echo -e &quot;${BLUE} Fetching cluster details and configuring kubectl&quot;<br># Use the variables captured above<br>az aks get-credentials --resource-group &quot;$resource_group_name&quot; --name &quot;$cluster_name&quot; --overwrite-existing --only-show-errors<br><br>cd ../canary/voting-app<br><br># Section 4: Deploys ARGO CRD<br>echo -e &quot;${BLUE} Installing Argo rollout CRD...&quot;<br>kubectl create namespace argo-rollouts<br>kubectl apply -n argo-rollouts -f https://raw.githubusercontent.com/argoproj/argo-rollouts/stable/manifests/install.yaml<br>echo -e &quot;${GREEN} ✅  Argo rollout CRD installation completed&quot;<br><br># Section 5: Deploys application stack<br>cd chart<br>echo -e &quot;${BLUE} Installing canary chart.. this will install vote-app,prometheus and grafana&quot;<br>helm install canary .<br><br>echo -e &quot;${GREEN} ✅ Helm deployment completed&quot;<br><br>echo -e &quot;${BLUE} waiting for ingress loadbalancer to be ready&quot;<br><br>INGRESS_SVC_NAME=canary-ingress-nginx-controller<br>INGRESS_NAMESPACE=default<br><br>EXTERNAL_IP=&#39;&#39;<br><br>while [ -z &quot;$EXTERNAL_IP&quot; ]; do<br> echo -e &quot;${RED} External IP is pending.. waiting for 10 sec&quot;<br> sleep 10<br> EXTERNAL_IP=$(kubectl get svc &quot;$INGRESS_SVC_NAME&quot; -n &quot;$INGRESS_NAMESPACE&quot; --output jsonpath=&#39;{.status.loadBalancer.ingress[0].ip}&#39;)<br>done<br><br>echo -e &quot;${GREEN} ✅ Got External IP:: $EXTERNAL_IP&quot;<br><br># Section 5: Deploys application sanity<br><br>curl -H &quot;host:vote.example.com&quot; http://&quot;$EXTERNAL_IP&quot; --silent --output /dev/null<br><br>if [ $? -eq 0 ]; then<br>  echo -e &quot;${GREEN} ✅ Curl command executed successfully at the network level.&quot;<br>else<br>  echo -e &quot;${RED} ❌ Curl command failed at the network level (e.g., connection refused, DNS error).&quot;<br>fi<br><br># Section 6: Deploys Argo Dashboard<br><br>echo -e &quot;${BLUE} Rolling out argo dahsboard...&quot;<br><br>kubectl argo rollouts dashboard --namespace default &amp;<br><br># Section 7: Modifies /etc/hosts for application access<br><br>sudo sed -i&quot;.bak&quot; &quot;/vote.example.com/s/.*/&quot;$EXTERNAL_IP&quot;\tvote.example.com/&quot; &quot;/etc/hosts&quot;<br><br>echo -e &quot;${GREEN} Argo rollout dashboard URL: http://localhost:3100/rollouts&quot;<br><br>echo -e &quot;${GREEN} Application URL: http://vote.example.com&quot;<br><br><br>echo -e &quot;${GREEN} Bootstrapping complete...&quot;</pre><p>Under the hood we are using Terraform script for creating AKS cluster.</p><p>Below is the basic blue print of our Terraform script. The script uses modular code to create AKS Kubernetes cluster, Resource group and use random module to generate cluster and resource group names.</p><pre># main.tf<br><br>module &quot;random&quot; {<br>  source = &quot;./modules/random&quot;<br>  length = 2<br>}<br><br>module &quot;resource_group&quot; {<br>  source = &quot;./modules/rg&quot;<br>  name   = module.random.random_id<br>}<br><br>module &quot;aks&quot; {<br>  source    = &quot;./modules/aks&quot;<br>  location  = module.resource_group.location<br>  name      = module.resource_group.resource_group_name<br>  random_id = module.random.random_id<br>}<br><br>#output<br><br>output &quot;aks_cluster_name&quot; {<br>  value       = module.eks.kubernetes_cluster_name<br>  description = &quot;AKS cluster name from module.eks&quot;<br>}<br><br>output &quot;aks_resource_group_name&quot; {<br>  value       = module.resource_group.resource_group_name<br>  description = &quot;This is resource group name&quot;<br>}<br><br># eks module<br><br>resource &quot;azurerm_kubernetes_cluster&quot; &quot;default&quot; {<br>  name                = &quot;${var.random_id}-aks&quot;<br>  location            = var.location<br>  resource_group_name = var.name<br>  dns_prefix          = &quot;${var.random_id}-k8s&quot;<br>  kubernetes_version  = &quot;1.34&quot;<br>  oidc_issuer_enabled = true <br><br>  default_node_pool {<br>    name            = &quot;default&quot;<br>    node_count      = 1<br>    vm_size         = &quot;Standard_D2_v4&quot;<br>    os_disk_size_gb = 30<br>  }<br><br> identity {<br>  type = &quot;SystemAssigned&quot;<br> }<br><br>  role_based_access_control_enabled = true<br><br>  tags = {<br>    environment = &quot;Demo&quot;<br>  }<br>}<br><br><br></pre><p>Helm sneak peek that will deploy Prometheus, Grafana and Ingress nginx.</p><pre>#Chart.yaml<br><br>apiVersion: v2<br>name: voting-app<br>description: A Helm chart for the Polyglot Voting Application with Canary Rollouts<br>type: application<br><br># The chart version (increments when you change the Helm configuration)<br>version: 1.0.0<br><br># The application version (increments when you update the actual Vote/Result code)<br>appVersion: &quot;42.0.0&quot;<br><br>maintainers:<br>- name: Ranjanabha<br>  email: ranjanabha@tcs.com<br><br># In 2025, we use dependencies to pull in stable community charts<br>dependencies:<br>- name: prometheus<br>  version: &quot;27.52.0&quot; # Use the current stable version for 2025<br>  repository: &quot;https://prometheus-community.github.io/helm-charts&quot;<br>  # Optional: Use a condition to toggle it on/off in values.yaml<br>  condition: prometheus.enabled<br>- name: grafana<br>  version: &quot;10.4.0&quot; # Current stable major version for late 2025<br>  repository: &quot;https://grafana.github.io/helm-charts&quot;<br><br>- name: ingress-nginx<br>  version: &quot;4.14.1&quot; # specify the chart version<br>  repository: &quot;https://kubernetes.github.io/ingress-nginx&quot;<br><br>annotations:<br>  category: Infrastructure<br>  display-name: Voting App<br><br># Values.yaml<br><br>  ingress-nginx:<br>    controller:<br>      metrics:<br>        enabled: true<br>        service:<br>          enabled: true<br>          type: ClusterIP<br>          ports:<br>            metrics: 10254<br>          annotations:<br>            prometheus.io/scrape: &quot;true&quot;<br>            prometheus.io/port: &quot;10254&quot;<br>            prometheus.io/path: &quot;/metrics&quot;<br><br>      config:<br>        metrics-per-ingress: &quot;true&quot;<br>        metrics-per-host: &quot;true&quot;<br><br>      service:<br>        type: LoadBalancer<br>        annotations:<br>          service.beta.kubernetes.io/azure-load-balancer-health-probe-protocol: tcp<br>          service.beta.kubernetes.io/azure-load-balancer-force-reconcile: &quot;true&quot;<br><br>  prometheus:<br>    server:<br>      service:<br>        type: ClusterIP<br><br>      extraScrapeConfigs:<br>      - job_name: ingress-nginx<br>        kubernetes_sd_configs:<br>        - role: endpoints<br>        relabel_configs:<br>        - source_labels: [ __meta_kubernetes_service_name ]<br>          action: keep<br>          regex: ingress-nginx-controller-metrics<br>        - source_labels: [ __meta_kubernetes_endpoint_port_name ]<br>          action: keep<br>          regex: metrics<br><br>    alertmanager:<br>      enabled: false<br><br>    pushgateway:<br>      enabled: false<br><br>  grafana:<br>    adminUser: admin<br>    adminPassword: &lt;&lt;Password&gt;&gt;<br><br>    dashboardProviders:<br>      dashboardproviders.yaml:<br>        apiVersion: 1<br>        providers:<br>        - name: default<br>          orgId: 1<br>          folder: Kubernetes<br>          type: file<br>          disableDeletion: false<br>          editable: true<br>          options:<br>            path: /var/lib/grafana/dashboards/default<br><br>    dashboards:<br>      default:<br>        kubernetes-cluster:<br>          gnetId: 315<br>          revision: 3<br>          datasource: Prometheus<br><br>        node-exporter-full:<br>          gnetId: 1860<br>          revision: 33<br>          datasource: Prometheus<br><br>        kubernetes-pods:<br>          gnetId: 893<br>          revision: 1<br>          datasource: Prometheus<br><br>        kubernetes-deployments:<br>          gnetId: 747<br>          revision: 1<br>          datasource: Prometheus<br><br>        ingress-nginx:<br>          gnetId: 12121<br>          revision: 1<br>          datasource: Prometheus<br><br>    service:<br>      type: ClusterIP<br>      port: 3000<br><br>    persistence:<br>      enabled: false<br><br>    datasources:<br>      datasources.yaml:<br>        apiVersion: 1<br>        datasources:<br>        - name: Prometheus<br>          type: prometheus<br>          access: proxy<br>          url: http://canary-prometheus-server.default.svc.cluster.local<br>          isDefault: true<br><br>    sidecar:<br>      dashboards:<br>        enabled: true<br>        label: grafana_dashboard<br>      datasources:<br>        enabled: true</pre><p>For full code preview please visit my Github link:</p><p><a href="https://github.com/ranjan-portfolio/Kubernetes.git">https://github.com/ranjan-portfolio/Kubernetes.git</a>.</p><p>This will download below folders canary, aks-terraform and bootstrap folder.</p><p>Our point of interest</p><ol><li>canary/voting-app/chart -&gt; For voting-app helm chart</li><li>aks-terraform -&gt; Terraform modules and main scripts for AKS cluster creation.</li><li>bootstrap -&gt; Scripts for bootstraping our application stack, destroy the application stack and test the application.</li></ol><p>Below video shows the script in action</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDeTFWCKNiQc&amp;type=text%2Fhtml&amp;schema=google&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDeTFWCKNiQc" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f4aa0dc2e434c071a8810180577b0ad/href">https://medium.com/media/8f4aa0dc2e434c071a8810180577b0ad/href</a></iframe><p>After the script action we now have our vote-app deployed with observabilty stack Prometheus and Grafana dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YjCw5ZvUGworpa8Z3_WPyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nn7rorKSCVvWhzj5kBkeaw.png" /></figure><p>For canary deployment I already have created the stage.</p><p>Unlike standard Kubernetes Deployments, Argo Rollouts allows fine-grained traffic control, metric-based analysis, and automated rollback — making it ideal for production-grade canary deployments. The configuration file uses deployment strategy as canary with traffic routing stages starting with 20% requests being sent to canary deployment and 80% to stable. The stage analyses traffic using an AnalysisTemplate and steps up traffic routing based on analysis outcome.</p><p>If analysis fails deployment will be reverted to previous version.</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Rollout<br>metadata:<br>  labels:<br>    app: vote<br>  name: vote<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: vote<br>  template:<br>    metadata:<br>      labels:<br>        app: vote<br>    spec:<br>      containers:<br>      - image: dockersamples/examplevotingapp_vote<br>        name: vote<br>        ports:<br>        - containerPort: 80<br>          name: vote<br>        envFrom:<br>        - configMapRef:<br>            name: vote-config  <br>  strategy:<br>    canary:<br>      stableService: vote-stable<br>      canaryService: vote-canary<br>      trafficRouting:<br>        nginx:<br>          stableIngress: vote-ingress<br>      steps:<br>      <br>      - setWeight: 20<br>      # The following pause step will pause the rollout indefinitely until manually resumed.<br>      # Rollouts can be manually resumed by running `kubectl argo rollouts promote ROLLOUT`<br>      - pause: {duration: 1m}<br>      - analysis:<br>          templates:<br>          - templateName: success-rate<br>          args:<br>          - name: service-name<br>            value: vote-canary<br>      - setWeight: 40<br>      - pause: {duration: 40s}<br>      - setWeight: 60<br>      - pause: {duration: 20s}<br>      - setWeight: 80<br>      - pause: {duration: 20s}</pre><p>Analysis template example below. The analysis template makes use of prometheus query given in metrics section to determine if canary deployment is stable.</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: AnalysisTemplate<br>metadata:<br>  name: success-rate<br>spec:<br>  args:<br>    - name: service-name<br>  metrics:<br>    - name: success-rate<br>      # How often to check the metric<br>      interval: 1m<br>      count: 3  <br>      # How many times it can fail before aborting the rollout<br>      failureLimit: 3<br>      # The condition that must be true for the check to pass<br>      successCondition: &quot;{{ `len(result) == 0 || (len(result) &gt; 0 &amp;&amp; result[0] &lt; 0.05)` }}&quot; <br>      provider:<br>        prometheus:<br>          # Replace with your actual Prometheus service address<br>          address: http://canary-prometheus-server.default.svc.cluster.local<br>          query: |<br>            sum(<br>                rate(nginx_ingress_controller_requests{<br>                service=&quot;{{`{{args.service-name}}`}}&quot;,<br>                status=~&quot;5..&quot;<br>              }[5m]))<br>            /<br>            sum(<br>                rate(nginx_ingress_controller_requests{<br>                service=&quot;{{`{{args.service-name}}`}}&quot;<br>            }[5m]))</pre><p>For canary deployment demo I will remove the configMap section from the Rollout config and use Helm to upgrade the deployment. Argo rollout will check the hash of the Rollout and since it changes now Argo will kick the canary deployment process.</p><p>Lets see the canary rollout in action</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUb_594W6JfM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUb_594W6JfM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUb_594W6JfM%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c27d25a314e5d246645f3c21f60eecf/href">https://medium.com/media/8c27d25a314e5d246645f3c21f60eecf/href</a></iframe><p><strong>Conclusion</strong></p><p>In this article, we automated the complete lifecycle of a Kubernetes canary deployment — from infrastructure provisioning to traffic analysis — using Terraform, Helm, and Argo Rollouts on AKS.</p><p>By combining GitOps-friendly tools with metrics-driven decision making, we can safely release changes with minimal risk and zero manual intervention.</p><p>In the next article, we’ll take this further by replacing the Ingress layer with the <strong>Kubernetes Gateway API</strong> to enable more advanced traffic management patterns.</p><p><strong>#Kubernetes #DevOps #ArgoRollouts #Azure #CanaryDeployment</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fef39e4d653" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blue-Green Deployment in AKS Using Taints, Tolerations, and Node Affinity]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/blue-green-deployment-in-aks-using-taints-tolerations-and-node-affinity-04d9d2baf255?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/04d9d2baf255</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 17:33:04 GMT</pubDate>
            <atom:updated>2025-12-25T17:33:04.367Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s blog, we will cover <strong>Blue-Green deployment in Kubernetes</strong>.<br>Instead of using the typical <strong>namespace- and service-based approach</strong>, we will implement <strong>taints, tolerations, and node affinity</strong> to achieve <strong>hard isolation</strong> between Blue and Green environments.</p><p>The demo is implemented using <strong>Azure Kubernetes Service (AKS)</strong>.</p><h3>Tech Stack</h3><ul><li><strong>Azure AKS</strong></li><li><strong>Helm</strong></li><li><strong>Unix / CLI</strong></li></ul><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pC0TnKCtZvScssbyLUe4kA.png" /></figure><p>We will use the popular <strong>vote-app</strong> from Docker samples and extend it to demonstrate a Blue-Green deployment strategy using <strong>separate AKS node pools</strong>.</p><h3>Node Pool Strategy</h3><p>The AKS cluster contains <strong>two node pools</strong>:</p><ol><li><strong>Blue Node Pool</strong></li></ol><ul><li>Hosts system pods</li><li>Hosts Blue application pods</li></ul><p><strong>2. Green Node Pool</strong></p><ul><li>Hosts Green application pods only</li></ul><p>We leverage:</p><ul><li><strong>Taints</strong> to repel unwanted pods</li><li><strong>Tolerations</strong> to explicitly allow scheduling</li><li><strong>Node Affinity</strong> to guarantee pod placement</li></ul><p>Each component of the vote-app has <strong>two deployments</strong>:</p><ul><li>One for <strong>Blue</strong></li><li>One for <strong>Green</strong></li></ul><p>Initially, the <strong>vote service</strong> points to the Blue pods.<br> Later, we switch the service selector to Green pods, achieving <strong>zero downtime deployment</strong>.</p><p>📌 <strong>End Result</strong></p><ul><li>Initially: voting between <strong>Cats vs Dogs</strong></li><li>After switch: voting between <strong>Democrat vs Republican</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXJDykG9363Lr-2-k0RNSg.png" /></figure><p><strong>Step 1: Create AKS Cluster</strong></p><ul><li>Search for <strong>Kubernetes Service</strong> in Azure Portal</li><li>Click <strong>Create</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIfVRdzkNNSYSrKM6--7Cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqQBLIGV7YtWFiYk5Ms_hw.png" /></figure><p><strong>Step 2: Configure Basic Settings</strong></p><ul><li>Choose a resource group</li><li>Provide a cluster name</li><li>Keep remaining settings default</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBe5BHZUS0zY2FBEa-fSKQ.png" /></figure><p><strong>Step 3: Configure Node Pools</strong></p><p>By default, AKS provides one agent pool.<br> Since this demo uses Azure Free Tier (4 vCPU limit), we customize node pools.</p><h4>Blue Node Pool</h4><ul><li>Rename default pool to <strong>blue</strong></li><li>Set min/max node count to <strong>1</strong></li><li>Enable <strong>Public IP per node</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUWpWwG_ezD3TcMpL44wLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECHAFCRNIBy_80kq1TMqhA.png" /></figure><p>Add label:</p><pre>environment=blue</pre><p>Add taints</p><pre>environment=blue:NoSchedule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hV7mDlLSue5LdLhvzy-_Tg.png" /></figure><p>This ensures:</p><ul><li>Only pods with matching tolerations are scheduled</li><li>System pods can still run in this pool</li></ul><h4>Green Node Pool</h4><ul><li>Add new node pool named <strong>green</strong></li><li>Node count: <strong>1</strong></li><li>Add label:</li></ul><pre>environment=green</pre><p>. Add taint:</p><pre>environment=green:NoSchedule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nzN-UhCLK6Otrpu6LVaQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1Oymr4Hw-RhP5bwUnGYTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_B9_Z7pEu8_gOsx4hmbkg.png" /></figure><p>Click <strong>Review + Create</strong> and wait for the cluster to be provisioned.</p><p><strong>Step 4: Blue-Green Deployment Configuration</strong></p><h4>Helm Chart Structure</h4><ul><li>Created a chart/ directory</li><li>Copied existing vote-app manifests</li><li>Created <strong>separate deployments</strong> for:</li></ul><p>1. vote</p><p>2. result</p><p>3. worker</p><p>4. redis</p><p>5. postgres</p><p>for both <strong>Blue</strong> and <strong>Green</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*A1qlj9pHMb_OH8mXo467kA.png" /></figure><p>Blue deployment example</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: vote-blue<br>  labels:<br>    app: vote-blue<br>    environment: blue<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: vote-blue<br>  template:<br>    metadata:<br>      labels:<br>        app: vote-blue<br>    spec:<br>      containers:<br>      - name: vote-blue<br>        image: azureciregistry.azurecr.io/votingapp/vote:57<br>        ports:<br>        - containerPort: 80<br>        startupProbe:<br>          httpGet:<br>            path: /<br>            port: 80<br>          failureThreshold: 6<br>          periodSeconds: 5<br>        readinessProbe:<br>          httpGet:<br>            path: /<br>            port: 80<br>          periodSeconds: 10<br>        livenessProbe:<br>          httpGet:<br>            path: /<br>            port: 80<br>          periodSeconds: 30<br>      tolerations:<br>      - key: &quot;environment&quot;<br>        operator: &quot;Equal&quot;<br>        value: &quot;blue&quot;<br>        effect: &quot;NoSchedule&quot;<br>      affinity:<br>        nodeAffinity:<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>            nodeSelectorTerms:<br>            - matchExpressions:<br>              - key: environment<br>                operator: In<br>                values:<br>                - blue<br>      resources:<br>        requests:<br>          cpu: &quot;100m&quot;<br>          memory: &quot;128Mi&quot;<br>        limits:<br>          cpu: &quot;200m&quot;<br>          memory: &quot;256Mi&quot;</pre><p>Green deployment example</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: vote-green<br>  labels:<br>    app: vote-green<br>    environment: green<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: vote-green<br>      environment: green<br>  template:<br>    metadata:<br>      labels:<br>        app: vote-green<br>        environment: green<br>    spec:<br>      containers:<br>      - name: vote-green<br>        image: azureciregistry.azurecr.io/votingapp/vote:57<br>        ports:<br>        - containerPort: 80<br>        envFrom:<br>        - configMapRef:<br>            name: vote-config<br>        startupProbe:<br>          httpGet:<br>            path: /<br>            port: 80<br>          failureThreshold: 6<br>          periodSeconds: 5<br>        readinessProbe:<br>          httpGet:<br>            path: /<br>            port: 80<br>          periodSeconds: 10<br>        livenessProbe:<br>          httpGet:<br>            path: /<br>            port: 80<br>          periodSeconds: 30<br>      tolerations:<br>      - key: &quot;environment&quot;<br>        operator: &quot;Equal&quot;<br>        value: &quot;green&quot;<br>        effect: &quot;NoSchedule&quot;<br>      affinity:<br>        nodeAffinity:<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>            nodeSelectorTerms:<br>            - matchExpressions:<br>              - key: environment<br>                operator: In<br>                values:<br>                - green<br>      resources:<br>        requests:<br>          cpu: &quot;100m&quot;<br>          memory: &quot;128Mi&quot;<br>        limits:<br>          cpu: &quot;200m&quot;<br>          memory: &quot;256Mi&quot;</pre><p>ConfigMap for UI Customization</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: vote-config<br>data:<br>  OPTION_A: Democrat<br>  OPTION_B: Republican</pre><p>Helm Chart Metadata (Chart.yaml)</p><pre>apiVersion: v2<br>name: vote-app<br>description: A Helm chart for vote-app<br>type: application<br>version: 1.0.0<br>appVersion: &quot;1.0.0&quot;<br>maintainers:<br>- name: Ranjanabha Bhattacharya<br>  email: ranjanabha@gmail.com<br>kubeVersion: &quot;&gt;=1.25.0-0&quot;</pre><p><strong>Step 5: Install Helm</strong></p><pre>curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3<br>chmod 700 get_helm.sh<br>./get_helm.sh</pre><p><strong>Step 6: Configure kubeconfig</strong></p><p>From Azure Portal:</p><ul><li>Open AKS cluster</li><li>Click <strong>Connect</strong></li><li>Run the provided commands locally</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raot01lQ83f6Zslh1cQmUQ.png" /></figure><p><strong>Step 7: Deploy the Application</strong></p><pre>git clone https://github.com/ranjanabha/Kubernetes.git<br>cd vote-app<br>helm install blue ./chart</pre><p>Verify:</p><pre>kubectl get pods -o wide</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vz9EucgU7EG3wyG84NBM7w.png" /></figure><p><strong>Step 8: Access the Application</strong></p><p>Allow NodePort access in:</p><p>VM Scale Set → Node Pool → Networking → Inbound Port Rules</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHQ9MXvwJ6NfxFTse92A3g.png" /></figure><p>Get node IP:</p><pre>kubectl get nodes -o wide</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoQ8DwSGm2yWDtNAz3DMRw.png" /></figure><p>Access:</p><pre>http://&lt;NODE_IP&gt;:&lt;NODE_PORT&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T13ZwamH2dzdeZfTM7yGvw.png" /></figure><p><strong>Step 9: Switch Traffic to Green (Zero Downtime)</strong></p><pre>kubectl edit svc vote</pre><p>Change selector from:</p><pre>app: vote-blue</pre><p>To</p><pre>app: vote-green</pre><p>Refresh the page.</p><p>✨ <strong>Voila! Zero-downtime Blue → Green switch completed.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iw1Hwky8rW64eIt-5DHpDA.png" /></figure><h3>Conclusion</h3><p>In this article, we:</p><ul><li>Created an AKS cluster with <strong>isolated node pools</strong></li><li>Deployed Blue and Green versions using <strong>Helm</strong></li><li>Enforced strict isolation using <strong>taints, tolerations, and affinity</strong></li><li>Switched traffic instantly by updating the service selector</li></ul><p>The application transitioned from <strong>Cats vs Dogs</strong> to <strong>Democrat vs Republican</strong> without any downtime.</p><p>For full code please visit my github</p><p><a href="https://github.com/ranjanabha/Kubernetes.git">https://github.com/ranjanabha/Kubernetes.git</a></p><p>👉 In the next blog, we will implement <strong>Canary deployments</strong> using <strong>Argo Rollouts</strong> to gradually shift traffic from Blue to Green.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04d9d2baf255" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Continuous Deployment Pipeline on AKS using Azure DevOps and Argo CD]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/building-a-continuous-deployment-pipeline-on-aks-using-azure-devops-and-argo-cd-cee3c8cf8f1b?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cee3c8cf8f1b</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 21:23:38 GMT</pubDate>
            <atom:updated>2025-12-17T21:23:38.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoCVSKr-1IsD8gDdsBMbDw.png" /></figure><p>In my previous article, I created a <strong>CI pipeline in Azure DevOps</strong> using the <em>voting-example</em> application from Docker’s sample GitHub repository. The pipeline builds Docker images for the <strong>vote</strong>, <strong>result</strong>, and <strong>worker</strong> services and pushes them to <strong>Azure Container Registry (ACR)</strong>.</p><p>In this article, we take the next step and build a <strong>continuous deployment (CD) pipeline</strong> using <strong>Azure Kubernetes Service (AKS)</strong> and <strong>Argo CD</strong>, following GitOps principles.</p><p>By the end of this article, you will have:</p><ul><li>An AKS cluster up and running</li><li>Argo CD installed and configured</li><li>A GitOps-based deployment setup</li><li>An automated pipeline where every successful build is deployed to Kubernetes</li></ul><p>Let’s get started 🚀</p><p><strong>Architecture Overview</strong></p><p>The deployment flow looks like this:</p><ol><li>Azure DevOps CI pipeline builds Docker images and pushes them to ACR</li><li>The pipeline updates Kubernetes deployment manifests with the new image tag</li><li>Changes are committed back to the Git repository</li><li>Argo CD detects the Git change and syncs the application to AKS</li></ol><p>This ensures <strong>Git remains the single source of truth</strong> for deployments.</p><p><strong>Step 1: Create an AKS Cluster</strong></p><p>Navigate to <strong>Azure Portal → Kubernetes services</strong> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFnQSGatTsdqEVDdmiQdaQ.png" /></figure><p>Provide a cluster name and keep most settings as default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k23BnNJxI11nPSYEPiaJAw.png" /></figure><p>Since I am using the <strong>Azure free tier</strong>, I am limited to a single node. Azure automatically provisions a <strong>system node pool</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHJt5dMo0botBw0oeEgefw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa1PFkxRCxmxFO7L6rT-ZQ.png" /></figure><p><strong>Key configurations:</strong></p><ul><li>Node OS: <strong>Ubuntu Linux</strong></li><li>Node count: <strong>1</strong></li><li>Max pods per node: <strong>30</strong></li><li>Enable public IP per node (for demo access)</li></ul><p>⚠️ <strong>Note:</strong> Public IP per node and NodePort exposure are for demo purposes only and should not be used in production environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sTVXfbfwz3V12DJk96Afg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywVMcSQPaQSwzp1k8LwOyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSp_LcLGXBmeIZwiDUB0iQ.png" /></figure><p>Complete the setup by clicking <strong>Review + Create</strong>.</p><p>Cluster provisioning usually takes <strong>10–15 minutes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dp1_sswLel7RFqLCwyWJwg.png" /></figure><p><strong>Step 2: Connect to the AKS Cluster</strong></p><p>Once the cluster is ready, click <strong>Connect</strong> in the Azure Portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5SvbrwjCtrwjt0QbQMhEA.png" /></figure><p>If Azure CLI and kubectl are already installed, run the commands shown under the <strong>Azure CLI</strong> tab to configure kubectl access to the cluster.</p><p>Verify connectivity:</p><p>kubectl get nodes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLYkYMf3cPYSpdAiTbU2NQ.png" /></figure><p><strong>Step 3: Install Argo CD</strong></p><p>Create a dedicated namespace and install Argo CD using the official manifest:</p><pre>kubectl create namespace argocd<br>kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml</pre><p>This installs all required Argo CD components in the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWVsrg2VvilPJZzyUpcZFA.png" /></figure><p><strong>Step 4: Access the Argo CD UI</strong></p><p>By default, the Argo CD server is exposed as a <strong>ClusterIP</strong> service.</p><p>For demo purposes, we’ll expose it using a <strong>NodePort</strong>.</p><p>kubectl edit svc/argocd-server -n argocd</p><p>Change:</p><p>type: ClusterIP</p><p>to:</p><p>type: NodePort</p><p>Once updated, note the assigned NodePort values and ensure the ports are allowed in the node’s network security group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnHQlZx2ce0ymjK3roihzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1E55BXLEJ0o22hf_oYT9cg.png" /></figure><p>To get the node’s public IP:</p><p>kubectl get nodes -o wide</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ydE9ZaSXb75pr5JDe5wRQ.png" /></figure><p>For access from external ip node network settings needs changing to allow inbound port 31908 and 30652.</p><p>Access Argo CD UI using:</p><p>http://&lt;NODE_PUBLIC_IP&gt;:&lt;NODE_PORT&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiZxiNCxsPeMn48o4-fJvQ.png" /></figure><p><strong>Step 5: Retrieve Argo CD Credentials</strong></p><ul><li><strong>Username:</strong> admin</li><li><strong>Password:</strong> stored in a Kubernetes secret</li></ul><p>For password you need to access Argo-CD secret and get the secret value and base64 decode it.</p><pre>kubectl get secret argocd-initial-admin-secret \ -n argocd \ -o jsonpath=&quot;{.data.password}&quot; | base64 -d</pre><p><strong>Step 6: Configure Argo CD Repository and Application</strong></p><p><strong>Add Git Repository</strong></p><p>Navigate to <strong>Settings → Repositories → Connect Repo</strong> and provide:</p><ul><li>Repository URL</li><li>Authentication details (PAT)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QripwZsy0W9tVHR8Eft_Ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jixo4tppitgxQ-rT3GJVvA.png" /></figure><p>Go to <strong>Applications → New App</strong> and configure:</p><ul><li>Application name</li><li>Git repository URL</li><li>Path containing Kubernetes manifests</li><li>Destination cluster and namespace</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0VEOwRxTULkreHMWLhaEQ.png" /></figure><p>Once created, Argo CD automatically syncs and deploys the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJZwe7sQLSpHiaf0XVZnUw.png" /></figure><p>Since this setup uses a single-node free tier cluster, pod scheduling may be constrained and application health may appear <em>Degraded</em>. This is expected for demo environments.</p><p>You can access the applications http://&lt;NODE_PUBLIC_IP&gt;:&lt;NODE_PORT&gt;</p><p>VOTE APP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kriLA362UI5ApgLP4wwcMw.png" /></figure><p>RESULT APP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DXqHzczr1PmLKq9mpRLOQw.png" /></figure><p><strong>Step 7: Automate Deployment from Azure DevOps</strong></p><p>To enable GitOps-style deployment, we update Kubernetes manifests automatically from the CI pipeline.</p><pre>#!/bin/bash<br>set -x<br># Set the repository URL<br>REPO_URL=&quot;https://Bs0WLXbAOGXz79HXgQGTWbETeqsD9bYLYRMrkrKS2qdCUJ18bgFyJQQJ99BLACAAAAAAAAAAAAASAZDO1Ctk@dev.azure.com/ranjanabhabhattacharya/voting-app/_git/voting-app&quot;<br># Clone the git repository into the /tmp directory<br>git clone &quot;$REPO_URL&quot; /tmp/temp_repo<br># Navigate into the cloned repository directory<br>cd /tmp/temp_repo<br># Make changes to the Kubernetes manifest file(s)<br># For example, let&#39;s say you want to change the image tag in a deployment.yaml file<br>sed -i &quot;s|image:.*|image: azureciregistry/$2:$3|g&quot; k8s-specifications/$1-deployment.yaml<br># Add the modified files<br>git add .<br># Commit the changes<br>git commit -m &quot;Update Kubernetes manifest&quot;<br># Push the changes back to the repository<br>git push<br># Cleanup: remove the temporary directory<br>rm -rf /tmp/temp_repo</pre><p><strong>What this script does:</strong></p><ul><li>Clones the Git repository</li><li>Updates the image tag in Kubernetes manifests</li><li>Commits and pushes changes back to Git</li></ul><p>⚠️ <strong>Important Notes</strong></p><ul><li>Store PATs securely using Azure DevOps pipeline variables</li><li>This approach is for learning and demonstration purposes</li><li>Production setups should use stronger access controls</li></ul><p>Add this file by creating a new folder scripts in Azure GIT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6MQXRPNFbG_3BcKDvm3YA.png" /></figure><p>Step 8: Update Azure DevOps Pipeline</p><p>Add a new pipeline stage that:</p><ul><li>Passes deployment name</li><li>Image name</li><li>Build number</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXdI7ZcfrvnkQiQABhsJfg.png" /></figure><p>Once the pipeline runs:</p><ol><li>Manifest files are updated</li><li>Git receives the change</li><li>Argo CD detects the update</li><li>AKS deployment is automatically synced</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkHrj74CeWq5ohpWRT_BZw.png" /></figure><p>Application is now synced with latest image</p><p><strong>Conclusion</strong></p><p>In this article, we built a <strong>complete GitOps-based continuous deployment pipeline</strong> using <strong>Azure DevOps, AKS, and Argo CD</strong>.</p><p>We:</p><ul><li>Created an AKS cluster</li><li>Installed and configured Argo CD</li><li>Automated Kubernetes manifest updates from CI</li><li>Enabled Argo CD to deploy changes automatically</li></ul><p>This setup ensures <strong>every successful build is deployed consistently and reliably</strong>.</p><p>In the next article, we’ll explore <strong>Kubernetes deployment strategies</strong> such as:</p><ul><li>Rolling deployments</li><li>Blue-Green deployments</li><li>Canary deployments</li></ul><p>Stay tuned 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cee3c8cf8f1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating a CI Pipeline from GitHub to Azure DevOps with ACR and GitOps using ArgoCD]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/migrating-a-ci-pipeline-from-github-to-azure-devops-with-acr-and-gitops-using-argocd-dc1e62b66246?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc1e62b66246</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 17:14:52 GMT</pubDate>
            <atom:updated>2025-12-14T17:14:52.800Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I demonstrate how to migrate an existing CI pipeline from GitHub to <strong>Azure DevOps</strong> and build container images using <strong>Azure Pipelines</strong>, storing them in <strong>Azure Container Registry (ACR)</strong>.</p><p>This setup lays the foundation for a <strong>GitOps-based continuous deployment workflow</strong>, where <strong>ArgoCD</strong> automatically deploys application changes to <strong>Azure Kubernetes Service (AKS)</strong> by tracking updates in the Git repository.</p><p>In this first part, we focus on:</p><ul><li>“Importing a GitHub repository into Azure DevOps”</li><li>“Setting up a self-hosted agent”</li><li>“Building and pushing Docker images to ACR using Azure Pipelines”</li></ul><p>In the next article, we will extend this pipeline by provisioning AKS and configuring ArgoCD for continuous deployment.</p><p><strong>Application Architecture</strong></p><p>The application consists of the following components:</p><ul><li><strong>Vote</strong>: Python-based frontend that allows users to vote for cats or dogs</li><li><strong>Redis</strong>: In-memory cache that temporarily stores votes</li><li><strong>Worker</strong>: .NET-based background service that processes votes from Redis and persists them</li><li><strong>Postgres</strong>: Database storing final vote counts</li><li><strong>Result</strong>: Node.js application that displays the voting results</li></ul><p>Below is the high-level application workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*2PFslI9vNFBtOgQBjYkmXw.png" /></figure><p><strong>Step 1: Create an Azure DevOps Organization</strong></p><p>Navigate to the Azure DevOps portal and create a new organization by following the on-screen instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5pj-rxIqae8yaUuwNscAg.png" /></figure><p><strong>Step 2: Create a virtual machine (To be used for agent pool configuration).</strong></p><p>Navigate to Virtual machines and click on ‘Create’ button. Select VM basic configuration with linux image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vz1DeXzIFNSRobPnvN2LrA.png" /></figure><p><strong>Step 3: Create a container registry</strong></p><p>Navigate to Container registries and provide a name &amp; location to your container registry and click on ‘Review + Create’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8ryrWClLoTHuGsVPMreEQ.png" /></figure><p><strong>Step 4 : Create a project (Voting-app) in the new organization created.</strong></p><p>Click on ‘New Project’ and provide a project name and description and press on ‘Create’ button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPWoFGhtsXdum04jlb0h9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OplwQN6_HXcQfy252YvBQ.png" /></figure><p><strong>Step 5: Import the Docker GitHub project repository into Azure DevOps Repos.</strong></p><p>Click on import button and provide Docker voter app https url <a href="https://github.com/dockersamples/example-voting-app.git">https://github.com/dockersamples/example-voting-app.git</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2QQJ1tBo4R_RXaASB2Dqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6hKWxjVJIyJRcdvvGXA0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9f0YkNIANNbFP345rZ2biQ.png" /></figure><p><strong>Step 6 Create an agent pool</strong></p><p>We will create pipelines to build application images and push them to Azure Container Registry.</p><p>For this we will require to configure our VM as agent pool. Azure DevOps will execute pipeline jobs on the virtual machine configured as part of the self-hosted agent pool.</p><p>Go to project settings and create an agent pool</p><p>Project Settings →Pipelines →Agent pools →Add pool -&gt;Self Hosted</p><p>Click on ‘Add pool’ button and select ‘Self Hosted’ option</p><p>Give a name of the agent pool and press ‘Create’ button.</p><p>This will create an agent pool. Now we have to add our VM (Step 2) to the the agent pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0neAL0lUtFUOu1xSPlfqDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plLbvQszUsG4t6SvDV8I3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxhCh9L_hmr8HpGs4aPPQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WM5ja6sE9wpv0MAPHs-5Ow.png" /></figure><p><strong>Step 7 Configure agent for the agent pool.</strong></p><p>Click on the agent pool name ‘azurecicdagentpool’, Click on ‘New agent button ‘ on upper right corner of the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4mQfaxUmQ6Hf8UkoQZaEQ.png" /></figure><p>This will open a pop up window with download button for downloading the agent binary and platform wise instruction to configure the agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEgQKh6zccQT7LQr7boTrg.png" /></figure><p>scp the downloaded tar file to the new created VM (Step 2) and extract the contents of the tar file.</p><p>Run config.sh file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXxTm6Q7eo7Jgd2oYXvAnQ.png" /></figure><p>Below inputs will be required for running the config.sh file.</p><ol><li>Server url: <a href="https://dev.azure.com/">https://dev.azure.com</a>/&lt;&lt;organization name&gt;&gt; (Created in step 1)</li><li>Personal Access Token: This needs to be generated from azure console.</li><li>Agentpool →The name of the agent pool created in step 6</li></ol><p>For personal access token please follow the below steps</p><p>Click on your organisation →Click on the ‘user settings’ button and upper right hand corner → Click on ‘Personal access tokens’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NX-b0zsdUWv-3qKK4k3HbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*sxaHb5I201JEDL7R--nwXw.png" /></figure><p>Click on ‘+New Token’ to generate new token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TXb5JEhkGPY2ZusVp82ig.png" /></figure><p>Provide a Name and in Scopes select ‘Full access’ and click on ‘Create’ button</p><p>⚠️ <strong>Note:</strong> For demonstration purposes, the token is created with <em>Full access</em>. For production environments, it is strongly recommended to limit the token scope to the minimum required permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDodiM6bny_cgfVLh5ckMg.png" /></figure><p><strong>Step 8. Run run.sh to bring the agent online</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxMdM6WCCkvpyTp88vkPKA.png" /></figure><p><strong>Step 9. View the agent status</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0fNqcg69szNPh0eMGDsZg.png" /></figure><p><strong>Step 10. Setting up build pipeline</strong></p><p>Navigate to your organisation → Project name →Pipelines. Click on ‘New pipeline’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5u7V8KQab5r7oEFGfnDxdA.png" /></figure><p>Select Azure Repos Git</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wofVdQy7ibzMN4Job8TjjA.png" /></figure><p>Select Azure Repos Git</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wofVdQy7ibzMN4Job8TjjA.png" /></figure><p>Select the GitHub Repo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhJejKP4IuwnfCRm8paMbA.png" /></figure><p>Select Docker 2nd Option I.e Docker (Build and push an image to Azure Container Registry)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14NvMry7pgRMrv9AJ9uDNA.png" /></figure><p>Select the subscription and press ‘Continue button’. You may be asked to login.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o95V9y3HGdn1VyArD4A-YA.png" /></figure><p>Container registry name should be pre populated, select the required container registry where you want to load the images</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Wfp8ykqvCxgeKJkr2kXeA.png" /></figure><p>Below is a pipeline example</p><p>The pipeline is configured with a path-based trigger, so it runs only when changes are made to the vote directory on the main branch. This helps reduce unnecessary pipeline executions and improves build efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-ITu1XO9_eIipZuzwqN0A.png" /></figure><p>Here we have defined ‘Build stage’ to build application image from Dockerfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZbFlGiRyCkgOecYylhT9Q.png" /></figure><p>Here we have defined a Push stage to push the built image to azure registry</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDb0rC6dC1njbD2gE_xdpQ.png" /></figure><p>Click on ‘Run’ to test individual pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ed72_M-3ZxC-GdnEst0l1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rP3dp46ulu86s84HoThqTA.png" /></figure><p>The pipeline updates the registry container with images of Voting-app, result-app and Worker app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3X2ToweaJ6jbSx70Zn0mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cnl5Jo3QdqvewvvFM24kcw.png" /></figure><p>In this article, we successfully migrated an application repository from GitHub to Azure DevOps and built a CI pipeline that:</p><ul><li>Uses a self-hosted Azure DevOps agent</li><li>Builds Docker images using Azure Pipelines</li><li>Pushes images securely to Azure Container Registry</li><li>Prepares the groundwork for GitOps-based deployment using ArgoCD</li></ul><p>In the next article, we will provision an <strong>AKS cluster</strong>, deploy <strong>ArgoCD</strong>, and complete the CI/CD pipeline by enabling automatic deployments based on Git repository changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc1e62b66246" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a full observability stack using Istio on Kubernetes]]></title>
            <link>https://medium.com/@ranjanabhabhattacharya/building-a-full-observability-stack-using-istio-on-kubernetes-af5232fd510d?source=rss-87d60615e8d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/af5232fd510d</guid>
            <dc:creator><![CDATA[Ranjanabha Bhattacharya]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 07:42:22 GMT</pubDate>
            <atom:updated>2025-11-01T07:42:22.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFXtU4wfsYlZjxMdqsYbug.png" /></figure><h3>🚀 Introduction</h3><p>In today’s cloud-native landscape, deploying microservices on Kubernetes is just the beginning. What truly matters is <strong>understanding how those services behave in production</strong> — how they communicate, where latency creeps in, and how system health evolves under real workloads.</p><p>That’s where <strong>observability</strong> comes in — the ability to <strong>monitor, trace, and visualize</strong> what’s happening inside your system.</p><p>In this guide, we’ll build a <strong>complete observability stack on AWS EKS using Istio</strong>, integrating industry-standard tools like:</p><ul><li><strong>Prometheus</strong> and <strong>Grafana</strong> for metrics and visualization</li><li><strong>Loki</strong> and <strong>Promtail</strong> for centralized log aggregation</li><li><strong>Jaeger</strong> for distributed tracing</li><li><strong>Kiali</strong> for real-time mesh visualization and traffic insights</li></ul><p>We’ll deploy Istio’s <strong>Bookinfo</strong> sample application, expose it via an Istio Gateway, and then connect all observability components to see the entire system in action.</p><p>By the end, you’ll have a fully instrumented Kubernetes environment — one that not only runs microservices but helps you <strong>understand</strong> and <strong>improve</strong> them with data-driven insights.</p><p>Whether you’re a Kubernetes enthusiast, a DevOps engineer, or just curious about observability, this guide will help you bridge the gap between deploying microservices and truly understanding them.</p><p>1️⃣ <strong>Setting up the EKS Cluster</strong></p><p>To start with the demo we will require a kubernetes cluster. In todays demo we will create a EKS cluster using eksctl command</p><pre>eksctl create cluster \<br>  --name private-cluster \<br>  --region eu-west-2 \<br>  --version 1.30 \<br>  --nodes 2 \<br>  --node-type t3.medium \<br>  --with-oidc \<br>  --ssh-access \<br>  --ssh-public-key Jenkins \<br>  --managed</pre><p>We will require to install EBS CSI driver as will be saving microservices logs in EBS</p><pre>eksctl create addon \<br>  --name aws-ebs-csi-driver \<br>  --cluster private-cluster \<br>  --service-account-role-arn arn:aws:iam::&lt;&lt;Your-Account-ID&gt;&gt;:role/AmazonEKS_EBS_CSI_DriverRole \<br>  --force</pre><p>Create a Kubernetes service account that maps to an IAM role, allowing the EBS CSI driver to securely manage EBS volumes</p><pre>eksctl create iamserviceaccount \<br>  --name ebs-csi-controller-sa \<br>  --namespace kube-system \<br>  --cluster private-cluster \<br>  --region eu-west-2 \<br>  --role-name AmazonEBSCSIDriverRole \<br>  --attach-policy-arn arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy \<br>  --approve<br>  --override-existing-serviceaccounts</pre><p>2️⃣ <strong>Installing Istio</strong></p><p>After EKS cluster is ready we will proceed to install Istio</p><pre>curl -L https://istio.io/downloadIstio | sh -<br>cd istio-*<br>export PATH=$PWD/bin:$PATH<br>istioctl install --set profile=demo -y</pre><p>This will download the istio folder, cd into the folder and install istio in demo profile.</p><p>We will be using shipped example of bookinfo supplied with istio installable to deploy bookinfo website.</p><p>Below image shows end-to-end architecture of bookinfo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhfBE44uAsVN6C_O3tRsxg.png" /></figure><p>3️⃣<strong> Deploying the Bookinfo App</strong></p><ol><li>Inject istio in default namespace</li></ol><pre>kubectl label namespace default istio-injection=enabled</pre><p>2. Deploy the book info app</p><pre>kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml</pre><p>3. Kubernetes pods, deployment and services deployed after step 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKgIbCKMt_9H-w3_Fo6Ofg.png" /></figure><p>4. Install istio gateway services to create load balancer service to let the application via the load balancer url</p><pre>kubectl apply -f samples/bookinfo/networking/bookinfo-gateway.yaml</pre><p>Get the load balancer url</p><pre>kubectl get gateway</pre><p>Access the url page. Notice the /productpage to view the book-info product page. Refresh the page multiple times and notice book review page changing this is because by default istio service gateway load balances user requests between review v1,v2 and v3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ah6pTY44hrvapu5uk8adDQ.png" /></figure><p>4️⃣<strong> Building the Observability Stack</strong></p><p>Istio supports multiple observability stack.</p><p>We will deploy observability stack Prometheus, Grafana, Kiali, Jaegar and Loki.</p><p>We will run the shipped observability stack that comes with Istio installer</p><pre>kubectl apply -f samples/addons/kiali.yaml<br><br>kubectl apply -f samples/addons/prometheus.yaml<br><br>kubectl apply -f samples/addons/grafana.yaml<br><br>kubectl apply -f samples/addons/jaeger.yaml<br><br>kubectl apply -f samples/addons/loki.yaml</pre><p>Check for observability pods</p><pre>kubectl get pods -n istio-system -w</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tb72hzy6DPuT9xfH2kRucQ.png" /></figure><p>5️⃣ <strong>Exploring Dashboards</strong></p><p><strong>Checking Kiali</strong> — Understand service dependencies and traffic flow in your mesh.</p><p>Kiali is an observability console for <strong>Istio service mesh</strong> that provides <strong>visibility into microservices interactions</strong>. It helps monitor <strong>service health, traffic flow, and metrics</strong>, and provides <strong>graphical representations</strong> of the mesh. Kiali also integrates <strong>tracing and telemetry</strong>, making it easier to <strong>debug issues and understand dependencies</strong>. Additionally, it supports <strong>policy and configuration validation</strong>, helping ensure the service mesh is correctly configured.</p><p>To view Kiali dashboard</p><pre>istioctl dashboard kiali</pre><p>This will show Kiali dashboard locally</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0kQHPh1QH6tiNcGOiZHHA.png" /></figure><p>Applications installed in your EKS cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGnW_QNOsdFvKz3NxWyfgg.png" /></figure><p>Workloads running in your EKS cluster (AKA Deployment,StatefulSets)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Un6IFoJUlRjKwno11N6fQ.png" /></figure><p>Services running in your EKS cluster (AKA Services)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MU9k1pDBxyG_uuSf-5ssXA.png" /><figcaption>x§</figcaption></figure><p>Istio Configs (VirtualServices, Gateway)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-qB1xB7IBd3Q0eCZyeQSg.png" /></figure><p>Istio Mesh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwfKjYN2SdlYbQQpnpivAA.png" /></figure><p><strong>Exploring Grafana dashboards with Prometheus as back end</strong> — Collect and visualize application and mesh-level metrics.</p><p>To view grafana dashboard use the below command</p><pre>istioctl dashboard grafana</pre><p>This will open the Grafana dashboard locally with couple of Istio Dashboards installed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqrUpXOJo1SwGCi-KICv8Q.png" /></figure><p>Few dashboards screenshots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nW_3bDT-HhfIMUZ6u_cKcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MFwCVl58H2dhRCNI5g5QA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEKAMx1KyJ9narEwiIoiGQ.png" /></figure><p><strong>Exploring Loki — </strong>Centralized, label-based logging system optimized for Kubernetes.</p><p>By default Loki configuration does not ships with EBS support</p><p>Path pvc loki storage to support AWS GP2 EBS</p><pre>kubectl patch pvc storage-loki-0 -n istio-system \<br>  -p &#39;{&quot;spec&quot;:{&quot;storageClassName&quot;:&quot;gp2&quot;}}&#39;</pre><p>Restart loki pods</p><pre>kubectl delete pod loki-0 -n istio-system</pre><p>Install promtail on node servers so that logs are shipped to Loki and we have centralized log aggregation system</p><pre>helm install promtail grafana/promtail -n istio-system \<br>  --set &quot;loki.serviceName=loki&quot; \<br>  --set &quot;loki.servicePort=3100&quot; \<br>  --set &quot;config.clients[0].url=http://loki.istio-system.svc.cluster.local:3100/loki/api/v1/push&quot;</pre><p>The command will install promtail and push container logs to Loki.</p><p>You can visualize container logs in Grafana</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myjvvyNa2rHtJ4_8yz7hIA.png" /></figure><p><strong>Exploring Jaegar- </strong>Trace requests across microservices for debugging and latency analysis.</p><p>Had Jaeger running by install istiod with tracing enabled with 100% request sampling rate and enable default tracing utilty zipkin to send traces to Jaeger.</p><pre>istioctl install -y \<br>--set profile=demo \<br>--set meshConfig.enableTracing=true \<br>--set meshConfig.defaultConfig.tracing.sampling=100 \<br>--set meshConfig.defaultConfig.tracing.zipkin.address=jaeger-collector.istio-system.svc.cluster.local:9411</pre><p>Restart all the deployments</p><pre>kubectl rollout restart deployment -n default</pre><p>Run the below command to start Jaeger locally</p><pre>istioctl dashboard jaeger</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtYuXJFfjCmsOUBkvownfA.png" /></figure><p>You can open, compare individual traces to view performance of each microservices for a given request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BJIeH73KJF9riaqrW-NRw.png" /></figure><p>🧩 Conclusion</p><p>We started by provisioning an EKS cluster using eksctl, then installed <strong>Istio</strong> as our service mesh foundation. Using the <strong>Bookinfo</strong> demo app, we explored how traffic flows between services and how Istio helps us manage it.</p><p>Next, we layered in observability — from <strong>Prometheus and Grafana</strong> for metrics, to <strong>Loki and Promtail</strong> for logs, to <strong>Jaeger</strong> for request tracing, and <strong>Kiali</strong> for intuitive mesh visualization. Each of these tools complements the others, giving you a <strong>360° view</strong> of your application’s health and performance.</p><p>This setup forms a <strong>production-grade observability foundation</strong> — ready for enhancements like <strong>mTLS security</strong>, <strong>canary and blue-green deployments</strong>, and <strong>GitOps automation</strong> with <strong>Argo CD</strong>.</p><p>If you’re building microservices on Kubernetes, mastering observability isn’t optional — it’s your best defense against blind spots in distributed systems. With Istio, it becomes not just possible, but elegant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af5232fd510d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>