<?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 Ashish Jain on Medium]]></title>
        <description><![CDATA[Stories by Ashish Jain on Medium]]></description>
        <link>https://medium.com/@ashishjaingoogle?source=rss-700442ffe5ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XcTLuSkL297iEINl4duOQw.png</url>
            <title>Stories by Ashish Jain on Medium</title>
            <link>https://medium.com/@ashishjaingoogle?source=rss-700442ffe5ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:07:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashishjaingoogle/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[Solving for Dynamic JSON and Nested Arrays in BigQuery]]></title>
            <link>https://medium.com/google-cloud/solving-for-dynamic-json-and-nested-arrays-in-bigquery-5f4e67670b96?source=rss-700442ffe5ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f4e67670b96</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[google-big-query]]></category>
            <dc:creator><![CDATA[Ashish Jain]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 02:22:52 GMT</pubDate>
            <atom:updated>2025-07-29T02:22:52.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvSARN6tfyxTcYG-ugFBLw.png" /></figure><p>How to combine Standard Views, Materialized Views, and Stored Procedures to build a robust, cost-effective data pipeline for semi-structured data.</p><p>If you’re a data engineer, you know the challenge. You have a stream of raw JSON data landing in BigQuery. The schema is flexible — new keys appear and disappear, and some values are nested arrays. Your goal is to create a clean, flat, performant table for your analysts. How do you build a pipeline that is both powerful and easy to maintain?</p><p>This article provides a complete, production-ready playbook to solve this exact problem. We’ll walk through a four-part architecture that is scalable, automated, and cost-effective by design.</p><h3>The Power of Layering: Why This Pattern Works</h3><p>The key to building a sophisticated data pipeline is to separate concerns. Instead of trying to accomplish everything in a single, monolithic query, we can create layers where each component has a specialized job.</p><ul><li><strong>A Transformation Layer:</strong> This layer is responsible for complex logic like cleaning data, applying business rules, and reshaping complex structures like arrays.</li><li><strong>An Acceleration Layer:</strong> This layer’s sole purpose is performance. It takes the clean data from the transformation layer and creates a pre-computed, optimized result set that’s ready for high-speed analytics.</li></ul><p>By separating these two functions, we create a pipeline that is easier to understand, maintain, and scale. This article demonstrates how to implement this powerful layered pattern in BigQuery.</p><h3>The Solution: A Four-Part Architecture</h3><p>Our architecture uses a sequence of BigQuery objects to create a seamless flow from raw data to an analysis-ready table.</p><p>Base Table -&gt; Standard View -&gt; Materialized View -&gt; User Queries</p><h4>Step 1: The Foundation — A Partitioned Base Table</h4><p>First, we need a reliable place to land our raw data. A partitioned table is perfect for this, as it optimizes storage costs and allows for efficient data management.</p><ul><li><strong>Purpose:</strong> Store raw, unmodified JSON data.</li><li><strong>Key Feature:</strong> Partitioned by date.</li></ul><p>SQL</p><pre>-- This table will store your raw JSON payloads as they arrive.<br>CREATE OR REPLACE TABLE demo2.json_events_with_array<br>(<br>  ingestion_time TIMESTAMP,<br>  custom_fields JSON<br>)<br>PARTITION BY DATE(ingestion_time);</pre><h4>Step 2: The Transformation Layer — A Standard View</h4><p>Here, we create a Standard View dedicated to the complex task of reshaping our data. This view will read from the base table and flatten the nested myid array into individual rows.</p><ul><li><strong>Purpose:</strong> To act as a dedicated transformation layer.</li><li><strong>Key Feature:</strong> It’s a logical view, so it costs nothing until you query it.</li></ul><p>SQL</p><pre>-- This view handles the flattening logic, preparing the data for the next step.<br>CREATE OR REPLACE VIEW demo2.events_unflattened_view AS<br>SELECT<br>  base.ingestion_time,<br>  base.custom_fields,<br>  JSON_VALUE(id_from_array) as myid<br>FROM<br>  demo2.json_events_with_array AS base,<br>  UNNEST(JSON_QUERY_ARRAY(base.custom_fields, &#39;$.myid&#39;)) AS id_from_array;</pre><h4>Step 3: The Automation — A Stored Procedure</h4><p>To handle a dynamic schema where new keys can appear in our JSON, we use a Stored Procedure. This procedure will automatically discover new keys and rebuild our final view with the new columns, ensuring our pipeline never goes stale.</p><ul><li><strong>Purpose:</strong> Automate the creation and maintenance of our final performance layer.</li><li><strong>Key Feature:</strong> Provides a “set it and forget it” approach to schema evolution.</li></ul><p>SQL</p><pre>-- This procedure builds the final MV, dynamically discovering JSON keys.<br>CREATE OR REPLACE PROCEDURE demo2.usp_create_or_replace_events_mv()<br>BEGIN<br>  DECLARE dynamic_columns_sql STRING;<br>  SET dynamic_columns_sql = (<br>    SELECT STRING_AGG(FORMAT(&#39;JSON_VALUE(custom_fields, &quot;$.%s&quot;) AS `%s`&#39;, key, key),&#39;, &#39;)<br>    FROM (<br>      SELECT DISTINCT key FROM demo2.json_events_with_array, UNNEST(JSON_KEYS(custom_fields)) AS key<br>      WHERE key != &#39;myid&#39;<br>    )<br>  );</pre><pre>  DECLARE final_sql_command STRING;<br>  SET final_sql_command = FORMAT(&quot;&quot;&quot;<br>    CREATE OR REPLACE MATERIALIZED VIEW demo2.events_mv<br>    CLUSTER BY myid AS<br>    SELECT<br>      ingestion_time,<br>      myid,<br>      %s<br>    FROM<br>      demo2.events_unflattened_view;<br>  &quot;&quot;&quot;, dynamic_columns_sql);</pre><pre>  EXECUTE IMMEDIATE final_sql_command;<br>END;</pre><h4>Step 4: The Acceleration Layer — An Incremental Materialized View</h4><p>Finally, we create our Materialized View. This is our performance layer. It reads from the simple, clean events_unflattened_view and creates a physical, pre-computed table. We also cluster it by myid for lightning-fast lookups. This view is created by calling the stored procedure from Step 3.</p><p>SQL</p><pre>-- This command runs the procedure, which in turn builds our final MV.<br>CALL demo2.usp_create_or_replace_events_mv();</pre><p>Your end-users and BI tools will only ever query this final demo2.events_mv table.</p><p>You no longer have to choose between advanced transformations and performance. With this pattern, you get both. Now you have a playbook to tackle even the most complex JSON challenges BigQuery throws at you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f4e67670b96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/solving-for-dynamic-json-and-nested-arrays-in-bigquery-5f4e67670b96">Solving for Dynamic JSON and Nested Arrays in BigQuery</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run Dataflow Job based on EventArc GCS Trigger.]]></title>
            <link>https://medium.com/google-cloud/run-dataflow-job-based-on-eventarc-gcs-trigger-043e32c33e07?source=rss-700442ffe5ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/043e32c33e07</guid>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[eventarc]]></category>
            <dc:creator><![CDATA[Ashish Jain]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 15:06:56 GMT</pubDate>
            <atom:updated>2024-09-16T15:06:56.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>Goal:</h3><p>Create an Eventarc trigger that monitors a GCS bucket for new file uploads and automatically initiates a Dataflow job defined in a template when a new file is detected.</p><h3>POC Steps</h3><h3>Step 1 : Create a GCS bucket</h3><p>If a new file is uploaded then the event is triggered .</p><p>Eg — my-event-bucket-poc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*LemwXf6qXvOcKnUP" /></figure><pre>STORAGE_BUCKET=&quot;my-event-bucket-poc&quot;<br>gcloud storage buckets create \<br>gs://$STORAGE_BUCKET</pre><h3>Step 2 : Enable APIs</h3><ul><li>Make sure below APIS are enabled in the project</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*GfxoA8o-Brtb8bny" /></figure><h3>Step 3 : Create Workflow</h3><p>You can use the console to create workflow and use <a href="https://docs.google.com/document/d/1ZpKNdwKdg8X1D-aUMDpWD8jo0uuq3ryC8Em4iY_Kms8/edit?resourcekey=0-OLfti6Awr0_V2A1xUHy9Dw&amp;tab=t.0#heading=h.425d72jrub1l">myEventWorkflow.yaml</a> and proceed to step 5 directly .</p><p>Change below as per your project, and then run in the cloud shell.</p><pre>export PROJECT_ID=mydiyproject<br>export PROJECT_NUMBER=711473716890<br>export WORKFLOW_LOCATION=us-central1<br>export TRIGGER_LOCATION=us-central1<br>export MY_WORKFLOW=myEventWorkflow<br><br>gcloud config set \<br>    workflows/location \<br>    ${WORKFLOW_LOCATION}<br><br>gcloud config set \<br>    eventarc/location \<br>    ${TRIGGER_LOCATION}<br><br><br>export \<br>    MY_SERVICE_ACCOUNT=my-service-account<br>gcloud iam service-accounts create \<br>    ${MY_SERVICE_ACCOUNT}<br><br>gcloud projects \<br>    add-iam-policy-binding \<br>    ${PROJECT_ID} \<br>    --member=&quot;serviceAccount:${MY_SERVICE_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com&quot; \<br>    --role=roles/eventarc.eventReceiver<br><br>gcloud projects \<br>    add-iam-policy-binding \<br>    ${PROJECT_ID} \<br>    --member=&quot;serviceAccount:${MY_SERVICE_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com&quot; \<br>    --role=roles/workflows.invoker<br><br><br>gcloud projects \<br>    add-iam-policy-binding \<br>    ${PROJECT_ID} \<br>    --member=&quot;serviceAccount:${PROJECT_NUMBER}-compute@developer.gserviceaccount.com&quot; \<br>    --role=roles/logging.logWriter<br><br><br><br>SERVICE_ACCOUNT=&quot;$(gcloud storage \<br>    service-agent \<br>    --project=${PROJECT_ID})&quot;<br><br>gcloud projects \<br>    add-iam-policy-binding \<br>    ${PROJECT_ID} \<br>    --member=&quot;serviceAccount:${SERVICE_ACCOUNT}&quot; \<br>    --role=roles/pubsub.publisher<br><br>gcloud projects \<br>    add-iam-policy-binding \<br>    ${PROJECT_ID} \<br>    --member=&quot;serviceAccount:@gcp-sa-pubsub.iam.gserviceaccount.com&quot;&gt;service-${PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com&quot; \<br>    --role=&#39;roles/iam.serviceAccountTokenCreator&#39;</pre><h4>myEventWorkflow.yaml</h4><p>This yaml file is a workflow yaml file which will have details related to the dataflow job. For Poc purposes I have used a word count template . You can create the template of your job to deploy the pipeline and update the Yaml file accordingly .</p><p>Below if the flow chart from console -&gt;</p><pre># This workflow demonstrates how to use the Cloud Dataflow connector.<br># The workflow creates a word count job using a Dataflow public job template<br># and uses a Cloud Storage bucket as temporary storage for temp files.<br># The bucket resource is deleted after the job completes.<br># Expected successful output: &quot;SUCCESS&quot;<br><br>- init:<br>    assign:<br>      - project_id: ${sys.get_env(&quot;GOOGLE_CLOUD_PROJECT_ID&quot;)}<br>      - location: &quot;us-central1&quot;<br>      - zone: &quot;us-central1-a&quot;<br>      - bucket_name: &quot;mydiybucket-workflow&quot;<br>      - job_name: &quot;mydiybucket-workflow-job-from-template-launch&quot;<br>      - input_file: &quot;gs://dataflow-samples/shakespeare/kinglear.txt&quot;<br>      - output_storage_file_prefix: ${&quot;gs://&quot; + bucket_name + &quot;/counts&quot;}<br>      - temp_location: ${&quot;gs://&quot; + bucket_name + &quot;/counts/temp&quot;}<br>      - template_path: &quot;gs://dataflow-templates-us-central1/latest/Word_Count&quot;<br>- launch:<br>    call: googleapis.dataflow.v1b3.projects.locations.templates.launch<br>    args:<br>      projectId: ${project_id}<br>      location: ${location}<br>      gcsPath: ${template_path}<br>      body:<br>        jobName: ${job_name}<br>        parameters:<br>          inputFile: ${input_file}<br>          output: ${output_storage_file_prefix}<br>        environment:<br>          numWorkers: 1<br>          maxWorkers: 2<br>          zone: ${zone}<br>          tempLocation: ${temp_location}<br>- the_end:<br>    return: &quot;SUCCESS&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1z6w0EnNezywX79h" /></figure><h3>Step 4 : create Eventarc Trigger and Deploy workflow</h3><p>Here source is myEventWorkflow.yaml, which I created in the previous step.</p><pre>gcloud workflows deploy \<br>    ${MY_WORKFLOW} \<br>    --source=myEventWorkflow.yaml<br><br><br>gcloud eventarc triggers create \<br>    storage-events-trigger \<br>    --destination-workflow=${MY_WORKFLOW} \<br>    --event-filters=&quot;type=google.cloud.storage.object.v1.finalized&quot; \<br>    --event-filters=&quot;bucket=my-event-bucket-poc&quot; \ --service-account=&quot;${MY_SERVICE_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*ycuX9xr0dKkSkSB-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*YIvY5JyM_YGzUavQ" /></figure><h3>Step 5 : Add an Event — A GCS file</h3><p>Here i’ve created a sample file random.txt and it will upload to gcs bucket my-event-bucket-poc, and should trigger workflow.</p><pre>echo &quot;Hello World&quot; &gt; random.txt<br>gcloud storage cp random.txt \<br>    gs://my-event-bucket-poc/random.txt<br><br><br>gcloud workflows executions list \<br>    ${MY_WORKFLOW} --limit=5<br><br><br>echo &quot;Hello World&quot; &gt; random.txt<br>gcloud storage cp random.txt \<br>    gs://my-event-bucket-poc/random.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cm7oXr4o6IK8r40O" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zjOAmxcE8N8qc35R" /></figure><h3>Step 6 : Validations</h3><ol><li>Go to the selected workflow -&gt; executions and see if it is running / succeeded .</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tcwpqs0MroP4Av9k" /></figure><ol><li>Go to a dataflow job , it should be in running /succeeded .</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xHf4uPrCG-qufg_c" /></figure><h4><strong>Reference(s) :</strong></h4><blockquote><a href="https://cloud.google.com/workflows/docs/samples/workflows-connector-dataflow">Connector for Dataflow | Workflows | Google Cloud</a></blockquote><blockquote><a href="https://cloud.google.com/dataflow/docs/reference/rest/v1b3/projects.locations.templates/launch">Method: projects.locations.templates.launch | Cloud Dataflow</a></blockquote><blockquote><a href="https://cloud.google.com/dataflow/docs/reference/rest">Dataflow API | Google Cloud</a></blockquote><blockquote><a href="https://cloud.google.com/dataflow/docs/guides/pipeline-workflows#traditional-vs-templates">Design Dataflow pipeline workflows | Google Cloud</a></blockquote><blockquote><a href="https://cloud.google.com/dataflow/docs/guides/templates/creating-templates#create-and-stage-a-classic-template">Creating classic Dataflow templates | Google Cloud</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=043e32c33e07" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/run-dataflow-job-based-on-eventarc-gcs-trigger-043e32c33e07">Run Dataflow Job based on EventArc GCS Trigger.</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Private Uptime check of Flask API running on Google cloud VM]]></title>
            <link>https://medium.com/google-cloud/private-uptime-check-of-flask-api-running-on-google-cloud-vm-7bb5dbe7f7fe?source=rss-700442ffe5ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb5dbe7f7fe</guid>
            <category><![CDATA[operations-suite]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[uptime-monitoring]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <dc:creator><![CDATA[Ashish Jain]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 08:59:14 GMT</pubDate>
            <atom:updated>2023-06-07T06:13:14.659Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Step 1</strong></h3><p>Start a VM and run a simple flask API on port 8081.</p><p>Here it should be on the same VPC network. I will be accessing it using Primary internal IP .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sp_7F7pLUHSY1J-iD6fTHw.png" /></figure><p>ssh to it , and create a simple <a href="http://app.py/">app.py</a></p><pre>from flask import Flask<br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def index():<br>  return &#39;It Works!&#39;</pre><p>Run below commands , mention the port 8081.</p><pre>export FLASK_ENV=development<br>export FLASK_APP=api.py<br>flask run flask run --host=0.0.0.0 --port=8081</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALl536N4P6H7BGVRUOq9fA.png" /></figure><p>It should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ThQeLbxYuEzlh0scG_cQbw.png" /></figure><h4>Authorize the service account</h4><p>Uptime checks use a Monitoring-owned service account to manage interactions with the Service Directory service. The service account name has the following format:</p><pre>gcloud config set project PROJECT_ID<br>export PROJECT_ID=$(gcloud config get-value core/project)<br>export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format=&#39;get(projectNumber)&#39;)<br><br>gcloud projects add-iam-policy-binding $PROJECT_ID \<br>--member=&#39;serviceAccount:@gcp-sa-monitoring-notification.iam.gserviceaccount.com&quot;&gt;service-&#39;$PROJECT_NUMBER&#39;@gcp-sa-monitoring-notification.iam.gserviceaccount.com&#39; \<br>--role=&#39;roles/servicedirectory.viewer&#39;<br><br>gcloud projects add-iam-policy-binding $PROJECT_ID \<br>--member=&#39;serviceAccount:@gcp-sa-monitoring-notification.iam.gserviceaccount.com&quot;&gt;service-&#39;$PROJECT_NUMBER&#39;@gcp-sa-monitoring-notification.iam.gserviceaccount.com&#39; \<br>--role=&#39;roles/servicedirectory.pscAuthorizedService&#39;</pre><p><strong>Configure firewall : </strong>Allow request from below mentioned source-ranges.</p><p>Network is default for me , same as vm.</p><pre>gcloud compute firewall-rules create<br>--network=&quot;default&quot;<br>--action=allow   --direction=ingress   --source-ranges=&quot;35.199.192.0/19&quot; \<br>--rules=tcp   --project=&quot;$PROJECT_ID&quot;</pre><h3>Step 2:</h3><p>Create a Service directory and mention end points .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hTIEox-N8NYpL29s2jzV1w.png" /></figure><p>Click on Register service and select “Standard” As service type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYFZhwoSD2syP2ceWI34PQ.png" /></figure><p>Mention Region , Namespace ( create if not available ) and unique service name and create it .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwbGp3Jelb_wQ7hsgzC2UA.png" /></figure><h3>Step 3 : Add endpoint in service</h3><p>After creating the service , add an endpoint in it. Mention the IP address , which is available in step 1 . Here it is Primary Internal IP Address. X.X.0.2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f87grJ2kif5p2cSVh_kCUQ.png" /></figure><p>Go to Monitoring and Click on Uptime check . with below configurations</p><p>Target -&gt; Protocol : HTTP</p><p>Resource Type : Internal IP</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XC4jKDxweO3FjqA4ffWr4Q.png" /></figure><p>Then Select the service directory which is created in step 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHjeDi4xFowYJbXh-N8iAA.png" /></figure><p>Leave all other configurations as default . For simplicity I am not adding any notification channel .Test the uptime check by clicking on test, it should give 200 responses if the API is up and running .</p><p>You can see the request coming in the ssh window , like below .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0FkBfQ-GaFY7TzwRZyQHg.png" /></figure><p>After creating the uptime check , you can access the charts like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QS0sjMo4UANHDTe1zU4IRg.png" /></figure><p><em>disclaimer : For demo purpose only . Refer Official documentation for detailed guidelines </em><a href="https://cloud.google.com/monitoring/uptime-checks/private-checks"><em>https://cloud.google.com/monitoring/uptime-checks/private-che</em></a>ck</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb5dbe7f7fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/private-uptime-check-of-flask-api-running-on-google-cloud-vm-7bb5dbe7f7fe">Private Uptime check of Flask API running on Google cloud VM</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgres Automatic IAM Database Authentication in Airflow]]></title>
            <link>https://medium.com/google-cloud/postgres-automatic-iam-database-authentication-in-airflow-7043cec895e4?source=rss-700442ffe5ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/7043cec895e4</guid>
            <category><![CDATA[iam-roles]]></category>
            <category><![CDATA[gcp-security-operations]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[ami]]></category>
            <dc:creator><![CDATA[Ashish Jain]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 03:51:04 GMT</pubDate>
            <atom:updated>2023-03-20T05:10:25.947Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Goal : To connect to Postgres using Automatic IAM db authentication in Airflow (Cloud Composer)</strong></p><p>Using this approach Passwords and tokens are not required to be passed while making connection to PostgreSQL.It will use IAM service account Credentials to login to PostgreSQL.In this approach I have used Google Cloud SQL with PostgreSQL Instance and enabled Private IP .</p><p><strong>Step 1 : Cloud Composer Environment : Package Installation</strong></p><p>Install the PYPI package <strong>cloud-sql-python-connector and pg8000 </strong>in the cloud composer environment.</p><p>[<a href="https://pypi.org/project/cloud-sql-python-connector/">https://pypi.org/project/cloud-sql-python-connector/</a>]</p><p>I am using below version (Choose the version which supports your composer version )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxJf9T8CGlf8b8vV2REWDQ.png" /></figure><p><strong>Step 2 : IAM account</strong></p><p>Add a Cloud IAM user account to Cloud SQL Postgre instance .</p><p>[After you create a user account with Cloud IAM authentication, it will have no database privileges, so make sure permissions are granted as needed ,eg in step 3 ]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hV3N11cF6KpNhCZP1XjhA.png" /></figure><p>* At IAM level , grant required permission to access cloud sql.</p><p><strong>Step 3 (Optional) : DB and Table setup In Postgre .</strong></p><p>If you already have tables and granted all the permission to the IAM service account , you can skip this step.</p><p>Use the command line where psql is installed and in the same VPC network.Here you can use builtin in user Postgre,( * password required )</p><pre>psql -h X.Y.240.3 - user=postgres - dbname=postgres<br>Create schema db3;<br>postgres=&gt; create schema db3;<br>postgres=&gt; GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA db3 to &quot;to-access-cloud-sql@XXXXX.iam&quot;;</pre><p>Now I will create the sample table using an IAM service account . Use below in the command line. Here it will be logged in by token.</p><pre>env PGPASSWORD=$(gcloud auth print-access-token to-access-cloud-sql@XXXXXX.iam.gserviceaccount.com) psql -h X.X.240.3 - user=&quot;to-access-cloud-sql@XXXXXX.iam&quot; - dbname=db3<br>CREATE TABLE IF NOT EXISTS mypets (<br>pet_id SERIAL PRIMARY KEY,<br>name VARCHAR NOT NULL,<br>pet_type VARCHAR NOT NULL,<br>birth_date DATE NOT NULL,<br>OWNER VARCHAR NOT NULL);</pre><p><strong>Step 4: Service Account key file .</strong></p><p>Upload the IAM Service account key to the data GCS bucket in Airflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6UCirixjcVO6zw86AZmnQ.png" /></figure><p>To secure these credentials, it is recommended that you use a <a href="https://cloud.google.com/storage/docs/access-control/lists">Cloud Storage ACL</a> to restrict access to the key file.</p><p><strong>Step 5 : Airflow Dag Using Python Operator .</strong></p><p>Using this approach password and tokens are not required to be passed while making connection to PostgreSQL.</p><p>In Below sample dag change below value as per your requirement</p><ul><li>INSTANCE_CONNECTION_NAME -Your Cloud SQL instance name like XXXX:us-west1:diypossql</li><li>DB_IAM_USER — Same as the service account ,But without .gserviceaccount.com</li><li>DB_NAME — Db name where you have created the table.and granted permission to the service account .</li><li>PRIVATE_IP — PRIVATE_IP of Cloud SQL instance . You can get it from google cloud console.</li><li>GOOGLE_APPLICATION_CREDENTIALS to the file ,Created in step 4 .</li></ul><pre>from __future__ import print_function<br>from airflow.operators.python_operator import PythonOperator<br>import datetime<br>from airflow import DAG<br>from airflow.operators.dummy import DummyOperator<br>from airflow.utils.task_group import TaskGroup<br>import time<br>from google.cloud.sql.connector import Connector, IPTypes<br>import sqlalchemy<br>import pg8000<br>import os<br><br><br>def connect_with_connector_auto_iam_authn() -&gt; sqlalchemy.engine.base.Engine:<br>    &quot;&quot;&quot;<br>    Initializes a connection pool for a Cloud SQL instance of Postgres.<br><br>    Uses the Cloud SQL Python Connector with Automatic IAM Database Authentication.<br>    &quot;&quot;&quot;<br>    # Note: Saving credentials in environment variables is convenient, but not<br>    # secure - consider a more secure solution such as<br>    # Cloud Secret Manager (https://cloud.google.com/secret-manager) to help<br>    # keep secrets safe.<br>    import os<br>    os.environ[&quot;INSTANCE_CONNECTION_NAME&quot;] = &quot;XXXX:us-west1:diypossql&quot;<br>    os.environ[&quot;DB_IAM_USER&quot;] = &quot;to-access-cloud-sql@XXXX.iam&quot;<br>    os.environ[&quot;DB_NAME&quot;] = &quot;db3&quot;<br>    os.environ[&quot;PRIVATE_IP&quot;] = &quot;X.Y.240.3&quot;<br>    os.environ[&#39;GOOGLE_APPLICATION_CREDENTIALS&#39;] = &#39;/home/airflow/gcs/data/XXXXX-6fb03d09b1cf.json&#39;<br><br>    instance_connection_name = os.environ[&quot;INSTANCE_CONNECTION_NAME&quot;]  # e.g. &#39;project:region:instance&#39;<br>    db_iam_user = os.environ[&quot;DB_IAM_USER&quot;]  # e.g. &#39;sa-name@project-id.iam&#39;<br>    db_name = os.environ[&quot;DB_NAME&quot;]  # e.g. &#39;my-database&#39;<br><br>    ip_type = IPTypes.PRIVATE if os.environ.get(&quot;PRIVATE_IP&quot;) else IPTypes.PUBLIC<br><br>    # initialize Cloud SQL Python Connector object<br>    connector = Connector()<br><br>    def getconn() -&gt; pg8000.dbapi.Connection:<br>        conn: pg8000.dbapi.Connection = connector.connect(<br>            instance_connection_name,<br>            &quot;pg8000&quot;,<br>            user=db_iam_user,<br>            db=db_name,<br>            enable_iam_auth=True,<br>            ip_type=ip_type<br>        )<br>        return conn<br><br>    # The Cloud SQL Python Connector can be used with SQLAlchemy<br>    # using the &#39;creator&#39; argument to &#39;create_engine&#39;<br>    pool = sqlalchemy.create_engine(<br>        &quot;postgresql+pg8000://&quot;,<br>        creator=getconn,<br>        # ...<br>    )<br>    return pool<br><br>def runme():<br>    connect_with_connector_auto_iam_authn().execute(&quot;INSERT INTO mypets (name, pet_type, birth_date, OWNER) VALUES ( &#39;Milo&#39;, &#39;Dog&#39;, &#39;2018-07-05&#39;, &#39;Jane&#39;);&quot;)<br><br><br>with DAG(<br>    dag_id=&quot;postgre_testing13&quot;,<br>    start_date=datetime.datetime(2023, 3, 18),<br>    schedule_interval=None,<br>    catchup=False,<br>) as dag:<br>        run_this = PythonOperator(<br>        task_id=&#39;runinpostgre&#39;,<br>        provide_context=True,<br>        python_callable=runme)<br><br>        run_this</pre><p>Here the path is like /home/airflow/gcs/data/&lt;your file name.json&gt; , not the GCS bucket path.</p><p><strong>Step 5</strong> : After running the DAG in cloud composer ,verify that data is inserted into the “mypets” tables using the command mentioned in step 3.</p><p>Reference Links : <a href="https://cloud.google.com/sql/docs/postgres/iam-logins#python">https://cloud.google.com/sql/docs/postgres/iam-logins#python</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7043cec895e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/postgres-automatic-iam-database-authentication-in-airflow-7043cec895e4">Postgres Automatic IAM Database Authentication in Airflow</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deterministic encryption/decryption with Cloud KMS using DLP Plugin in Data Fusion]]></title>
            <link>https://medium.com/google-cloud/deterministic-encryption-decryption-with-cloud-kms-using-dlp-plugin-in-data-fusion-f237bd2aa5da?source=rss-700442ffe5ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/f237bd2aa5da</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cloud-data-fusion]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Ashish Jain]]></dc:creator>
            <pubDate>Sat, 26 Nov 2022 01:45:50 GMT</pubDate>
            <atom:updated>2022-11-27T06:47:32.666Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deterministic encryption/decryption with Cloud KMS using DLP Plugin in Cloud Data Fusion</h3><blockquote><strong>Goal</strong> : To encrypt and decrypt the data in the datafusion pipeline, DLP plugin can be used .This post provides a step by step guide to do deterministic encryption and decryption in data fusion with cloud KMS .</blockquote><h3>Steps :</h3><h4><strong>1. KMS Keys</strong></h4><p>To manage encryption keys and perform cryptographic operations with those keys.</p><p><strong>1.1</strong> Go to Security → Key Management. (Enable the Api if not enabled.)</p><p>You can follow the steps <a href="https://cloud.google.com/kms/docs/creating-keys#kms-create-symmetric-encrypt-decrypt-gcloud">here</a> or continue with the steps below.</p><p><strong>1.2</strong> Creating symmetric encryption keys , Create keyring :</p><p><em>Required role permission : cloudkms.keyRings.create </em><a href="https://cloud.google.com/kms/docs/reference/permissions-and-roles"><em>refer</em></a></p><p>Create a key ring from key management. Mention name of key ring and location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zge_bXsrD52HmqpfPef45g.png" /></figure><p><strong>1.3</strong> After Creating a keyring , Create a key , and mention other details as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IpnegOT7V5WygUtQ" /></figure><p>1.4 Copy the resource name of the key, we will use it in next steps .</p><pre>projects/xxxxxxx/locations/us-west1/keyRings/mytestkeyring/cryptoKeys/testkey</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xt4hDU8tChQkKbag" /></figure><p>1.5 Create a wrapped key ( follow <a href="https://cloud.google.com/dlp/docs/create-wrapped-key">this link</a> or continue here) :</p><p>In cloud shell with user having required permissions , execute below commands to get the wrapped key :</p><p>a.</p><pre>openssl rand -out &quot;./aes_key.bin&quot; 32<br></pre><p>b.</p><pre>base64 -i ./aes_key.bin</pre><p><em>It is BASE64_ENCODED_AES_KEY ,You get an output similar to the following: </em>uEDo6/yKx+zCg2cZ1DBwpwvzMVNk/c+jWs7OwpkMc/s=</p><p>c. To wrap the AES key, use curl to send the following request to the Cloud KMS API</p><p><strong>Replace the key</strong> and BASE64_ENCODED_AES_KEY returned from steps 1.4 and b</p><pre>curl &quot;https://cloudkms.googleapis.com/v1/projects/xxxxxx/locations/us-west1/keyRings/mytestkeyring/cryptoKeys/testkey:encrypt&quot; \<br>  --request &quot;POST&quot; \<br>  --header &quot;Authorization:Bearer $(gcloud auth application-default print-access-token)&quot; \<br>  --header &quot;content-type: application/json&quot; \<br>  --data &quot;{\&quot;plaintext\&quot;: \&quot;uEDo6/yKx+zCg2cZ1DBwpwvzMVNk/c+jWs7OwpkMc/s=\&quot;}&quot;</pre><p>Take note of the value of ciphertext in the response that you get. That is your wrapped key. We will be using it in the next steps .</p><h4><strong>2 DLP Template</strong></h4><p>2.1 To Create a DLP template go to Security → Data Loss Prevention. Enable the Api if not enabled.</p><p>2.2 Create the template from the configuration Tab .You can follow the Steps <a href="https://cloud.google.com/dlp/docs/creating-templates-inspect">here</a> to create the template.</p><p>2.3 Once template is created copy the path like :</p><blockquote>projects/xxxxxxx/locations/us-west1/inspectTemplates/template1</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5C7OB88VmlEMHrN29JxYA.png" /></figure><h4>3 Data fusion pipeline</h4><p>Enable the data fusion api . Once done ,then create a data fusion instance using Data Fusion → Instance</p><p>Grant permission to Cloud Data Fusion to use the selected Dataproc Service Account.Click create .</p><p>It might take around 20 mins to spin up .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qiE3c8olk6W911qH" /></figure><p>Once instance is up ,go to HUB from the top menu and search for “ data loss “, deploy the plugin “data loss prevention”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OBwY4ajJ_Uq-tLuU" /></figure><p>From the left menu select studio from the Pipeline .We will be creating the below pipeline . For simplicity and understanding, we are going to encrypt and decrypt in the same pipeline .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CZ9dRchesJhBDKGd" /></figure><ol><li>Source : Big Query</li></ol><p>Select Big Query from the source , in the properties browse the dataset and table .Click on validate after filling required information. You can also check the output schema .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h5AqQi0B4rv9rdVv" /></figure><p>You can see the DLP related transformation in “transform” .</p><p>2. For encryption — select Google DLP redact from transform .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*1t63M4Xse9NWfFtW" /></figure><p>Connect a big query source and DLP redact . The columns of the Big query source will be available in DLP redact .</p><ul><li>In the properties section , select “Yes” to Use custom template*</li><li>And paste the template path from step 2.1 , Mention the same resource location .</li><li>In the Matching choose deterministic encryption and select the input field where you want to have encryption .</li><li>Use Crypto key Type as “KMS Wrapped key” .</li><li>Mention KMS Resource ID and Wrapped Key from steps 1.4 ,1.5.c respectively .</li><li>Use the surrogate key of your choice.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y67uSrYbvOOuSJMC" /></figure><p>3. For decryption — Use DLP decrypt from the transform , and mention all the details same as encryption .</p><p>4. Sink : Select Big query from the sink and browse the sink table . make sure it has a matching schema same as output of DLP decrypt .</p><p>Make sure to validate each node. Additionally Grant required permission for DLP and KMS related roles .</p><p><em>[While using Deterministic Encryption with KMS Wrapped Key, the Cloud KMS CryptoKey Encrypter/Decrypter role must be granted to Cloud Data Loss Prevention Service Agent]</em></p><p>Go to the preview section and Run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*08IqEGVR1z1mI66N" /></figure><p>Once Succeeded,use Preview data to check the sample results .Where column a1 is encrypted. It is the output of Google DLP redact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QTVMupS4rBQEx8EQ" /></figure><p>After decryption below is the preview data .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F2NUwuy2AHZXKkFA" /></figure><p>You can add more transformation in between the source and sink .Once done, deploy the pipeline using Deploy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f237bd2aa5da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/deterministic-encryption-decryption-with-cloud-kms-using-dlp-plugin-in-data-fusion-f237bd2aa5da">Deterministic encryption/decryption with Cloud KMS using DLP Plugin in Data Fusion</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>