<?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 Ivan Viliamov on Medium]]></title>
        <description><![CDATA[Stories by Ivan Viliamov on Medium]]></description>
        <link>https://medium.com/@vilyamm?source=rss-58576fd8cf29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nWnsHkkU9q3x_i5J</url>
            <title>Stories by Ivan Viliamov on Medium</title>
            <link>https://medium.com/@vilyamm?source=rss-58576fd8cf29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:58:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vilyamm/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[Epic Migration Battle Report: Taming a Legacy PHP Server on Google Cloud]]></title>
            <link>https://medium.com/@vilyamm/epic-migration-battle-report-taming-a-legacy-php-server-on-google-cloud-0f1fed18e361?source=rss-58576fd8cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f1fed18e361</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Ivan Viliamov]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 04:11:06 GMT</pubDate>
            <atom:updated>2025-10-07T04:15:52.320Z</atom:updated>
            <content:encoded><![CDATA[<p>Want a fucked-up story about how a Data Engineer became a DevOps engineer? Then here you go.</p><p>We’ve all been there. You inherit a server. It’s important, it’s been running for years, and nobody <em>really</em> wants to touch it. Ours was a classic: a single Google Compute Engine VM running Ubuntu 16.04, a vintage PHP 8.0, and an old version of Nginx with public IP address.</p><p>It was slow, showing its age, and the CPU spikes were getting legendary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvSyKdxjXVz_XmsINiM_Yg.png" /></figure><p>The mission: migrate to a modern, performant, and stable environment.</p><p>Now, my background is in Data Engineering, and tangentially Solution Architecture and DevOps. I can orchestrate clouds and build CI/CD pipelines not because it’s my passion, but a modern data engineer should be a Swiss army knife. But PHP? Let’s just say it’s not my native language. So for this adventure, I teamed up with an AI assistant to be my guide and sounding board. This is the story of our journey — the failures, the “aha!” moments, and the final victory.</p><h3>Attempt #0: Rapid Resuscitation</h3><p>It’s obvious but first movement was to move Redis and MySQL 5 to separate GCP services. Server contained itself all services on the board, so I didn’t even know if 100% of CPU usage was even race for resources or real php overload — “top” command showed crazy round robin of cpu usage. <br>Migration of DB was boring and usual, Redis too. <br>Also I’ve installed OpsAgent to see at minimum something because such old linux VM just showed only CPU load in monitoring and zero logs.<br>As a result, first success! We’ve seen much lover usage of CPU, but still with high peaks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtJSVo51LPXcYXSGk-LCpQ.png" /><figcaption>CPU usage with moving MySQL and Redis out of server. Vertical lines means VM restart</figcaption></figure><p>Finding best Redis cache size was heuristic approach with few days monitoring</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azZ5lWq7RjbRoXd2We7kug.png" /></figure><p>The fire was successfully extinguished. But we still can’t use latest version of plugins, there was a lot of warning and errors on the logs, service didn’t felt as healthy. So we decided to move next</p><h3>Attempt #1: The “Blueprint and Rebuild” Fallacy</h3><p>My first thought was the clean, logical one: let’s build a perfect new server from scratch. The plan “Blueprint and Rebuild” was simple. We’d cherry-pick the important configs from the old server — Nginx virtual hosts, the PHP-FPM pool, cron jobs — and deploy them onto a fresh Ubuntu 24.04 instance. We’d refactor on the fly, cleaning up as we went.</p><p>It was a beautiful plan. And it failed spectacularly.</p><p>The problem wasn’t the plan; it was history. This server had seen years of development. I quickly discovered that the “important stuff” was… well, <em>everything</em>. There were critical cron jobs running under three different user accounts, there were obscure scripts in different home directories, we were dealing with the ghosts of developers past, and our neat blueprint couldn’t account for the chaotic, living history of the machine.</p><p><strong>Lesson Learned:</strong> You can’t manually blueprint a server that’s been a core part of your business for years. The “noise” is part of the system.</p><h3>Attempt #2: The All-Seeing Script That Wasn’t</h3><p>Okay, manual cherry-picking is out. “Let’s automate the blueprinting,” I said. I devised a clever rsync-based script to copy the <em>entire</em> web root, every Nginx config, every cron file, every user manifest and permissions. We would create a perfect snapshot of the “working condition” of the old server and deploy it to the new one.</p><p>This also failed, but for a much more subtle reason.</p><p>The script worked perfectly. It copied everything. But we were trying to paste the configuration of a 2016-era car onto the chassis of a 2024 model. System dependencies had changed. Library paths were different. The configuration files we copied were expecting an Ubuntu 16.04 foundation, and they were landing on a clean Ubuntu 24.04. It was a recipe for conflict.<br>But most important part is that failes because a lot of hard dependencies for SSL certificates, passwords and some other tiny stuff and s..t arounf web root that was not covered by manual rsync, and couldn’t be.</p><p><strong>Lesson Learned:</strong> A server’s configuration is not just its text files. It’s the entire ecosystem of installed packages and system libraries that those files depend on.</p><h3>Attempt #3: The “Clone, Upgrade, Stabilize” Doctrine</h3><p>This was the “aha!” moment. We had been trying to build a new house and move the old furniture in. The real solution was to move the <em>entire house</em> and then renovate it, room by room.</p><p><strong>Step 1: The Perfect Clone</strong><br>Using the Google Cloud CLI, we took a snapshot of the old VM’s entire disk and created a new, identical VM from it. No files missed. No cron jobs forgotten. SSL certs, FTP users, every custom script — everything came along for the ride.</p><p><strong>Step 2: The Upgrade </strong><br>This is where the real battle began. We started the official do-release-upgrade process on our cloned server. I learned that you can’t jump from Ubuntu 16.04 to 24.04 directly. You have to go in hops: 16.04 → 18.04 → 20.04 → 22.04 → 24.04. Each step was an adventure in itself.</p><p><strong>Step 3: The Stabilization Battle</strong><br>The upgrade process was successful, but it left a battlefield of broken dependencies in its wake. This is where having an AI to quickly analyze error logs was invaluable. We fought, and won, several boss battles:</p><ul><li><strong>Google’s Own Package Conflicts:</strong> We had to surgically force-overwrite some of Google’s own old packages to get the upgrade started.</li><li><strong>The “ESM Wall”:</strong> The upgrader would halt, complaining about pending security updates that required a paid “ESM” subscription. The solution was to find and temporarily disable the repository that was telling apt about these updates, allowing the upgrader to proceed.</li><li><strong>The Final Boss of Dependency Hell:</strong> After all that, a single library, libargon2, brought the system to a halt. The deb.sury.org PPA (for PHP) and the official Ubuntu repositories were fighting over this one package. With LLM’s help, we used a technique called “APT Pinning” to explicitly command the package manager which version to use.</li></ul><p>After the battles, I hardened the server, purging the “zombie” MySQL, Apache2, memcached and a lot of other services that was running but unused (I’ve analysed network port usage on old server), and removing the old packages that had been pulled in during the upgrade.</p><h4>The Final Ascent: The PHP 8.3 Mirage</h4><p>With a stable Ubuntu 24.04 server, it was time for the final goal: upgrading PHP. We chose PHP 8.3, installed it, and immediately the site went down with a 502 Bad Gateway. The logs were grim, revealing something much deeper than a simple script error: segfaults. This wasn’t a WordPress error; this was the PHP engine itself crashing.</p><p>This was our “whack-a-mole” phase.</p><ul><li>We’d see a TypeError from the Yoast SEO plugin and disable it.</li><li>A new Fatal Error would pop up from Gravity Forms.</li><li>Then WordPress Popular Posts would fail.</li></ul><p>I was getting frustrated, telling my AI guide, “it was working yesterday!” And that was the clue that we were on the wrong track. My assistant suggested disabling key PHP extensions one by one, a standard procedure for this kind of crash. We disabled xdebug, memcache, apcu.. The crashes continued.</p><p>The final, definitive diagnosis came from the kernel logs (dmesg): the crash was happening inside <strong>opcache.so</strong>, PHP’s own caching engine. We were certain we had found the culprit. We tried to force Opcache into a “safe mode” by disabling its JIT compiler, a common fix for this kind of instability.</p><p>It didn’t help. The segfaults continued. I were going in circles.</p><h3>The Realization: The Contradiction is the Answer</h3><p>This is where the entire investigation pivoted. I decided to check the versions of PHP installed on the machine, and I found the final, critical piece of the puzzle. The output was contradictory and revealed everything.</p><pre>$ php8.4 --version<br>PHP 8.4.13 (cli) ...<br>with Zend OPcache v8.4.13, Copyright (c), by Zend Technologies<br><br>$ php8.3 --version<br>PHP 8.3.26 (cli) ...<br>with Xdebug v3.4.5, Copyright (c) 2002-2025, by Derick Rethans</pre><p>The difference was glaring. The PHP 8.4 installation, which apt had pulled in automatically, was complete and reported that it was running <strong>with Zend OPcache</strong>. The PHP 8.3 installation, the one we were trying to run, was <strong>missing that line entirely</strong>.</p><p>This was the “aha!” moment. The segfaults were happening in opcache.so, yet the PHP 8.3 installation we were trying to debug didn’t even have Opcache properly loaded or installed. The entire PHP 8.3 installation from the PPA was fundamentally broken or incomplete on my specific, multi-upgraded server environment. For sure, manual or apt re-installation didn’t helped.<br>We were chasing a ghost.</p><h3>The Pivot: A Data-Driven Decision to Upgrade</h3><p>The path forward was suddenly crystal clear. Why continue to fight to repair a demonstrably broken PHP 8.3 installation when a complete, newer PHP 8.4 installation was already on the machine?</p><p>This wasn’t a leap of faith; it was a logical, data-driven decision. We chose the version that was intact.</p><p>We created a reusable script to automate the process of switching all the server’s configurations — Nginx, PHP-FPM pools, cron jobs, and system alternatives — from one version to another. We ran the script to point everything explicitly to PHP 8.4.</p><pre>#!/bin/bash<br>#<br># ==============================================================================<br># PHP Version Switcher Script<br># ==============================================================================<br># This script automates the process of switching the server&#39;s configuration<br># from one PHP version to another.<br>#<br># Usage: sudo bash ./switch_php_version.sh &lt;OLD_VERSION&gt; &lt;NEW_VERSION&gt;<br># Example: sudo bash ./switch_php_version.sh 8.3 8.4<br># ==============================================================================<br><br>set -e<br><br>OLD_VERSION=$1<br>NEW_VERSION=$2<br><br>if [ -z &quot;$OLD_VERSION&quot; ] || [ -z &quot;$NEW_VERSION&quot; ]; then<br>    echo &quot;ERROR: You must provide both an old and a new version.&quot;<br>    echo &quot;Usage: sudo bash $0 &lt;OLD_VERSION&gt; &lt;NEW_VERSION&gt;&quot;<br>    echo &quot;Example: sudo bash $0 8.3 8.4&quot;<br>    exit 1<br>fi<br><br>echo &quot;### Switching configurations from PHP ${OLD_VERSION} to ${NEW_VERSION}...&quot;<br><br># 1. Update Nginx Configurations<br>echo &quot;--&gt; Updating Nginx site configurations...&quot;<br>sudo find /etc/nginx/sites-available/ -type f -exec sudo sed -i &quot;s/${OLD_VERSION}.sock/${NEW_VERSION}.sock/g&quot; {} +<br>echo &quot;--&gt; Nginx updated.&quot;<br><br># 2. Update PHP-FPM Pools<br>echo &quot;--&gt; Migrating PHP-FPM pools...&quot;<br>for pool in /etc/php/${OLD_VERSION}/fpm/pool.d/*.conf; do<br>    filename=$(basename &quot;$pool&quot;)<br>    # Ensure the new directory exists<br>    sudo mkdir -p /etc/php/${NEW_VERSION}/fpm/pool.d/<br>    # Copy and update the pool file<br>    sudo cp &quot;$pool&quot; &quot;/etc/php/${NEW_VERSION}/fpm/pool.d/${filename}&quot;<br>    sudo sed -i &quot;s/${OLD_VERSION}.sock/${NEW_VERSION}.sock/g&quot; &quot;/etc/php/${NEW_VERSION}/fpm/pool.d/${filename}&quot;<br>done<br>echo &quot;--&gt; FPM pools migrated.&quot;<br><br># 3. Update System Default PHP CLI<br>echo &quot;--&gt; Setting system default PHP to ${NEW_VERSION}...&quot;<br>sudo update-alternatives --set php /usr/bin/php${NEW_VERSION}<br>echo &quot;--&gt; System default updated.&quot;<br><br># 4. Update Cron Jobs<br>echo &quot;--&gt; Updating all cron jobs...&quot;<br>sudo find /var/spool/cron/crontabs/ -type f -exec sudo sed -i &quot;s/php${OLD_VERSION}/php${NEW_VERSION}/g&quot; {} +<br>sudo find /etc/cron.d/ -type f -exec sudo sed -i &quot;s/php${OLD_VERSION}/php${NEW_VERSION}/g&quot; {} +<br>echo &quot;--&gt; Cron jobs updated.&quot;<br><br>echo &quot;&quot;<br>echo &quot;### Configuration switch complete!&quot;<br>echo &quot;Please review the changes and restart the services.&quot;</pre><p>Then we purged everything else. All php8.3, php8.0, and any other phantom PHP packages were completely removed from the system, leaving a single, clean, consistent PHP 8.4 environment.</p><p>After a final restart of the services, we held our breath and refreshed the browser.</p><p>It worked.</p><h3>The Canary Release: A Safe Landing</h3><p>With a fully functional, albeit bleeding-edge, new server, the final step was to introduce it to live traffic. We created a new instance group for our instance-2 server and used the Google Cloud Load Balancer’s “capacity scaler” to perform a canary release. We sent just 2% of live traffic to the new machine, monitoring the logs and performance closely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CiN3o_UB010is0vaTSMfiQ.png" /></figure><p>For sure, there will be a lot more steps: Upgrade MySQL, remove SSL from server because now it’s managed by GCP Load Balancer, and others, bringing last 10 years of progress, but it will be usual routine if I compare it with current story.</p><p>But when I’ll pack PHP to the Serverless Dockers with autoscaling — I guess it will be another long blog post :)</p><h3>Conclusion</h3><p>The journey was a marathon of debugging. But we went from a fragile, legacy server to a modern, hardened, observable, and performant one. The key lessons were profound:</p><ol><li>For a server with history: <strong>clone, don’t rebuild.</strong> A disk snapshot is the only way to guarantee perfect fidelity.</li><li><strong>Verify the integrity of your core components.</strong> Our biggest mistake was assuming a package installation was complete and correct. Comparing the php — version output for both versions revealed the fundamental flaw.</li><li><strong>Trust your logs, especially the kernel.</strong> dmesg told us the truth (segfault in opcache.so) from the beginning, even when it seemed contradictory. The contradiction itself was the final clue.</li><li><strong>Collaborating with an AI is a force multiplier.</strong> Even when it was wrong, it provided a logical path, analyzed logs in seconds, and gave me the commands to test its hypotheses. The dialogue was the tool that ultimately led to the solution.</li><li>And the last, most important: even <strong>Data Engineer can</strong> take and <strong>solve</strong> real hard <strong>DevOps</strong> Linux problems <strong>with LLMs help</strong>. Key point is that <strong>Engineer is the problem solver</strong>, not LLM itself.</li></ol><p>It was a tough fight, but the new server is now handling traffic like a champ. And I, a Data Engineer who started this journey not knowing the first thing about PHP’s internals, now have a deep respect for the complexities of its environment and a battle-tested playbook for the next migration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f1fed18e361" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Publish Your Cloud Run Service on Cloudflare Using a Static IP]]></title>
            <link>https://medium.com/@vilyamm/how-to-publish-your-cloud-run-service-on-cloudflare-using-a-static-ip-497f52e78f91?source=rss-58576fd8cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/497f52e78f91</guid>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Ivan Viliamov]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 01:34:34 GMT</pubDate>
            <atom:updated>2025-04-07T09:51:54.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ffrSXCx8bRGDbhiL91xSA.jpeg" /></figure><p>In this article, we’ll walk through creating a Google Cloud Load Balancer for your Cloud Run service that provides a static IP address — making it seamlessly publishable to Cloudflare. Whether you’re a seasoned developer or just starting out, this guide will show you how to connect your Cloud Run service with Cloudflare effortlessly.</p><figure><img alt="schematic flow how CloudFlare DNS can access CloudRun" src="https://cdn-images-1.medium.com/max/1024/1*_GqiP8pMI9_64fNEr31NXg.png" /></figure><h4><strong>Step 1: Reserve a Static Global IP Address</strong></h4><p>Create a fixed global IP address that will serve as the entry point for your service. This static IP is essential when pointing your Cloudflare DNS records to your service.</p><p><em>Here and bellow I’ll give you 2 alternatives for </em><strong><em>terraform</em></strong><em> and </em><strong><em>gcloud. </em></strong><em>You should choose only one instrument</em></p><pre>### terraform<br><br>resource &quot;google_compute_global_address&quot; &quot;frontend_lb_ip&quot; {<br>  project = var.project_id<br>  name    = &quot;frontend-lb-ip&quot;<br>}</pre><pre>### gcloud<br><br>gcloud compute addresses create frontend-lb-ip --global --project [PROJECT_ID]</pre><h4><strong>Step 2: Set Up a Network Endpoint Group for Cloud Run</strong></h4><p><strong>Why You Need It: </strong>Cloud Run services are serverless and require a special endpoint group to let the load balancer know where to route incoming traffic.<br><strong>What It Does: </strong>A Network Endpoint Group (NEG) of type SERVERLESS connects your Cloud Run service to the load balancer.</p><pre>### terraform<br><br>resource &quot;google_compute_region_network_endpoint_group&quot; &quot;frontend_neg&quot; {<br>  project               = var.project_id<br>  name                  = &quot;frontend-neg&quot;<br>  description           = &quot;Frontend Network Endpoint Group for Cloud Run&quot;<br>  network_endpoint_type = &quot;SERVERLESS&quot;<br>  region                = var.region<br><br>  cloud_run {<br>    service = google_cloud_run_v2_service.frontend.name<br>  }<br>}</pre><pre>### gcloud<br><br>gcloud compute network-endpoint-groups create frontend-neg \<br>  --region=[REGION] \<br>  --network-endpoint-type=SERVERLESS \<br>  --cloud-run-service=[CLOUD_RUN_SERVICE] \<br>  --project=[PROJECT_ID]</pre><h4><strong>Step 3: Configure the Backend Service</strong></h4><p><strong>Why You Need It: </strong>The backend service tells the load balancer where to send incoming requests. It bundles your NEGs and defines load balancing behavior.<br><strong>What It Does: </strong>This resource routes traffic from the load balancer to your Cloud Run NEG.</p><pre>### terraform<br><br>resource &quot;google_compute_backend_service&quot; &quot;frontend_backend&quot; {<br>  project               = var.project_id<br>  name                  = &quot;frontend-backend&quot;<br>  description           = &quot;Frontend Backend Service for Cloud Run&quot;<br>  protocol              = &quot;HTTP&quot;<br>  load_balancing_scheme = &quot;EXTERNAL&quot;<br><br>  backend {<br>    group = google_compute_region_network_endpoint_group.frontend_neg.id<br>  }<br>}</pre><pre>### gcloud<br><br>gcloud compute backend-services create frontend-backend \<br>  --global \<br>  --protocol=HTTP \<br>  --load-balancing-scheme=EXTERNAL \<br>  --project=[PROJECT_ID]<br><br>gcloud compute backend-services add-backend frontend-backend \<br>  --global \<br>  --network-endpoint-group=frontend-neg \<br>  --network-endpoint-group-region=[REGION] \<br>  --project=[PROJECT_ID]</pre><h4><strong>Step 4: Create URL Maps for Traffic Routing</strong></h4><p><strong>Why You Need It: </strong>URL maps define how requests are routed based on rules. You can either send traffic directly to your backend or redirect HTTP requests to HTTPS. This flexibility is key when you want to control whether your service forces secure connections or serves HTTP traffic directly.<br><strong>What It Does:<br></strong>• <strong>Standard URL Map:</strong> Routes traffic directly to your backend service.<br>• <strong>Redirect URL Map:</strong> Redirects incoming HTTP requests to HTTPS.<br>• <strong>Conditional Logic:</strong> Using a local variable and two parameters (<strong>https_enabled</strong> and <strong>http_https_redirect</strong>), we decide which URL map to use.</p><pre>### terraform<br><br># Standard URL Map<br>resource &quot;google_compute_url_map&quot; &quot;frontend_url_map&quot; {<br>  project         = var.project_id<br>  name            = &quot;frontend-url-map&quot;<br>  description     = &quot;Routes directly to Cloud Run backend Service&quot;<br>  default_service = google_compute_backend_service.frontend_backend.self_link<br>}<br><br># Redirect URL Map<br>resource &quot;google_compute_url_map&quot; &quot;frontend_redirect_url_map&quot; {<br>  project     = var.project_id<br>  name        = &quot;frontend-redirect-url-map&quot;<br>  description = &quot;Redirects HTTP to HTTPS&quot;<br><br>  default_url_redirect {<br>    https_redirect         = true<br>    redirect_response_code = &quot;MOVED_PERMANENTLY_DEFAULT&quot;<br>    strip_query            = false<br>  }<br>}<br><br># Local Variable for URL Map Selection: <br># Here&#39;s the trick: if both https_enabled and http_https_redirect are true, <br># we use the redirect URL map; <br># otherwise, we use the standard URL map.<br>locals {<br>  http_proxy_url_map_self_link = (var.https_enabled &amp;&amp; var.http_https_redirect) ? google_compute_url_map.frontend_redirect_url_map.self_link : google_compute_url_map.frontend_url_map.self_link<br>}</pre><pre>### gcloud<br><br># Standard URL Map<br>gcloud compute url-maps create frontend-url-map \<br>  --default-service=frontend-backend \<br>  --project=[PROJECT_ID]<br><br># Redirect URL Map<br>gcloud compute url-maps create frontend-redirect-url-map \<br>  --default-url-redirect=&quot;https_redirect=true,redirect_response_code=MOVED_PERMANENTLY_DEFAULT,strip_query=false&quot; \<br>  --project=[PROJECT_ID]<br><br># Note: <br># The local conditional logic is handled within Terraform; <br># with gcloud, you would manually choose the appropriate URL map <br># based on your deployment requirements.</pre><h4><strong>Step 5: Configure the HTTP Proxy and Global Forwarding Rule</strong></h4><p><strong>Why You Need It: </strong>The HTTP proxy receives traffic on port 80 and directs it using the URL map selected above. The forwarding rule binds the static IP to port 80 and connects it to the HTTP proxy.<br><strong>What It Does:<br></strong>• <strong>HTTP Proxy:</strong> Uses the conditional URL map (redirect vs. direct routing).<br>• <strong>HTTP Forwarding Rule:</strong> Listens on port 80 and sends traffic to the HTTP proxy.</p><pre>### terraform<br><br># HTTP Proxy<br>resource &quot;google_compute_target_http_proxy&quot; &quot;frontend_http_proxy&quot; {<br>  project     = var.project_id<br>  name        = &quot;frontend-http-proxy&quot;<br>  description = &quot;Routes HTTP traffic based on your redirection settings&quot;<br>  url_map     = local.http_proxy_url_map_self_link<br>}<br><br># HTTP Forwarding Rule<br>resource &quot;google_compute_global_forwarding_rule&quot; &quot;frontend_http_forwarding_rule&quot; {<br>  project     = var.project_id<br>  name        = &quot;frontend-http-forwarding-rule&quot;<br>  description = &quot;Forwards HTTP traffic from static IP to HTTP proxy&quot;<br>  ip_address  = google_compute_global_address.frontend_lb_ip.address<br>  port_range  = &quot;80&quot;<br>  target      = google_compute_target_http_proxy.frontend_http_proxy.self_link<br>}</pre><pre>### gcloud<br><br># Note.<br># Replace [URL_MAP] with either <br># frontend-redirect-url-map or frontend-url-map <br># based on your parameters.<br># HTTP Proxy<br>gcloud compute target-http-proxies create frontend-http-proxy \<br>  --url-map=[URL_MAP] \<br>  --project=[PROJECT_ID]<br><br># HTTP Forwarding Rule<br>gcloud compute forwarding-rules create frontend-http-forwarding-rule \<br>  --global \<br>  --target-http-proxy=frontend-http-proxy \<br>  --ports=80 \<br>  --address=[STATIC_IP] \<br>  --project=[PROJECT_ID]</pre><h4><strong>Step 6: Set Up HTTPS for Secure Traffic (Optional)</strong></h4><p><strong>Why You Need It: </strong>If you choose to enable HTTPS, you must configure an SSL certificate, an HTTPS proxy, and a forwarding rule on port 443. This ensures that secure traffic is handled appropriately and that your service can leverage Cloudflare’s secure connectivity.<br><strong>What It Does:<br></strong>• <strong>Managed SSL Certificate:</strong> Automatically provisions an SSL certificate for your domain.<br>• <strong>HTTPS Proxy:</strong> Routes HTTPS traffic to your backend using the standard URL map (without redirection).<br>• <strong>HTTPS Forwarding Rule:</strong> Binds port 443 of your static IP to the HTTPS proxy.</p><pre>### terraform<br><br># Managed SSL Certificate<br>resource &quot;google_compute_managed_ssl_certificate&quot; &quot;frontend_cert&quot; {<br>  project = var.project_id<br>  name    = &quot;frontend-cert&quot;<br><br>  managed {<br>    domains = var.ssl_domains # array<br>  }<br>}<br><br># HTTPS Proxy (conditionally created)<br>resource &quot;google_compute_target_https_proxy&quot; &quot;frontend_https_proxy&quot; {<br>  count           = var.enable_https ? 1 : 0<br>  project         = var.project_id<br>  name            = &quot;frontend-https-proxy&quot;<br>  description     = &quot;Routes HTTPS traffic to Cloud Run&quot;<br>  url_map         = google_compute_url_map.frontend_url_map.self_link<br>  ssl_certificates = [google_compute_managed_ssl_certificate.frontend_cert.self_link]<br>}<br><br># HTTPS Forwarding Rule (conditionally created)<br>resource &quot;google_compute_global_forwarding_rule&quot; &quot;frontend_https_forwarding_rule&quot; {<br>  count      = var.load_balancer.enable_https ? 1 : 0<br>  project    = var.project_id<br>  name       = &quot;frontend-https-forwarding-rule&quot;<br>  description= &quot;Forwards HTTPS traffic from static IP to HTTPS proxy&quot;<br>  ip_address = google_compute_global_address.frontend_lb_ip.address<br>  port_range = &quot;443&quot;<br>  target     = google_compute_target_https_proxy.frontend_https_proxy[0].self_link<br>}</pre><pre>### gcloud<br><br># Managed SSL Certificate (Beta Command)<br>gcloud beta compute ssl-certificates create frontend-cert \<br>  --domains=[DOMAIN1,DOMAIN2] \<br>  --global \<br>  --project=[PROJECT_ID]<br><br># HTTPS Proxy<br>gcloud compute target-https-proxies create frontend-https-proxy \<br>  --url-map=frontend-url-map \<br>  --ssl-certificates=frontend-cert \<br>  --project=[PROJECT_ID]<br><br># HTTPS Forwarding Rule<br>gcloud compute forwarding-rules create frontend-https-forwarding-rule \<br>  --global \<br>  --target-https-proxy=frontend-https-proxy \<br>  --ports=443 \<br>  --address=[STATIC_IP] \<br>  --project=[PROJECT_ID]</pre><h4>Bonus. CloudFlare terraform snippet and playing around 525 error with SSLs</h4><pre>resource &quot;cloudflare_dns_record&quot; &quot;application&quot; {<br>  provider = cloudflare<br>  zone_id  = data.cloudflare_zone.application_zone.zone_id<br>  comment  = &quot;application ${var.environment} record&quot;<br>  content  = google_compute_global_address.frontend_lb_ip.address<br>  name     = local.dns_application_url<br>  proxied  = false # tricky part<br>  ttl      = 1<br>  type     = &quot;A&quot;<br>}</pre><p>Here is the tricky part when we need a GCP SSL certificate and HTTPS.<br>You can use <strong>proxied=true</strong> and no need to use GCP SSL! <br>But to do that, you need to change CloudFlare org level settings, because by default CloudFlare required SSL of your website, and it’s not always possible.<br>But! if you enable <strong>proxied=true</strong> and create SSL cert on GCP, it can be always ‘provisioned’ because Cert manager can’t access the resource, because it’s not available under Cloudflare 525/526 error… it’s infinite loop!<br>So, to broke this infinite loop we need:<br>1. create HTTP load balancer without redirection https-&gt;http rule.<br>2. setup this cloudflare_dns_record with <strong>proxied=false</strong><br>3. create SSL Cert using terraform or gcloud and wait until status ‘Active’<br>4. then you can create HTTPS redirection rule and enable <strong>proxied=true</strong></p><h4><strong>Conclusion</strong></h4><p>By following these steps, you now have a flexible setup that:<br>• Provides your Cloud Run service with a static global IP — essential for integrating with Cloudflare.<br>• Uses Terraform to define all infrastructure as code while also offering gcloud CLI alternatives.<br>• Offers dynamic control over HTTP/HTTPS behavior with two parameters:<br>• <strong>https_enabled</strong>: Determines whether HTTPS resources are active.<br>• <strong>http_https_redirect</strong>: When combined with HTTPS being enabled, forces an HTTP-to-HTTPS redirect; otherwise, serves HTTP directly.</p><p>This approach ensures that you can start with a secure (or plain HTTP) configuration and update your settings later without tearing down resources — keeping your SSL certificate intact and your deployment smooth.</p><p>Happy deploying!</p><p><em>experimenting with SEO, if you are human please ignore this </em>💀</p><p><em>Struggling with Cloud Run’s dynamic IPs when trying to integrate with Cloudflare? Curious how to expose your Cloud Run service on Cloudflare while using a fixed global IP? Want a step-by-step guide to set up a load balancer that solves this challenge? Have you ever wondered how to overcome the limitations of dynamic IPs for your Cloud Run service on Cloudflare? This guide provides a clear, actionable roadmap to publish your service reliably, whether you need HTTP-only or a full HTTPS-enabled setup.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=497f52e78f91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Jinja Met Dataflow: A Developer’s Guide to Conditional Templating in Airflow]]></title>
            <link>https://medium.com/@vilyamm/when-jinja-met-dataflow-a-developers-guide-to-conditional-templating-in-airflow-7751a42db2aa?source=rss-58576fd8cf29------2</link>
            <guid isPermaLink="false">https://medium.com/p/7751a42db2aa</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Ivan Viliamov]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 23:32:54 GMT</pubDate>
            <atom:updated>2025-03-05T23:32:54.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*F-0PPQyjPSc2-44MrOPYBw.png" /></figure><p>In this post, I’ll explain how I solved a common problem when launching a Dataflow Flex Template job using Airflow: how to include (or skip) a parameter in the JSON payload only when its value is not null. Along the way, I’ll show you how to use user‑defined macros and filters in Airflow’s Jinja templates.</p><h3><strong>The Problem</strong></h3><p>When using Airflow’s Dataflow operators, you often need to build a JSON payload that is sent to the Dataflow API. Sometimes, you only want to include a parameter if a value is provided. For example, you might want to include the “propertyAsId” key only when a non‑null value exists. If you pass a null value, the API fails.</p><h3><strong>The Approach</strong></h3><p>Since you cannot use Jinja control structures (like {% if %}) directly in Python code, we solve this by:</p><h4>1. <strong>Creating a Helper Function</strong></h4><p>Write a Python function that builds the parameters dictionary. This function uses simple Python logic (with if statements) to include keys only when needed.</p><h4>2. <strong>Registering as a User-Defined Macro</strong></h4><p>Pass this function into Airflow using user_defined_macros so it is available in your Jinja template.</p><h4>3. <strong>Building the Request Body as JSON</strong></h4><p>Use the helper function to build a Python dictionary, convert it to JSON using the tojson filter, and let Airflow convert it back to a dict with native templating enabled.</p><h4>4. <strong>Optionally Adding a Custom Filter</strong></h4><p>If needed, register a custom filter (for example, to convert a JSON string back to a dict).</p><h3><strong>Step-by-Step Code Examples</strong></h3><h4><strong>1. Create a Helper Function for Conditional Parameters</strong></h4><p>The helper function will build the parameters and only add “propertyAsId” if a value is provided.</p><pre>def build_flex_parameters(params, dag_run):<br>    flex_params = {<br>        &quot;inputTableSpec&quot;: (<br>            f&quot;{dag_run.conf.get(&#39;input_project&#39;, params[&#39;input_project&#39;])}:&quot;<br>            f&quot;{dag_run.conf.get(&#39;input_dataset&#39;, params[&#39;input_dataset&#39;])}.&quot;<br>            f&quot;{dag_run.conf.get(&#39;input_table&#39;, params[&#39;input_table&#39;])}&quot;<br>        ),<br>        &quot;outputDeadletterTable&quot;: dag_run.conf.get(&#39;dead_letter_table&#39;, params[&#39;dead_letter_table&#39;]),<br>        &quot;stagingLocation&quot;: dag_run.conf.get(&#39;staging_location&#39;, params[&#39;staging_location&#39;]),<br>        &quot;saveHeapDumpsToGcsPath&quot;: dag_run.conf.get(&#39;error_location&#39;, params[&#39;error_location&#39;]),<br>        &quot;useLegacySql&quot;: dag_run.conf.get(&#39;use_legacy_sql&#39;, params[&#39;use_legacy_sql&#39;]),<br>        &quot;queryLocation&quot;: dag_run.conf.get(&#39;query_location&#39;, params[&#39;query_location&#39;]),<br>        &quot;connectionUrl&quot;: dag_run.conf.get(&#39;es_url&#39;, params[&#39;es_url&#39;]),<br>        &quot;apiKey&quot;: dag_run.conf.get(&#39;es_auth_token&#39;, params[&#39;es_auth_token&#39;]),<br>        &quot;apiKeySource&quot;: dag_run.conf.get(&#39;api_key_source&#39;, params[&#39;api_key_source&#39;]),<br>        &quot;index&quot;: dag_run.conf.get(&#39;es_index&#39;, params[&#39;es_index&#39;]),<br>        &quot;batchSize&quot;: str(dag_run.conf.get(&#39;batch_size&#39;, params[&#39;batch_size&#39;])),<br>        &quot;batchSizeBytes&quot;: str(dag_run.conf.get(&#39;batch_size_bytes&#39;, params[&#39;batch_size_bytes&#39;])),<br>        &quot;maxRetryAttempts&quot;: str(dag_run.conf.get(&#39;max_retry_attempts&#39;, params[&#39;max_retry_attempts&#39;])),<br>        &quot;maxRetryDuration&quot;: str(dag_run.conf.get(&#39;max_retry_duration&#39;, params[&#39;max_retry_duration&#39;])),<br>        &quot;usePartialUpdate&quot;: dag_run.conf.get(&#39;use_partial_update&#39;, params[&#39;use_partial_update&#39;]),<br>        &quot;bulkInsertMethod&quot;: dag_run.conf.get(&#39;bulk_insert_method&#39;, params[&#39;bulk_insert_method&#39;]),<br>        &quot;trustSelfSignedCerts&quot;: dag_run.conf.get(&#39;trust_self_signed_certs&#39;, params[&#39;trust_self_signed_certs&#39;]),<br>        &quot;disableCertificateValidation&quot;: dag_run.conf.get(&#39;disable_certificate_validation&#39;,<br>                                                         params[&#39;disable_certificate_validation&#39;]),<br>        &quot;numberOfWorkerHarnessThreads&quot;: str(dag_run.conf.get(&#39;workers_threads&#39;, params[&#39;workers_threads&#39;])),<br>    }<br>    property_as_id = dag_run.conf.get(&#39;property_as_id&#39;, params[&#39;property_as_id&#39;])<br>    if property_as_id:<br>        flex_params[&quot;propertyAsId&quot;] = property_as_id<br>    return flex_params</pre><h4><strong>2. Create a Function to Build the Complete Request Body</strong></h4><p>This function builds the full payload including job name and environment.</p><pre>def get_body(params, dag_run, ts_nodash):<br>    # Build jobName by replacing underscores with hyphens and lowercasing the timestamp.<br>    job_name = (<br>        &quot;bq-&quot; +<br>        dag_run.conf.get(&quot;input_dataset&quot;, params[&quot;input_dataset&quot;]).replace(&quot;_&quot;, &quot;-&quot;) +<br>        &quot;-&quot; +<br>        dag_run.conf.get(&quot;input_table&quot;, params[&quot;input_table&quot;]).replace(&quot;_&quot;, &quot;-&quot;) +<br>        &quot;-to-es-&quot; +<br>        dag_run.conf.get(&quot;es_index&quot;, params[&quot;es_index&quot;]).replace(&quot;_&quot;, &quot;-&quot;) +<br>        &quot;-&quot; +<br>        ts_nodash.lower()<br>    )<br>    body = {<br>        &quot;launchParameter&quot;: {<br>            &quot;jobName&quot;: job_name,<br>            &quot;containerSpecGcsPath&quot;: dag_run.conf.get(&quot;template&quot;, params[&quot;template&quot;]),<br>            &quot;parameters&quot;: build_flex_parameters(params, dag_run),<br>            &quot;environment&quot;: {<br>                &quot;tempLocation&quot;: dag_run.conf.get(&quot;temp_location&quot;, params[&quot;temp_location&quot;]),<br>                &quot;network&quot;: dag_run.conf.get(&quot;network&quot;, params[&quot;network&quot;]),<br>                &quot;subnetwork&quot;: dag_run.conf.get(&quot;subnetwork&quot;, params[&quot;subnetwork&quot;]),<br>                &quot;numWorkers&quot;: str(dag_run.conf.get(&quot;num_workers&quot;, params[&quot;num_workers&quot;])),<br>                &quot;maxWorkers&quot;: str(dag_run.conf.get(&quot;max_workers&quot;, params[&quot;max_workers&quot;])),<br>                &quot;workerZone&quot;: dag_run.conf.get(&quot;worker_zone&quot;, params[&quot;worker_zone&quot;]),<br>                &quot;serviceAccountEmail&quot;: dag_run.conf.get(&quot;service_account&quot;, params[&quot;service_account&quot;])<br>            }<br>        }<br>    }<br>    return body</pre><h4><strong>3. Register the Functions as User-Defined Macros</strong></h4><pre>with DAG(<br>    &quot;dataflow_flex_template_dag&quot;,<br>    schedule_interval=None,<br>    default_args=default_args,<br>    catchup=False,<br>    params=default_params,<br>    tags=[&quot;gold&quot;, &quot;dataflow&quot;],<br>    user_defined_macros={<br>        &quot;build_flex_parameters&quot;: build_flex_parameters,<br>        &quot;get_body&quot;: get_body,<br>    },<br>    render_template_as_native_obj=True,<br>) as dag:</pre><h4><strong>4. Use the Flex Template Operator</strong></h4><p>Finally, use the DataflowStartFlexTemplateOperator with the body template.</p><pre>from airflow.providers.google.cloud.operators.dataflow import DataflowStartFlexTemplateOperator<br><br>start_dataflow_flex_template_job = DataflowStartFlexTemplateOperator(<br>    task_id=&quot;start_dataflow_flex_template&quot;,<br>    project_id=&quot;{{ dag_run.conf.get(&#39;project&#39;, params.project) }}&quot;,<br>    location=&quot;{{ dag_run.conf.get(&#39;region&#39;, params.region) }}&quot;,<br>    body=&quot;{{ get_body(params, dag_run, ts_nodash) | tojson }}&quot;,<br>    gcp_conn_id=&quot;google_cloud_default&quot;,<br>    deferrable=True,<br>    wait_until_finished=False,<br>    append_job_name=False,<br>    dag=dag,<br>)<br><br>start_dataflow_flex_template_job</pre><h3><strong>Summary</strong></h3><h4>• <strong>Helper Functions:</strong></h4><p>Use Python helper functions (build_flex_parameters and get_body) to build your request payload. These functions can include conditional logic (like skipping “propertyAsId” if its value is null).</p><h4>• <strong>User-Defined Macros:</strong></h4><p>Register your helper functions in the DAG’s user_defined_macros so you can call them in your Jinja templates.</p><h4>• <strong>JSON Conversion:</strong></h4><p>Pipe your function’s output through the tojson filter. With render_template_as_native_obj=True, Airflow will convert the JSON string back to a Python dictionary.</p><h4>• <strong>Copy-Paste Ready:</strong></h4><p>The complete code examples provided here can be copied directly into your Airflow DAG file.</p><p>I hope this guide helps you understand how to conditionally include parameters in your Dataflow Flex Template payload using Airflow’s Jinja templating. Happy coding!</p><blockquote>P.S. as a bonus, my example of default_params</blockquote><pre>default_params = {<br>    # Input source parameters<br>    &quot;input_project&quot;: Param(&quot;my-project&quot;, type=&quot;string&quot;, title=&quot;BQ input project&quot;,<br>                           description=&quot;The BigQuery project to read from&quot;),<br>    &quot;input_dataset&quot;: Param(&quot;my_dataset&quot;, type=&quot;string&quot;, title=&quot;BQ input dataset&quot;,<br>                           description=&quot;The BigQuery dataset to read from&quot;),<br>    &quot;input_table&quot;: Param(&quot;my_table&quot;, type=&quot;string&quot;, title=&quot;BQ input table&quot;,<br>                         description=&quot;The BigQuery table to read from&quot;),<br>    <br>    # Elasticsearch configuration<br>    &quot;es_index&quot;: Param(type=&quot;string&quot;, title=&quot;ES Index&quot;, description=&quot;The Elasticsearch index to write to&quot;,<br>                      examples=[&quot;index-v1&quot;, &quot;index-v2&quot;]),<br>    &quot;es_url&quot;: Param(&quot;http://es.example.com:9200&quot;, type=&quot;string&quot;, title=&quot;ES URL&quot;,<br>                    description=&quot;The Elasticsearch URL&quot;),<br>    &quot;property_as_id&quot;: Param(&quot;id&quot;, type=[&quot;null&quot;, &quot;string&quot;], title=&quot;Property as ID&quot;,<br>                            description=&quot;The property in BQ to use as the ES document ID&quot;),<br><br>    # Dataflow worker configuration, here is a key for performance tuning<br>    &quot;batch_size&quot;: 100,<br>    &quot;batch_size_bytes&quot;: 2097152,<br>    &quot;workers_threads&quot;: Param(5, type=&quot;integer&quot;, minimum=2),<br>    &quot;num_workers&quot;: 1,<br>    &quot;max_workers&quot;: 12,<br><br>    &quot;es_auth_username&quot;: Param(&quot;&quot;, type=[&quot;null&quot;, &quot;string&quot;]),<br>    &quot;es_auth_password&quot;: Param(&quot;&quot;, type=[&quot;null&quot;, &quot;string&quot;]),<br>    &quot;es_auth_token&quot;: &quot;dummy-api-key&quot;,<br>    &quot;api_key_source&quot;: &quot;PLAINTEXT&quot;,<br><br>    # Dataflow project, region, and temp location<br>    &quot;project&quot;: &quot;my-project&quot;,<br>    &quot;region&quot;: &quot;us-central1&quot;,<br>    &quot;temp_location&quot;: &quot;gs://my-project-dataflow-temp-bucket/temp&quot;,<br>    &quot;network&quot;: &quot;https://www.googleapis.com/compute/v1/projects/my-network/global/networks/default&quot;,<br>    &quot;subnetwork&quot;: &quot;https://www.googleapis.com/compute/v1/projects/my-network/regions/us-central1/subnetworks/default&quot;,<br>    &quot;worker_zone&quot;: &quot;us-central1-a&quot;,<br>    &quot;service_account&quot;: &quot;dataflow-worker@my-project.iam.gserviceaccount.com&quot;,<br><br>    &quot;max_retry_attempts&quot;: 5,<br>    &quot;max_retry_duration&quot;: 10000,<br>    &quot;use_partial_update&quot;: Param(&quot;false&quot;, type=&quot;string&quot;, enum=[&quot;true&quot;, &quot;false&quot;]),<br>    &quot;bulk_insert_method&quot;: Param(&quot;INDEX&quot;, type=&quot;string&quot;, enum=[&quot;INDEX&quot;, &quot;CREATE&quot;], title=&quot;Bulk Insert Method&quot;,<br>                                description=&quot;Whether to use INDEX (allows upserts) or CREATE (errors on duplicate _id)&quot;),<br>    &quot;trust_self_signed_certs&quot;: Param(&quot;true&quot;, type=&quot;string&quot;, enum=[&quot;true&quot;, &quot;false&quot;]),<br>    &quot;disable_certificate_validation&quot;: Param(&quot;true&quot;, type=&quot;string&quot;, enum=[&quot;true&quot;, &quot;false&quot;]),<br><br>    &quot;dead_letter_table&quot;: &quot;my-project:dead_letter_dataset.my_dead_letter_table&quot;,<br>    &quot;staging_location&quot;: &quot;gs://my-project-dataflow-temp-bucket/staging&quot;,<br>    &quot;error_location&quot;: &quot;gs://my-project-dataflow-temp-bucket/errors&quot;,<br>    &quot;use_legacy_sql&quot;: Param(&quot;false&quot;, type=&quot;string&quot;, enum=[&quot;true&quot;, &quot;false&quot;]),<br>    &quot;query_location&quot;: Param(&quot;US&quot;, type=&quot;string&quot;, enum=[&quot;EU&quot;, &quot;US&quot;]),<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7751a42db2aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>