<?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 Austen Novis on Medium]]></title>
        <description><![CDATA[Stories by Austen Novis on Medium]]></description>
        <link>https://medium.com/@austennovis?source=rss-8b06b96dee6c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dZCJg1--IGxa3XxB.</url>
            <title>Stories by Austen Novis on Medium</title>
            <link>https://medium.com/@austennovis?source=rss-8b06b96dee6c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:24:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@austennovis/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[Serverless Data Pipelines in GCP using Dataform and BigQuery Remote Functions]]></title>
            <link>https://engineering.premise.com/serverless-data-pipelines-in-gcp-using-dataform-and-bigquery-remote-functions-9ee235d0cb18?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ee235d0cb18</guid>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[goblet]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 13:35:22 GMT</pubDate>
            <atom:updated>2023-08-23T13:35:22.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cSfINV5gIm4zLBx9" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://cloud.google.com/dataform">Dataform</a> is an amazing new offering from <a href="https://cloud.google.com/gcp?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=na-US-all-en-dr-bkws-all-all-trial-e-dr-1605212&amp;utm_content=text-ad-none-any-DEV_c-CRE_665735450624-ADGP_Hybrid+%7C+BKWS+-+EXA+%7C+Txt_GCP-KWID_43700077223807298-kwd-87853815&amp;utm_term=KW_gcp-ST_gcp&amp;gclid=Cj0KCQjwuNemBhCBARIsADp74QQNLPlImqheJCB4pu0-ZL0f9HuT7W1GmNIhkT0qfNjRLxpO1dZf-VwaAvqdEALw_wcB&amp;gclsrc=aw.ds&amp;hl=en">Google Cloud Platform</a> (GCP) that allows for serverless orchestration for data pipelines. Previously, data engineering pipelines were either supported by separate data engineering teams, which many smaller organizations don’t have the resources to support, or were stitched together using a series of interrelated BigQuery scheduled queries, which could be time-consuming to build and error-prone to run and maintain.</p><p>Dataform solves these problems, especially for data scientists and data analysts, by including features such as</p><ul><li>Ability to build data pipelines using SQL</li><li>Integrates with GitHub and GitLab for code versioning and deployment</li><li>Monitor pipelines for failures and trigger alerts</li></ul><p>The main limitation of Dataform is that it only supports SQL, with limited ability to add javascript, but this limitation can be overcome with <a href="https://cloud.google.com/bigquery/docs/remote-functions">BigQuery Remote Functions</a>. BigQuery Remote Functions allow you to call external services running in <a href="https://cloud.google.com/run">Cloudrun</a> or <a href="https://cloud.google.com/functions">Cloudfunctions</a> from BigQuery, making it possible to have a serverless data pipeline that can run custom logic in any programming language that you may need.</p><p>The rest of this blog post will go through a complete example on how to setup both Dataform and BigQuery Remote Functions in just a few steps.</p><h3>Setup Dataform</h3><p>We will begin by setting up a simple Dataform pipeline in the GCP console. Navigate to Dataform and create a repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*jj9V9s9zc_cTbRNGAemoxw.png" /><figcaption>Create Repository</figcaption></figure><p>Make sure to grant the default Dataform service account service-PROJECT_ID@gcp-sa-dataform.iam.gserviceaccount.com BigQuery read and write permissions. This can be accomplished using the roles/bigquery.user role.</p><p>Next create a new development workspace and allow GCP to initialize it, which will add the default files needed to run the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*txPxvOuBEIl5jRzjbXZ1ng.png" /><figcaption>Dataform files</figcaption></figure><p>Next create a new BigQuery dataset called tutorial , and inside a table called test with schema id: int, val: int, type: str .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*TXUqBxmildsCK_kJK72Jtw.png" /><figcaption>BigQuery Schema</figcaption></figure><p>We can insert some test data by running the following query</p><pre>INSERT `PROJECT.tutorial.test` (id, val, type) VALUES (1,1,&quot;double&quot;),(2,2,&quot;square&quot;),(3,3,&quot;zero&quot;) </pre><p>Now lets return back to Dataform and in the file dataform.json update the defaultSchema to be the dataset tutorial. This ensures that Dataform creates any new tables in this dataset, and will allow us to deploy our goblet application correctly.</p><p>Next we will update the definitions/first_view.sqlx file to create a new table from the table we selected in the previous step.</p><pre>config { type: &quot;table&quot; }<br><br>SELECT * FROM PROJECT.DATASET.TABLE</pre><p>We will now setup the BigQuery Remote Function before coming back and updating the second_view.sqlx.</p><h3>Setup BigQuery Remote Function</h3><p>Setting up the BigQuery Remote Function requires a few steps, including creating a Cloudrun or Cloudfunction endpoint, creating a BigQuery routine, creating a BigQuery connection, and setting up the IAM permissions.</p><p>Luckily we can leverage <a href="https://github.com/goblet/goblet">Goblet</a>, an open source framework for writing, deploying, and managing serverless REST APIs and related GCP resources. With Goblet, we will be able to simply write our API code, while Goblet will handle all of the deployment steps. The source code for the following steps can be found in <a href="https://github.com/premisedata/gcp-tutorials/tree/main/018-dataform-bq-remote-functions">Github</a>.</p><p>To setup our Goblet application we need a requirements.txt that includes goblet-gcp .</p><p>We also need to pip install goblet locally in order to deploy our application, which can be done by running the commandpip install goblet-gcp.</p><p>Next we will setup our main.py , which will contain our function logic. In our example we will create a remote function that takes in a val and a type and returns an int. Note that we can put any logic we would like in this function including calls to a machine learning model.</p><pre>from goblet import Goblet, goblet_entrypoint<br><br>app = Goblet(function_name=&quot;goblet&quot;)<br>goblet_entrypoint(app)<br><br><br>@app.bqremotefunction(dataset_id=&quot;tutorial&quot;, location=&quot;US&quot;)<br>def tutorial(value: int, type: str) -&gt; int:<br>    if type == &quot;double&quot;:<br>        return value * 2<br>    if type == &quot;square&quot;:<br>        return value**2<br>    if type == &quot;zero&quot;:<br>        return 0<br>    else:<br>        return value</pre><p>To deploy the cloudfunction, the BigQuery connection, the BigQuery routine, and the correct invoker permissions, we simple need to run goblet deploy -p PROJECT -l LOCATION .</p><p>(To read a full writeup on Goblet and BigQuery Remote Functions, check out <a href="https://engineering.premise.com/tutorial-deploying-bigquery-remote-functions-9040316d9d3e">Tutorial: Deploying BigQuery Remote Function</a>s)</p><h3>Setup Dataform with BigQuery Remote Function</h3><p>Now that we have deployed our BigQuery Remote Function we are able to reference it in Dataform in defintions/second_view.sqlx , by using the following code</p><pre>config { type: &quot;table&quot;,<br>columns:{<br>             id: &quot;id&quot;,<br>             val:&quot;val&quot;,<br>             type:&quot;type&quot;<br>      } }<br><br>SELECT id, `PROJECT.tutorial`.goblet_tutorial(val, type) as val, type FROM ${ref(&quot;first_view&quot;)}</pre><p>Note how we call the BigQuery remote function we created in the previous section by using PROJECT.tutorial`.goblet_tutorial(val, type) , where val and type fields are passed to our Goblet application, and an int is returned, which we save as val in our new table.</p><p>We can view the full pipeline by looking at the compiled graph in Dataform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghLzR-S-xElIJPHteF-k8g.png" /><figcaption>Compiled Graph</figcaption></figure><h3>Executing the Dataform Pipeline</h3><p>Now that we have created a BigQuery test dataset, a Dataform pipeline and deployed a BigQuery Remote Function, all that is left is to execute our pipeline!</p><p>This can be triggered in the console, by clicking the start execution dropdown and selecting all actions .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*O_r3aTnmc-hiNKDtmA19NQ.png" /><figcaption>Start Execution</figcaption></figure><p>The results of the pipeline can been seen in our test dataset in the table second_view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*2yWyY2nBvuHRHU40jIcJhw.png" /><figcaption>Results of Dataform Pipeline</figcaption></figure><h3>Conclusion</h3><p>Dataform is a powerful new offering from GCP that allows for serverless orchestration for data pipelines. The main limitation of using Dataform compared to other workflow tools, is that Dataform is only able to run SQL queries. However, we have shown that we can actually add any custom logic into our pipelines using BigQuery Remote Functions in just a few simple steps. This makes Dataform a powerful tool, that can handle a wide variety of use cases, especially for data scientists and data analysts.</p><p>Feel free to leave a comment letting us know your interesting use cases for Dataform and BigQuery Remote Functions and don’t forget to star our open source project <a href="https://github.com/goblet/goblet/issues">Goblet</a>.</p><p><strong><em>Premise is constantly looking to hire top-tier engineering talent to help us improve our front-end, mobile offerings and cloud infrastructure. Come find out why we’re consistently named among the top places to work in Silicon Valley by visiting our </em></strong><a href="https://bit.ly/3wnTrLn"><strong><em>Careers</em></strong></a><strong><em> page.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ee235d0cb18" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/serverless-data-pipelines-in-gcp-using-dataform-and-bigquery-remote-functions-9ee235d0cb18">Serverless Data Pipelines in GCP using Dataform and BigQuery Remote Functions</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily Manage IAM Policies for Serverless REST Applications in GCP with Goblet]]></title>
            <link>https://engineering.premise.com/easily-manage-iam-policies-for-serverless-rest-applications-in-gcp-with-goblet-f1580a97b74?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1580a97b74</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[identity-and-access]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[goblet]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 20:09:55 GMT</pubDate>
            <atom:updated>2023-07-10T20:09:55.640Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>By Austen Novis, Staff Software Engineer</em></strong></p><figure><img alt="Golden keys of various sizes arrayed on a wooden table" src="https://cdn-images-1.medium.com/max/1024/0*ouxzdExy8DC8eSF7" /><figcaption>Photo by <a href="https://unsplash.com/@fotonium?utm_source=medium&amp;utm_medium=referral">Akhilesh Sharma</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Writing and deploying serverless applications has never been easier, especially on <a href="https://cloud.google.com/gcp?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=na-US-all-en-dr-bkws-all-all-trial-e-dr-1605212&amp;utm_content=text-ad-none-any-DEV_c-CRE_491349594127-ADGP_Desk+%7C+BKWS+-+EXA+%7C+Txt+_+Google+Cloud+Platform+Core-KWID_43700060017921809-kwd-87853815&amp;utm_term=KW_gcp-ST_gcp&amp;gclid=CjwKCAjw-vmkBhBMEiwAlrMeF5CEwg3bINXm4o52K9T3ej459FXqqwDLFQXpviQjK0ZQbvUmnzkoUxoCVGAQAvD_BwE&amp;gclsrc=aw.ds&amp;hl=en">Google Cloud Platform</a> (GCP). With a few clicks developers are able to deploy their application to the cloud and then trigger calls in a variety of ways from <a href="https://cloud.google.com/scheduler">Cloud Schedulers</a> and <a href="https://cloud.google.com/pubsub/docs/overview#:~:text=Pub%2FSub%20is%20an%20asynchronous,the%20order%20of%20100%20milliseconds.">Pubsub Subscriptions</a> to <a href="https://cloud.google.com/api-gateway">API Gateways</a>.</p><p>Deploying your resources to GCP seems straightforward until you get a 403 error, <em>permission denied</em>. This error causes frustration as the root cause can be a number of issues, and often the solution requires knowing GCP roles and permissions in an in depth manner. The issue can be caused by the user not having the correct permissions to deploy their services or the services themselves not having the correct permissions to connect to each other.</p><p>Once you have identified the problem you will need to understand what roles have the required permissions, how to apply those roles, and where to apply them. Instead of application developers wasting their time researching GCP documentation, searching stack overflow, or reaching out to devops teams, IAM access should be as automated as much as possible.</p><p>Using the <a href="https://github.com/goblet/goblet">Goblet</a> framework, we are now able to view exactly what permissions are needed to deploy our serverless applications, enable required GCP service API’s, create a new custom role with these permissions, create a service account with this role, and add the correct invoker bindings so that all serverless services can connect to each other.</p><p>Goblet is a python framework for writing serverless applications in GCP with the goal of making it as simple as possible to write and deploy REST applications. Goblet uses simple decorators, similar to flask, to create the necessary configurations and automatically deploy the required services and infrastructure.</p><p>For example, with code below we can deploy a simple cloudfunction that is triggered by a pubsub subscription and a cloud scheduler. Goblet will also take care of adding the invoker bindings so both the subscription and cloud scheduler will have the permissions needed to actually make the call to the cloudfunction.</p><pre>import logging<br>from goblet import Goblet, goblet_entrypoint<br><br># goblet setup<br>app = Goblet(function_name=&quot;goblet-iam-tutorial&quot;)<br>goblet_entrypoint(app)<br><br># set debug level<br>app.log.setLevel(logging.DEBUG)<br><br># Define resources <br><br># Pubsub Topic<br>app.pubsub_topic(&quot;test&quot;)<br><br># Pubsub Subscription<br>@app.pubsub_subscription(topic=&quot;test&quot;, use_subscription=True)<br>def subscription(data):<br>    return &quot;success&quot;<br><br># Cloud Scheduler<br>@app.schedule(&quot;1 * * * *&quot;)<br>def schedule():<br>    return &quot;success&quot;</pre><p>In the rest of the tutorial we will go over how to write a simple Goblet application, how to enable the required GCP services, how to view the permissions needed to deploy the application, how to create a new custom role with these permissions, and finally how to create a deployment service account with this role. The code used for this tutorial can be found in <a href="https://github.com/premisedata/gcp-tutorials/tree/main/017-goblet-iam">github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VH8QV2ynaYIarHU7glKTw.png" /><figcaption>Visualization of what Resources Goblet Manages</figcaption></figure><h3>Prerequisites</h3><ul><li>GCP Account</li><li>Python environment (&gt;3.8)</li><li><a href="https://cloud.google.com/sdk/docs/install">Gcloud cli</a></li></ul><h3>Getting Started:</h3><p>Before you can deploy an application, be sure you have GCP credentials configured. You should run gcloud auth login and sign in to the desired GCP project.</p><p>Next you will need to install goblet, which can be done by running the commandpip install goblet-gcp .</p><h3>Writing your Application:</h3><p>We will write a simple application that can be triggered by both a Pubsub topic and cron job. Our code will also create the Pubsub topic if it doesn’t already exist. See below for the complete application, which we will write to main.py .</p><pre>import logging<br>from goblet import Goblet, goblet_entrypoint<br><br># goblet setup<br>app = Goblet(function_name=&quot;goblet-iam-tutorial&quot;)<br>goblet_entrypoint(app)<br><br># set debug level<br>app.log.setLevel(logging.DEBUG)<br><br># Define resources <br><br># Pubsub Topic<br>app.pubsub_topic(&quot;test&quot;)<br><br># Pubsub Subscription<br>@app.pubsub_subscription(topic=&quot;test&quot;, use_subscription=True)<br>def subscription(data):<br>    return &quot;success&quot;<br><br># Cloud Scheduler<br>@app.schedule(&quot;1 * * * *&quot;)<br>def schedule():<br>    return &quot;success&quot;</pre><p>Our requirements.txt will contain goblet-gcp .</p><pre>goblet-gcp</pre><p>And finally we will need a .goblet/config.json where we can specify our service accounts for our Pubsub topic and Cloud Scheduler.</p><pre>{<br>    &quot;pubsub&quot;: {<br>        &quot;serviceAccountEmail&quot;: &quot;sa_pubsub@goblet.iam.gserviceaccount.com&quot;<br>    },<br>    &quot;scheduler&quot;: {<br>        &quot;serviceAccount&quot;: &quot;sa_scheduler@goblet.iam.gserviceaccount.com&quot;<br>    }<br>}</pre><p>That is all that is needed for actually writing our application.</p><h3>Enabling Services</h3><p>Before we can deploy our application and the dependent resources, we need to ensure that the required GCP apis are enabled. This can be done by running goblet services check . This will check to see what service API’s are needed for the application code you have written.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*52ZcHVZG3k_nV60LbVZC4g.png" /><figcaption>GCP Service Api’s Required</figcaption></figure><p>If there are some services not enabled you can run goblet services enable and goblet will handle enabling the APIs. Note that it will take a few minutes for the API’s to be enabled.</p><h3>Generating an IAM Policy, an IAM Role, and a Service Account</h3><p>We can view the required permissions needed to deploy our application by using Goblet to generate a deployment IAM policy. This is done by running goblet services autogen_iam . This will create a autogen_iam_role.jsonfile in the .goblet directory.</p><pre>{<br>    &quot;roleId&quot;: &quot;Goblet_Deployment_Role_goblet_iam_tutorial&quot;,<br>    &quot;role&quot;: {<br>        &quot;title&quot;: &quot;Deployment role for goblet-iam-tutorial&quot;,<br>        &quot;description&quot;: &quot;Goblet generated role&quot;,<br>        &quot;includedPermissions&quot;: [<br>            &quot;cloudfunctions.functions.create&quot;,<br>            &quot;cloudfunctions.functions.delete&quot;,<br>            &quot;cloudfunctions.functions.get&quot;,<br>            &quot;cloudfunctions.functions.getIamPolicy&quot;,<br>            &quot;cloudfunctions.functions.list&quot;,<br>            &quot;cloudfunctions.functions.setIamPolicy&quot;,<br>            &quot;cloudfunctions.functions.sourceCodeSet&quot;,<br>            &quot;cloudfunctions.functions.update&quot;,<br>            &quot;cloudfunctions.operations.get&quot;,<br>            &quot;cloudscheduler.jobs.create&quot;,<br>            &quot;cloudscheduler.jobs.delete&quot;,<br>            &quot;cloudscheduler.jobs.get&quot;,<br>            &quot;cloudscheduler.jobs.list&quot;,<br>            &quot;cloudscheduler.jobs.update&quot;,<br>            &quot;pubsub.subscriptions.create&quot;,<br>            &quot;pubsub.subscriptions.delete&quot;,<br>            &quot;pubsub.subscriptions.get&quot;,<br>            &quot;pubsub.subscriptions.list&quot;,<br>            &quot;pubsub.subscriptions.update&quot;,<br>            &quot;pubsub.topics.create&quot;,<br>            &quot;pubsub.topics.delete&quot;,<br>            &quot;pubsub.topics.get&quot;,<br>            &quot;pubsub.topics.list&quot;,<br>            &quot;pubsub.topics.update&quot;<br>        ],<br>        &quot;stage&quot;: &quot;GA&quot;<br>    }<br>}</pre><p>This role contains all the required permissions needed to deploy our application. This is useful if you are using an external service to handle deployments, such as Github Actions, and want to create a service account that has the minimal permissions needed for deployment.</p><p>Goblet can also handle the creation of a custom role based on the IAM policy that was autogenerated, the creation of a deployment service account, and attaching the role to the service account. This is done by running goblet services create_service_account -p PROJECT .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWf4Pvj7aA3ui4VZW4ouVw.png" /><figcaption>Output of running goblet services create_service_account -p PROJECT</figcaption></figure><p>You can now view the service account in the IAM console and verify that the custom deployment role is attached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGIePWWjgWJ_oZphsiz8Mg.png" /><figcaption>Screenshot of the service account created by Goblet</figcaption></figure><h3>Deploying the Application</h3><p>Now that we have enabled the required GCP service API’s and created a custom deployment role and custom deployment service account, we are ready to deploy our application. Now using our custom deployment service account, we can simply run goblet deploy -p PROJECT -l LOCATION .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5U938nVBwIA2YEyxBa36sw.png" /><figcaption>Output of running goblet deploy</figcaption></figure><h3>Triggering the Application</h3><p>You can verify everything is working correctly by submitting a test message in the Pubsub topic, which can be done via the CLI or the cloud console. You can also trigger the Cloud Scheduler manually if you do not want to wait for the cron schedule to trigger a scheduled event.</p><h3>Cleaning up</h3><p>You can easily delete all resources created by running goblet destroy -p PROJECT -l LOCATION . The only resources you will need to delete manually are the service account and custom role.</p><h3>Conclusion</h3><p>Using the <a href="https://github.com/goblet/goblet">Goblet</a> framework, we are now able to view exactly what permissions are needed to deploy our serverless applications, enable required GCP service API’s, create a new custom role with these permissions, create a service account with this role, and add the correct invoker bindings so that all serverless services can connect to each other.</p><p>Check out the full<a href="https://goblet.github.io/goblet/"> Goblet documentation</a> for more information on supported backends, infrastircture, and handlers. If you enjoyed this blog, then check out our other <a href="https://github.com/premisedata/gcp-tutorials">tutorials</a> or explore additional content on our newly launched <a href="https://engineering.premise.com/">engineer blog</a>!</p><p><strong><em>Premise is constantly looking to hire top-tier engineering talent to help us improve our front-end, mobile offerings and cloud infrastructure. Come find out why we’re consistently named among the top places to work in Silicon Valley by visiting our </em></strong><a href="https://bit.ly/3wnTrLn"><strong><em>Careers</em></strong></a><strong><em> page.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1580a97b74" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/easily-manage-iam-policies-for-serverless-rest-applications-in-gcp-with-goblet-f1580a97b74">Easily Manage IAM Policies for Serverless REST Applications in GCP with Goblet</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting a fully Serverless Web-Based Postgres Admin Client on GCP using Pgweb, Cloud Run, & IAP]]></title>
            <link>https://engineering.premise.com/hosting-a-fully-serverless-web-based-postgres-admin-client-on-gcp-using-pgweb-cloud-run-iap-cff0ce8f471b?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cff0ce8f471b</guid>
            <category><![CDATA[cloud-sql]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[pgweb]]></category>
            <category><![CDATA[cloudrun]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 13:17:20 GMT</pubDate>
            <atom:updated>2023-03-06T13:17:20.614Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>By Austen Novis, Staff Software Engineer</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*58nld7no2yd0cYo27UMySA.png" /><figcaption>Pgweb example screenshot</figcaption></figure><p>There are a number of quality Postgres open source administration tools such as <a href="https://www.pgadmin.org/">pgAdmin</a> or <a href="https://dbeaver.io/">DBeaver</a>, but these tools require a persistent server to run. This means that each user needs to install the tool locally and setup their connections, or you need to host the tool in a cloud server, which can get expensive.</p><p>A much cheaper alternative is to use <a href="https://sosedoff.github.io/pgweb/">Pgweb</a>, a lightweight web-based database explorer for PostgreSQL written in Go, and deploy to <a href="https://cloud.google.com/run">Cloud Run</a>. This allows you to utilize a web-based tool, for minimal cost, that can scale for any number of users.</p><p>We will leverage several <a href="https://cloud.google.com/">Google Cloud Platform</a> services for the complete setup starting with a http load balancer to allow for a custom DNS name as well as enable <a href="https://cloud.google.com/iap">Identity Aware Proxy</a> (IAP), which is what we will be using for authentication. We will host the service in Cloud Run and connect directly to CloudSQL using a <a href="https://cloud.google.com/sql/docs/postgres/connect-connectors">CloudSQL connector</a>. You can bypass the load balancer and IAP if you would like to use username and passwords for authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*5hDcCfOoiyrSn0LrE64X8w.png" /><figcaption>Cloud components</figcaption></figure><h3>Cloud Setup</h3><p>The first step is setting up your CloudSQL instance. This can be done via terraform or in the GCP console. The main requirement is that you enable a public ip address, which will allow us to use the CloudSQL Auth proxy to connect our Cloud Run instance to our CloudSQL instance. If this is not possible you can still connect to your CloudSQL instance to Cloud Run through a VPC Connector instead.</p><p>Next we will need to save our database connection credentials in GCP’s <a href="https://cloud.google.com/secret-manager">Secret Manger</a> by creating a new secret called PGWEB_DATABASE_URL in the format of postgres:///DB_NAME?host=/cloudsql/PROJECT:REGION:INSTANCE_NAME&amp;user=DB_USER&amp;password=DB_PASSWORD .</p><p>Now that we have our CloudSQL instance and connection secret we will deploy our Cloud Run instance using the <a href="https://cloud.google.com/sdk/gcloud">gcloud cli</a>. First we will need to push the desired Pgweb container to GCP’s Artifact Registry, which we can do using the following commands.</p><pre>gcloud auth configure-docker us-central1-docker.pkg.dev<br><br>export PROJECT=PROJECT<br><br>docker pull sosedoff/pgweb:0.14.0<br>docker tag sosedoff/pgweb:0.14.0  us-central1-docker.pkg.dev/$PROJECT/cloud-run-source-deploy/pgweb:0.14.0<br>docker push us-central1-docker.pkg.dev/$PROJECT/cloud-run-source-deploy/pgweb:0.14.0</pre><p>Next you can run the following gcloud command to deploy your Cloud Run instance. You will need to replace the following variables (PROJECT, SERVICE_ACCOUNT, INSTANCE_NAME).</p><pre>export PROJECT=PROJECT<br>export SERVICE_ACCOUNT=SERVICE_ACCOUNT<br>export INSTANCE_NAME=INSTANCE_NAME<br><br>gcloud alpha run deploy pgweb --set-secrets PGWEB_DATABASE_URL=PGWEB_DATABASE_URL:latest --no-allow-unauthenticated --project=$PROJECT --region=us-central1 --platform managed --service-account=$SEVICE_ACCOUNT --min-instances=1 --max-instances=1 --port=8081 --image=us-central1-docker.pkg.dev/$PROJECT/cloud-run-source-deploy/pgweb:0.14.0 --set-cloudsql-instances=$PROJECT:us-central1:$INSTANCE_NAME</pre><p>Note that your service account will need CloudSQL user permissions for your instance. The min instance is set to 1 to make sure that an instance is always running.</p><p>The next step is deploying the HTTP Load Balancer. This can be deploying in the console, by selecting a global load balancer and creating a route to your Cloud Run instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9m8iArjHLSw8wpFpu3uUHQ.png" /><figcaption>Load Balancer Sceenshot</figcaption></figure><p>Once this is created you will need to go to the IAP page in the GCP console and enable IAP on your http load balancer. If this is your first time using IAP you will need to follow the IAP setup steps, which requires adding a firewall rule to your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1zRjutMjs4IcjY2DQTH6A.png" /><figcaption>IAP Screenshot</figcaption></figure><p>In order to grant users permission to Pgweb, you will need to grant specific users <strong>IAP-Secured Web App User </strong>permission in IAP.</p><p>An additional step to make it easier on users to access is to setup a DNS record to point to your load balancer. For example you can create a pgweb.DOMAIN.com DNS record to point to the ip address of your load balancer.</p><h3>Conclusion</h3><p>We now have a way to deploy a lightweight web-based database explorer for PostgreSQL hosted on Cloud Run. This is great for rapid development and keeping costs low.</p><p>If you enjoyed this blog, then check out our other <a href="https://github.com/premisedata/gcp-tutorials">tutorials</a> or explore additional content on our newly launched <a href="https://engineering.premise.com/">engineer blog</a>!</p><p><strong><em>Premise is constantly looking to hire top-tier engineering talent to help us improve our front-end, mobile offerings and cloud infrastructure. Come find out why we’re consistently named among the top places to work in Silicon Valley by visiting our </em></strong><a href="https://bit.ly/3wnTrLn"><strong><em>Careers</em></strong></a><strong><em> page.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cff0ce8f471b" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/hosting-a-fully-serverless-web-based-postgres-admin-client-on-gcp-using-pgweb-cloud-run-iap-cff0ce8f471b">Hosting a fully Serverless Web-Based Postgres Admin Client on GCP using Pgweb, Cloud Run, &amp; IAP</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCP Alerts the Easy Way: Alerting for Cloudfunctions and Cloudrun using Goblet.]]></title>
            <link>https://engineering.premise.com/gcp-alerts-the-easy-way-alerting-for-cloudfunctions-and-cloudrun-using-goblet-62bdf2126ef6?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/62bdf2126ef6</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[alerts]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 21:32:57 GMT</pubDate>
            <atom:updated>2023-01-24T21:32:57.211Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>By Austen Novis, Staff Software Engineer</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pKuV4BjC3GTAv9lu" /><figcaption>Photo by <a href="https://unsplash.com/@scottrodgerson?utm_source=medium&amp;utm_medium=referral">Scott Rodgerson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://cloud.google.com/">Google Cloud Platform’s</a> <a href="https://cloud.google.com/monitoring">monitoring</a> and <a href="https://cloud.google.com/monitoring/alerts">alerting</a> toolings are quite powerful, but require time to learn and setup correctly. Oftentimes, monitoring and alerting are setup separately from the application using tools like <a href="https://www.terraform.io/">terraform</a> or even managed by separate centralized infrastructure teams. This requires application developers to learn new tools and skillsets, or offload the work to other teams, which reduces visibility and access to the alerting systems that they depend on to develop and maintain a healthy application.</p><p>The solution is to enable application developers to write, manage, and deploy their alerting policies using the same processes and in the same codebase as their application. This is accomplished by leveraging the <a href="https://github.com/goblet/goblet">Goblet</a> framework and the recently added alert resource.</p><p>Goblet is a python framework for writing serverless applications in GCP with the goal of making it as simple as possible to write and deploy REST applications. Goblet uses simple decorators, similar to flask, to create the necessary configurations and automatically deploy the required services and infrastructure.</p><p>For example, with following code we can deploy a simple application as well as an alert we want to monitor.</p><pre>from goblet import Goblet, jsonify, goblet_entrypoint<br><br>app = Goblet(function_name=&quot;goblet_example&quot;)<br><br>app.alert(&quot;metric&quot;,conditions=[MetricCondition(&quot;execution_count&quot;, metric=&quot;cloudfunctions.googleapis.com/function/execution_count&quot;, value=1000)])<br><br>@app.http()<br>def main(request):<br>    return jsonify(request.json)</pre><p>Next we will go over how to write and deploy a simple goblet application that contains not only the application logic, but also the logic to deploy a metric alert, a log based alert, and a custom metric based alert.</p><h3>Prerequisites</h3><ul><li>GCP Account</li><li>Python environment (&gt;3.7)</li><li><a href="https://cloud.google.com/sdk/docs/install">Gcloud cli</a></li></ul><h3>Getting Started:</h3><p>Before you can deploy an application, be sure you have credentials configured. You should run gcloud auth login and sign in to the desired project. Make sure to have the correct services enabled in your GCP project which include</p><ul><li>Cloud Build</li><li>Cloud Functions</li><li>Cloud Monitoring</li><li>Cloud Alerting</li></ul><p>Next you will need to install goblet, which can be done by running the commandpip install goblet-gcp .</p><h3>Writing your Application and Alerts:</h3><p>To get started we will clone the <a href="https://github.com/premisedata/gcp-tutorials">tutorial repo</a> and navigate to the folder <em>012-backend-alerts</em>, which contains <em>main.py</em> where the core logic is contained, a <em>.goblet/config.json</em> file where the alerts notification channels can be set, a <em>requirements.txt </em>file.</p><p>Our sample <em>main.py</em><strong><em> </em></strong>file contains the logic to deploy a simple cloudfunction as well as 3 different alerts. One alert will trigger off of the metric condition <em>execution_times </em>with a threshold of 1000ms. The second alert will trigger off of any matched log that contains an error severity. The third alert will trigger off of a custom metric based on logged errors with a threshold of 1. This custom metric is defined in code and will be created and deployed by goblet together with the other alerts.</p><p>In additional we will be deploying a simple http goblet application that allows us to trigger various errors based on the headers we pass in the request for testing purposes.</p><pre>from goblet import Goblet, goblet_entrypoint, Response<br>from goblet.infrastructures.alerts import (<br>    MetricCondition,<br>    LogMatchCondition,<br>    CustomMetricCondition,<br>)<br>import logging<br>import time<br><br>app = Goblet(function_name=&quot;example-cloudfunction-alerts&quot;)<br>goblet_entrypoint(app)<br><br>app.log.setLevel(logging.DEBUG)  # configure goblet logger level<br><br># Example Metric Alert for the cloudfunction metric execution_times with a threshold of 1000 ms<br>app.alert(<br>    &quot;metric&quot;,<br>    conditions=[<br>        MetricCondition(<br>            &quot;test&quot;,<br>            metric=&quot;cloudfunctions.googleapis.com/function/execution_times&quot;,<br>            value=1000,<br>            aggregations=[<br>                {<br>                    &quot;alignmentPeriod&quot;: &quot;300s&quot;,<br>                    &quot;crossSeriesReducer&quot;: &quot;REDUCE_NONE&quot;,<br>                    &quot;perSeriesAligner&quot;: &quot;ALIGN_PERCENTILE_50&quot;,<br>                }<br>            ],<br>        )<br>    ],<br>)<br><br># Example Log Match metric that will trigger an incendent off of any Error logs<br>app.alert(&quot;log-error&quot;, conditions=[LogMatchCondition(&quot;error&quot;, &quot;severity&gt;=ERROR&quot;)])<br><br># Example Metric Alert that creates a custom metric for errors and creates an alert with a threshold of 2<br>app.alert(<br>    &quot;custom-error&quot;,<br>    conditions=[<br>        CustomMetricCondition(<br>            &quot;custom&quot;,<br>            metric_filter=&quot;severity=(ERROR OR CRITICAL OR ALERT OR EMERGENCY)&quot;,<br>            value=2,<br>        )<br>    ],<br>)<br><br><br>@app.http()<br>def main(request):<br>    # Set a delay<br>    delay = app.current_request.headers.get(&quot;X-DELAY&quot;, 0)<br>    time.sleep(int(delay))<br><br>    # Raise error<br>    error = app.current_request.headers.get(&quot;X-ERROR&quot;, None)<br>    if error:<br>        app.log.error(&quot;ERROR&quot;)<br>        return Response(&quot;ERROR&quot;, status_code=500)<br><br>    return &quot;200&quot;<br></pre><h3>Deploying your Cloudfunction and Alerts:</h3><p>Deploying your Cloud Run jobs is as simple as running one command.</p><pre>goblet deploy -p PROJECT -l REGION</pre><p>If you would like to associate your alerts with a notification channel you can specify a channel in .goblet/config.json .</p><pre>{<br>    &quot;alerts&quot;:{<br>        &quot;notification_channels&quot;: [&quot;projects/PROJECT/notificationChannels/CHANNEL_ID&quot;]<br>    }<br>}</pre><p>If you do not wish to assign any notification channels you can remove this section.</p><p>If you would like different channels for different alerts you can also pass them directly into the alert decorator.</p><pre>app.alert(&quot;metric&quot;,notification_channels=[&quot;projects/PROJECT/notificationChannels/CHANNEL_ID&quot;], conditions=[MetricCondition(&quot;test&quot;, metric=&quot;cloudfunctions.googleapis.com/function/execution_times&quot;, value=1000)])</pre><p>You can view that your alerts are deployed correctly, by looking at the <a href="https://console.cloud.google.com/monitoring/alerting/policies">GCP monitoring console</a>, which should look like the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*v-zlT0enrz8OAqhrLHuMhw.png" /><figcaption>Screenshot of Deployed Alerts</figcaption></figure><p>Clicking into an alert will show the metrics associated with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNlbQ6I7bf9x4lVX7AqpqA.png" /><figcaption>Screenshot of Alert Policy</figcaption></figure><h3>Testing:</h3><p>Now we will test that the alerts are properly deployed and triggering correctly. All we will need is the url of the cloudfunction you deployed and then make several requests.</p><p>First we will test the regular metric based alert by sending a get request with the header X-DELAY=3 . Note that because this metric is based on a rolling window there will be delay until an incident is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c58pl4JBadXZoOj3SX_Csg.png" /><figcaption>Triggered Metric Alert</figcaption></figure><p>Next we can trigger the log alert by sending a request with the header X-ERROR=true. Since this is triggered off of any log match this will create an incident immediately .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNPwNsZns-oDOj-KeAt4Ow.png" /><figcaption>Triggered Log Alert</figcaption></figure><p>Sending this request a second time will trigger the custom metric based alert. Make sure you send the follow up requests quickly after each other since this alerts triggers based on reaching the threshold in a 1 min time window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhofPx7SbffjoKsL61dsuw.png" /><figcaption>Triggered Custom Metric Alert</figcaption></figure><p>You can view that these alerts are triggered in the GCP console.</p><h3>Cleaning up your Cloudfunction and Alerts:</h3><p>To cleanup all deployed resources, including the Cloudfunction, alerts, and custom metric you can run the goblet destroy command.</p><pre>goblet destroy -p PROJECT -l REGION</pre><h3>Conclusion</h3><p>We now have a powerful way to develop, deploy, and manage our application alerts using Goblet without needing to learn any new tools or depend on any external teams. Feel free to customize your alerts to fit your needs and let us know if you have any suggestions for improvements. Check out the full<a href="https://goblet.github.io/goblet/"> Goblet documentation</a> for more information on supported backends and triggers. If you enjoyed this blog, then check out our other <a href="https://github.com/premisedata/gcp-tutorials">tutorials</a> or explore additional content on our newly launched <a href="https://engineering.premise.com/">engineer blog</a>!</p><p><strong><em>Premise is constantly looking to hire top-tier engineering talent to help us improve our front-end, mobile offerings and cloud infrastructure. Come find out why we’re consistently named among the top places to work in Silicon Valley by visiting our </em></strong><a href="https://bit.ly/3wnTrLn"><strong><em>Careers</em></strong></a><strong><em> page.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62bdf2126ef6" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/gcp-alerts-the-easy-way-alerting-for-cloudfunctions-and-cloudrun-using-goblet-62bdf2126ef6">GCP Alerts the Easy Way: Alerting for Cloudfunctions and Cloudrun using Goblet.</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Deploying Cloud Run Jobs]]></title>
            <link>https://engineering.premise.com/tutorial-deploying-cloud-run-jobs-9435466b26f5?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9435466b26f5</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 19:49:30 GMT</pubDate>
            <atom:updated>2022-11-28T14:21:31.453Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>By Austen Novis, Staff Software Engineer</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78dpDB60OOO5mZIj7XBnoA.png" /><figcaption>Cloud Run Jobs UI</figcaption></figure><p><a href="https://cloud.google.com/run/docs/create-jobs">Cloud Run jobs</a> are a new way to execute code in containers on the <a href="https://cloud.google.com/gcp?hl=en">Google Cloud Platform</a> (GCP), and are a good fit for containers that run to completion and don’t serve requests. For example, processing records from a database, processing a list of files from a Cloud Storage bucket, or a long-running operation, such as calculating Pi.</p><p>In order to deploy a Cloud Run job, developers will need to perform several steps to capture the configuration needed to run the job including the container image, region, and environment variables. The job can be configured to run on a schedule or executed manually in the console or via cli.</p><p>While Cloud Run jobs open up a lot of possibilities, we found that the development, deployment, and management of jobs natively on GCP requires several steps and a steep learning curve. In this tutorial, we will walk through an simpler and more efficient way to manage your jobs, by using the open source python framework <a href="https://github.com/goblet/goblet">goblet</a>, which already has support for <a href="https://cloud.google.com/run">Cloudrun</a> and <a href="https://cloud.google.com/functions">Cloudfunction</a> backends and various triggers such as <a href="https://cloud.google.com/scheduler">Scheduler</a>, <a href="https://cloud.google.com/pubsub">Pubsub</a>, and <a href="https://cloud.google.com/eventarc/docs">Eventarc</a>.</p><p>Instead of learning various <a href="https://cloud.google.com/sdk/gcloud">gcloud</a> commands, and figuring out how to build your container, you can develop and deploy your job, by simply writing python code.</p><p>This tutorial will walk you through the steps to develop and deploy your own Cloud Run job in minutes.</p><h3>Prerequisites:</h3><ul><li>GCP Account</li><li>Python environment (&gt;3.7)</li><li><a href="https://cloud.google.com/sdk/docs/install">Gcloud cli</a></li></ul><h3>Getting Started:</h3><p>Before you can deploy an application, be sure you have credentials configured. You should run gcloud auth login and sign in to the desired project. Make sure to have the correct services enabled in your GCP project which include</p><ul><li>Cloud Build</li><li>Cloud Run</li><li>Artifact Registry</li><li>Cloud Scheduler (for scheduled jobs)</li></ul><p>Next you will need to install goblet, which can be done by running the commandpip install goblet-gcp</p><h3>Writing your Cloud Run Job:</h3><p>To get started we will clone the <a href="https://github.com/premisedata/gcp-tutorials">tutorial repo</a> and navigate to the folder <a href="https://github.com/premisedata/gcp-tutorials/tree/main/010-cloudrun-jobs"><em>010-cloudrun-jobs</em></a>, which contains <em>main.py</em> where the core job logic is contained, a <em>.goblet/config.json</em> file where the cloudrun job configuration can be set, a <em>requirements.txt </em>file and a <em>Dockerfile</em>.</p><p>Our sample <em>main.py</em><strong><em> </em></strong>file contains the logic to deploy 2 different Cloudrun jobs.</p><p>The first job test, consists of two tasks that run in parallel and log different statements. Tasks are differentiated by passing in different a task_id to a job with the same name. Note that task ids start at 0.</p><p>The second job test-schedule, is a scheduled job that runs every minute, and can be customized with the schedule argument. In order for the schedule to work you will need to set a service account in the <em>.goblet/config.json </em>under the key scheduler .</p><pre>from goblet import Goblet, goblet_entrypoint<br>import logging</pre><pre>app = Goblet(function_name=&quot;example-job&quot;, backend=&quot;cloudrun&quot;)<br>goblet_entrypoint(app)<br>app.log.setLevel(logging.DEBUG)  # configure goblet logger level</pre><pre><a href="http://twitter.com/app">@app</a>.job(&quot;test&quot;)<br>def job1_task_1(id):<br>    app.log.info(f&quot;execution test {id}&quot;)<br>    return &quot;200&quot;</pre><pre><a href="http://twitter.com/app">@app</a>.job(&quot;test&quot;, task_id=1)<br>def job2_task_2(id):<br>    app.log.info(f&quot;second task {id}&quot;)<br>    return &quot;200&quot;</pre><pre><a href="http://twitter.com/app">@app</a>.job(&quot;test-schedule&quot;, schedule=&quot;* * * * *&quot;)<br>def job2(id):<br>    app.log.info(f&quot;execution every min&quot;)<br>    return &quot;200&quot;</pre><h3>Running your Cloud Run Job Locally:</h3><p>You can test your jobs locally by using the goblet cli.</p><pre>goblet job run FUNCTION_NAME-JOB_NAME TASK_ID</pre><p>In our example if we wanted to execute job1_task_1 we would run goblet job run example-job-test 1</p><h3>Deploying your Cloud Run Job:</h3><p>Deploying your Cloud Run jobs is as simple as running one command.</p><pre>goblet deploy -p PROJECT -l REGION</pre><p>By default cloud run will assume there is an artifact registry called <em>cloud-run-source-deploy</em>. You can specify a custom registry by setting the <em>artifact_registry </em>field in the <em>cloudbuild</em> section of the <em>config.json </em>file.</p><pre>{<br>   “cloudbuild”:{<br>     “artifact_registry”: “location-docker.pkg.dev/gcp_project/artifact/image”<br>   }<br>}</pre><p>After running the goblet deploy command, you will see both jobs deployed in the console under the jobs tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Gc5MkxZl3wjnR77aQVXVw.png" /><figcaption>Deployed Cloud Run Jobs</figcaption></figure><p>The scheduled job will begin executing every minute as soon as it is deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R76_5KIVlpdXAs50ArXAkg.png" /><figcaption>Cloud Scheduler Job that is created by Goblet</figcaption></figure><p>To execute the first job example-job-test you will need to click into the job in the console and click execute (or trigger the job via the gcloud cli). You can then click on the job execution to view logs for all tasks, which in our case consists of task 0 and task 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78dpDB60OOO5mZIj7XBnoA.png" /><figcaption>Cloud Run Job Execution</figcaption></figure><h3>Cleaning up your Cloud Run Job:</h3><p>To cleanup all deployed resources, including the Cloud Run jobs and Cloud Scheduled job you can run the goblet destroy command.</p><pre>goblet destroy -p PROJECT -l REGION</pre><h3>Conclusion:</h3><p>We now have a powerful way to develop, deploy, and manage our Cloud Run jobs using goblet. Feel free to customize your jobs to fit your needs and let us know if you have any suggestions for improvements. Check out the full<a href="https://goblet.github.io/goblet/"> goblet documentation</a> for more information on supported backends and triggers. If you enjoyed this blog, then check out our other <a href="https://github.com/premisedata/gcp-tutorials">tutorials</a> or explore additional content on our newly launched <a href="https://engineering.premise.com/">engineer blog</a>!</p><p><strong><em>Premise is constantly looking to hire top-tier engineering talent to help us improve our front-end, mobile offerings and cloud infrastructure. Come find out why we’re consistently named among the top places to work in Silicon Valley by visiting our </em></strong><a href="https://bit.ly/3wnTrLn"><strong><em>Careers</em></strong></a><strong><em> page.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9435466b26f5" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/tutorial-deploying-cloud-run-jobs-9435466b26f5">Tutorial: Deploying Cloud Run Jobs</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Python APIs made simple on GCP with Goblet backed by Cloud Functions and Cloud Run]]></title>
            <link>https://engineering.premise.com/serverless-apis-made-simple-on-gcp-with-goblet-backed-by-cloud-functions-and-cloud-run-730db2da04ba?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/730db2da04ba</guid>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[cloudrun]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 18:53:35 GMT</pubDate>
            <atom:updated>2022-11-22T18:19:54.575Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>By Austen Novis, Staff Software Engineer</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bcuuxyp56BWuj2Fe" /><figcaption>User and Goblet Managed Resources</figcaption></figure><p>REST API’s have become the foundation layer in most companies to expose data between services and clients. The goal therefore is to standardize the creation and operation of these API’s and increase the speed to deployment. To address these concerns <a href="https://cloud.google.com/">Google Cloud Platform</a> (GCP) offers a fully managed <a href="https://cloud.google.com/api-gateway">API Gateway</a> service. With API Gateway, you can create, secure, and monitor APIs for various Google Cloud serverless back ends that include <a href="https://cloud.google.com/functions">Cloud Functions</a> and <a href="https://cloud.google.com/run">Cloud Run</a>. API Gateway allows you to standardize your API’s in a simple and reusable manner and includes many powerful features such as built-in authentication and key validation with direct integration with firebase auth.</p><p>One downside to using an API Gateway together with other GCP serverless services is that they require significant configuration to set up properly. For example, an API Gateway requires an <a href="https://swagger.io/docs/specification/about/">OpenAPI Spec</a>, an API resource, an API config resource, and a gateway resource. This does not even include setting up the connections to your serverless backends, and other common integrations such as <a href="https://cloud.google.com/scheduler">Cloud Scheduler</a> and <a href="https://cloud.google.com/pubsub">PubSub</a> topics.</p><p>This is where <a href="https://github.com/anovis/goblet">Goblet</a> comes in to help. Goblet is a python framework for writing serverless applications in GCP with the goal of making it as simple as possible to write and deploy REST applications. Goblet uses simple decorators, similar to flask, to create the necessary configurations and automatically deploy the required services. Goblet will also handle the deployment of any updates to your source code or GCP service dependencies without any downtime to your application.</p><p>For example, below is a complete application that deploys API Gateway endpoints for the routes /hello, hello/{person}, /bye , a Scheduler Job that triggers on the cron schedule * * * * *, and a PubSub Subscription that pushes events from the hello-events PubSub Topic to the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*XK5CBTytuq1S6vVnCTl_Pg.png" /><figcaption>Example Goblet Application</figcaption></figure><p>This application requires the deployment of many different GCP resources (see below diagram), which all need to be deployed in the correct order to ensure proper configuration. Goblet is able to deduce what needs to be deployed simply based on the Python API code and automates the most difficult and tedious aspects of the deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bcuuxyp56BWuj2Fe" /><figcaption>User and Goblet Managed Resources</figcaption></figure><p>Simply run goblet deploy -p PROJECT -l LOCATION and all of your API Gateway resources, Cloud Scheduler, and PubSub Subscriptions will be deployed!</p><p>Goblet originally only had support for Cloud function backends, but we realized as services scaled and changed, we wanted the option to move some services to Cloud Run, which is able to handle larger volumes. However, we did not want to change our code or deployment pipelines. Luckily, Cloud Functions are backed by google’s function-framework which is able to easily port to any containerized solution. This allows us to change one simple config in our python code and Goblet is able to deploy to a completely different backend!</p><p>Not only does the deployment handle a different serverless backend, but most of the integrations with other GCP services work with both backends as well. For example, let’s assume the same application discussed earlier that handled various routes, scheduled jobs, and PubSub events and would like to migrate to Cloud Run to handle the increased scale. You would be able to reuse all the same source code and cicd pipelines and simply change the desired backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*92BbIzZpRvgjB8Aw" /><figcaption>Setting a Goblet backend</figcaption></figure><p>Goblet then propagates any necessary changes in GCP infrastructure. Since API Gateway is still being used to do the routing, no changes on the DNS or Load Balancer level would need to be made. End users wouldn’t even know the change occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kYCfyODxE_ujy9w6" /></figure><h3>Conclusion</h3><p>In this blog post we have gone through a simple example, showing how a few lines of Python code can configure and deploy a fully functioning restful API backed by a Cloud Function. Then with a simple code change we are able to deploy the exact same API to Cloud Run!</p><p>For advanced configuration options such as authentication and scheduling check out the <a href="https://goblet.github.io/goblet/">documentation</a> and if you have any comments, issues, or feedback feel free to open a <a href="https://github.com/anovis/goblet/issues">ticket</a> on GitHub. <a href="https://github.com/anovis/goblet">Goblet</a> is still in active development so if you have suggestions for features you would like to see feel free to submit an issue as well or comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=730db2da04ba" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/serverless-apis-made-simple-on-gcp-with-goblet-backed-by-cloud-functions-and-cloud-run-730db2da04ba">Serverless Python APIs made simple on GCP with Goblet backed by Cloud Functions and Cloud Run</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Managing Serverless GCP Load Balancers Dynamically with Terraform]]></title>
            <link>https://engineering.premise.com/tutorial-managing-serverless-gcp-load-balancers-dynamically-with-terraform-e15751853312?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e15751853312</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[load-balancer]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 14:20:42 GMT</pubDate>
            <atom:updated>2021-12-14T14:20:42.848Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>By Austen Novis, Software Engineer</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sn_9RAFoVwv7oSC2" /><figcaption>Photo by <a href="https://unsplash.com/@__itsflores?utm_source=medium&amp;utm_medium=referral">Omar Flores</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://cloud.google.com/">Google Cloud Platform</a> (GCP) offers support for many different serverless services that include <a href="https://cloud.google.com/appengine">App Engine</a>, <a href="https://cloud.google.com/run">Cloudrun</a>, <a href="https://cloud.google.com/functions">Cloudfunctions</a>, and <a href="https://cloud.google.com/api-gateway">Api Gateway</a>. Each service has its pros and cons and often companies will host applications in multiple if not all of these services. One difficulty in managing multiple different types of services is maintaining a robust networking layer.</p><p>The simplest solution for managing your networking layer is to not use a load balancer at all and instead call each service directly. While this solution is certainly the easiest, there are many problems, especially if you would like to migrate an application to a new backend service since it would require updating all references to its service name in external applications that make calls to that service. Additionally, GCP’s global load balancers offer many important features that include DDOS protection, rate limiting and throttling, and improved network latency, that make it a no-brainer to use.</p><p>Another option to manage the networking layer for serverless is to create a load balancer for each application in each backend service, with its own unique DNS address. The benefit of this approach is that it is easy to update and manage each service as they are all maintained independently. However, as the number of services grow, maintaining individual load balancers, certifications, and DNS records can become a significant operations problem.</p><p>Alternatively, the approach that we at <a href="https://www.premise.com/">Premise</a> took is to maintain one single load balancer that then routes requests to all of our individual services. The difficulty with this approach is that the singular load balancer can become quite complex and tough to maintain. To solve this problem, we leveraged <a href="https://registry.terraform.io/modules/GoogleCloudPlatform/lb-http/google/latest/submodules/serverless_negs">Terraform’s GCP serverless load balancer module</a> combined with <a href="https://www.terraform.io/docs/language/expressions/dynamic-blocks.html">dynamic blocks</a>. The result is a simple, scalable, and customizable solution to maintain a singular load balancer for any number of serverless applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYup-bB00dqfB1gZPZMZBw.png" /><figcaption>Dynamic Serverless Load Balancer Diagram</figcaption></figure><p>This tutorial will go step by step into the different pieces of the Terraform script required to deploy and maintain a dynamic serverless load balancer. We will begin with installing and setting up Terraform, followed up by setting local variables. Next we will dive into the different dynamic blocks, and illustrate different options to further customize your load balancer resources. Finally we will end with future work and how we plan on expanding this load balancer in the future, including several Terraform pull requests we have in progress.</p><p>The code for this tutorial can be found in our <a href="https://github.com/premisedata/gcp-tutorials/tree/main/004-dynamic-serverless-loadbalancer">gcp-tutorials</a> GitHub repository.</p><h3>Getting Started</h3><p>Getting up and running with Terraform is quick and easy. To install, simply <a href="https://www.terraform.io/downloads.html">download</a> from the Terraform website. Now to get started you will need to setup your Terraform provider, which will be google in our case and Terraform backend, which is where your Terraform state file will be saved to. The easiest way is to have Terraform saved locally using a local backend.</p><pre><em>provider “google” {}</em></pre><pre><em>terraform {</em></pre><pre><em>  backend “local” {}</em></pre><pre><em>}</em></pre><p>Once you have verified it working locally you should store your state file in GCS using the gcs backend.</p><pre><em>provider “google” {}</em></pre><pre><em>terraform {</em></pre><pre><em>backend “gcs” {</em></pre><pre><em>  bucket = “tf-state”</em></pre><pre><em>  prefix = “lb”</em></pre><pre><em>  }</em></pre><pre><em>}</em></pre><p>The first command you will need to run is terraform init which will install the google provider libraries. You will need to run this command later one once we have defined our modules later on in this tutorial, but for now you are up and running with Terraform!</p><h3>Setting Local Variables</h3><p>The next step is setting up local variables, which will make it easy to add new backend services as well as maintain multiple load balancers for different environments such as for development and production. We use locals, but you can certainly use regular Terraform variables as well. The main variables used are domain, project, region, environment, and services. The services variable is the only place required to define your different backends and any customizations required. The rest of the Terraform script will dynamically create all resources based on what you have defined in services.</p><p>For example, the example definition below will create a load balancer with paths to three different services with the paths DOMAIN.com/service1/*<strong><em> </em></strong>that will route to an app engine backend, DOMAIN.com/service2/* that will route to an additional app engine backend, and DOMAIN.com/service3/*<strong><em> </em></strong>that will route to a cloudrun backend. All three of these routes have path_prefix_rewiting set so the applications themselves do not need to have any logic to handle the incoming base paths.</p><p>To extend this Terraform script you would be able to add additional fields to each service and use dynamic blocks to either further customize currently defined resources or even create additional resources such as cloud armor security policies.</p><pre>locals {<br>  domain        = &quot;DOMAIN.COM&quot;<br>  project       = &quot;PROJECT&quot;<br>  region        = &quot;REGION&quot;<br>  env           = &quot;dev&quot;<br>  services = [<br>    {<br>      &quot;service&quot; : &quot;service1&quot;,<br>      &quot;type&quot; : &quot;app_engine&quot;,<br>      &quot;path&quot; : &quot;/service1/*&quot;,<br>      &quot;path_prefix_rewrite&quot; : &quot;/&quot;<br>    },<br>    { <br>      &quot;service&quot; : &quot;service2&quot;,<br>      &quot;type&quot; : &quot;app_engine&quot;,<br>      &quot;path&quot; : &quot;/service2/*&quot;,<br>      &quot;path_prefix_rewrite&quot; : &quot;/&quot;<br>    },    <br>    {<br>      &quot;service&quot; : &quot;service3&quot;,<br>      &quot;type&quot; : &quot;cloud_run&quot;,<br>      &quot;path&quot; : &quot;/service3/*&quot;,<br>      &quot;path_prefix_rewrite&quot; : &quot;/&quot;<br>    }<br>  ]<br>}</pre><h3>Dynamic Serverless Network Endpoint Groups</h3><p>We can keep all of our logic in the services local variable because we utilize dynamic blocks in various Terraform resources, with the first example in the google_compute_region_network_endpoint_group<strong><em>. </em></strong>Here we use a for_each statement, to iterate through each service and then use a dynamic block to set values for app_engine or cloudrun since only one type can be set at a time in this resource.</p><pre>resource &quot;google_compute_region_network_endpoint_group&quot; &quot;neg&quot; {<br>  for_each              = { for service in local.services : &quot;${service.service}&quot; =&gt; service }</pre><pre>  name                  = &quot;${each.value.service}-${local.env}&quot;</pre><pre>  network_endpoint_type = &quot;SERVERLESS&quot;<br>  region                = local.region<br>  project               = local.project</pre><pre>dynamic &quot;app_engine&quot; {<br>    for_each = each.value.type == &quot;app_engine&quot; ? [{ &quot;service&quot; : each.value.service }] : []<br>    content {<br>      service = app_engine.value.service<br>    }<br>  }</pre><pre>dynamic &quot;cloud_run&quot; {<br>    for_each = each.value.type == &quot;cloud_run&quot; ? [{ &quot;service&quot; : each.value.service }] : []<br>    content {<br>      service = cloud_run.value.service<br>    }<br>  }</pre><pre>}</pre><h3>Dynamic Compute URL Map</h3><p>We again utilize dynamic blocks to generate path rules for each of our services and take it one step further with an additional nested dynamic block to further customize our path rules. In the example below, we have a nested dynamic path_rule block that allows us to customize the path rule for each service. In this case we just have a customization option for path_prefix_rewrite, but it is easy to extend and add other customization options based on the services definitions you provide in the local variable.</p><pre>resource &quot;google_compute_url_map&quot; &quot;url-map&quot; {<br>  name        = &quot;${local.env}-url-map&quot;<br>  description = &quot;${local.env}  url mapping for ${local.domain}&quot;<br>  project     = local.project</pre><pre>  default_service = module.lb-http.backend_services[&quot;default&quot;].self_link</pre><pre>host_rule {<br>    hosts        =  [${local.env}.${local.domain}.${local.domain_suffix}&quot;]<br>    <br>    path_matcher = &quot;main&quot;<br>  }<br>  path_matcher {<br>    name            = &quot;main&quot;<br>    default_service = module.lb-http.backend_services[&quot;default&quot;].self_link</pre><pre>dynamic &quot;path_rule&quot; {<br>      for_each = local.services<br>      content {<br>        paths   = [path_rule.value.path]<br>        service = module.lb-http.backend_services[path_rule.value.service].self_link<br>        dynamic &quot;route_action&quot; {<br>          for_each = can(path_rule.value.path_prefix_rewrite) ? [{ &quot;path_prefix_rewrite&quot; : path_rule.value.path_prefix_rewrite }] : []<br>          <br>           content {<br>            url_rewrite {<br>              path_prefix_rewrite = route_action.value.path_prefix_rewrite<br>            }<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><h3>Serverless Loadbalancer</h3><p>Finally you will need to define your serverless load balancer using the source GoogleCloudPlatform/lb-http/google//modules/serverless_negs and reference the resources created above. This is done by first referencing the url-map<em> </em>resource and then using a for loop in the backends section of the load balancer to iterate through each service. During each iteration you will reference the service group using google_compute_region_network_endpoint_group.neg[serviceObj.service].self_link<strong><em> </em></strong>to dynamically select each service endpoint group resource and retrieve its self link.</p><pre>module &quot;lb-http&quot; {<br>  source  = &quot;GoogleCloudPlatform/lb-http/google//modules/serverless_negs&quot;<br>  <br>  version = &quot;~&gt; 6.1.1&quot;<br>  name    = &quot;${local.env}-${local.domain}&quot;<br>  project = local.project</pre><pre>  ssl                             = true<br>  managed_ssl_certificate_domains = [${local.env}.${local.domain}.${local.domain_suffix}&quot;]<br>  <br>  https_redirect                  = true<br>  create_url_map                  = false<br>  url_map                         = google_compute_url_map.url-map.self_link</pre><pre>backends = {<br>    for serviceObj in local.services :<br>    serviceObj.service =&gt; {<br>      description = serviceObj.service<br>      groups = [<br>        {<br>          group = google_compute_region_network_endpoint_group.neg[serviceObj.service].self_link<br>        }<br>      ]<br>      enable_cdn              = false<br>      security_policy         = null<br>      custom_request_headers  = null<br>      custom_response_headers = null<br>      timeout_sec             = 300</pre><pre>     iap_config = {<br>        enable               = false<br>        oauth2_client_id     = &quot;&quot;<br>        oauth2_client_secret = &quot;&quot;<br>      }<br>      log_config = {<br>        enable      = false<br>        sample_rate = null<br>      }<br>    }<br>  }<br>}</pre><h3>Deploying your Load balancer</h3><p>Once you have defined all of your Terraform resources you can test your configuration using terraform plan , which will show all resources that will be created.</p><p>Once you verified that your plan is what you expect, then you can deploy all resources by running terraform apply .</p><h3>Further Applications and Future Work</h3><p>While this tutorial goes through the basics to set up a dynamic serverless load balancer, there are many additional components you can add to extend this example. One option is to add a DNS resource that can reference the IP address from the load balancer output.</p><p>Another exciting opportunity is to add various <a href="https://medium.com/r?url=https%3A%2F%2Fcloud.google.com%2Farmor">Cloud Armor</a> policies to different routes and endpoints. This feature is still in beta, but as it comes more mature we will have an additional blog post on it, so stay tuned. An example resource could look like the below policy, which we could add in a dynamic block and reference in the backend block with the <strong><em>security_policy</em></strong> field.</p><pre> resource &quot;google_compute_security_policy&quot; &quot;service_sec_policy&quot; {<br>   provider = google-beta</pre><pre>   name        = &quot;service_sec_policy-${local.domain}&quot;<br>   description = &quot;mobileproxy-sec-policy&quot;<br>   project     = local.project</pre><pre>   adaptive_protection_config {<br>       layer_7_ddos_defense_config {<br>           enable = true<br>       }<br>   }</pre><p>We also have several pull requests pending in Google’s Terraform provider to add additional functionality including adding the api-gateway resource as an option in the google_compute_region_network_endpoint_group<strong><em> </em></strong>resource as well as add full support for cloud armor policies in google_compute_security_policy including rate limiting and throttling options.</p><p>If you enjoyed this blog, then check out our other <a href="https://github.com/premisedata/gcp-tutorials">tutorials</a> or explore additional content on our newly launched <a href="https://engineering.premise.com/">engineering blog</a>!</p><p><strong><em>Premise is constantly looking to hire top-tier engineering talent to help us improve our front-end, mobile offerings, data and cloud infrastructure. Come find out why we’re consistently named among the top places to work in Silicon Valley by visiting our </em></strong><a href="https://bit.ly/3wnTrLn"><strong><em>Careers</em></strong></a><strong><em> page.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e15751853312" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/tutorial-managing-serverless-gcp-load-balancers-dynamically-with-terraform-e15751853312">Tutorial: Managing Serverless GCP Load Balancers Dynamically with Terraform</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Cost Spike Alerting for Google Cloud Platform (GCP)]]></title>
            <link>https://engineering.premise.com/tutorial-cost-spike-alerting-for-google-cloud-platform-gcp-46fd26ae3f6a?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/46fd26ae3f6a</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[google-cloud-pl]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[billing]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Tue, 31 Aug 2021 16:28:21 GMT</pubDate>
            <atom:updated>2023-08-14T20:57:07.626Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>By Austen Novis, Software Engineer</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4A8V7f-6fCFBOW-t" /><figcaption>Photo by <a href="https://unsplash.com/@f7photo?utm_source=medium&amp;utm_medium=referral">Michael Longmire</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The cloud has made deploying large scale applications as easy as a click of a button.</p><p>That button, however, can quickly become quite costly if not configured properly. The key is to identify when costs are increasing drastically so you can look into and stop any problematic service before getting surprised by a huge monthly bill. On the flip side, it is also useful to be alerted to large cost decreases since this can signify a major issue with a service that may have been missed by your other monitoring and alerting systems.</p><p>Google Cloud Platform (GCP) billing does allow for customized <a href="https://cloud.google.com/billing/docs/how-to/budgets">budget alerting</a>, which offers a good first line defense for spending spikes. However, these alerts require the user to set predefined static dollar amount thresholds on their entire GCP spending or manually set thresholds on a per service basis.</p><p>Built-in budget alerts are useful if you have a few services that you expect could potentially be misconfigured and abused, but manually setting and updating service budget alerts for almost 1700 services is not feasible especially as your cloud spend increases naturally as your cloud usage grows.</p><p>Our goal then was to build a solution that would alert daily on any large percentage cost increase or decrease from the previous day on a per service basis. Our solution utilized GCP’s built in capability to export daily costs from billing directly in a BigQuery dataset. This allowed us to set up a daily triggered cloud function to parse this dataset and alert to a Slack channel on any significant cost increases or decreases with the corresponding SKU, service name, and a link to the billing dashboard.</p><p>This tutorial will walk you through setting up this entire flow in a few quick and easy steps, while allowing you to easily customize the service thresholds, Slack message ui, and the cron schedule. The code for this tutorial can be found on our <a href="https://github.com/premisedata/gcp-tutorials/tree/main/003-cost-alerts">gcp-tutorials</a> GitHub repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yizxLF47WnKOWK0Y" /><figcaption>GCP Cost Alert Diagram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_O-jKW53kQ8QuEc5" /><figcaption>Example Slack Alert</figcaption></figure><h3>Prerequisites:</h3><ul><li>GCP Account</li><li>Python environment (&gt;3.8)</li><li><a href="https://cloud.google.com/sdk/docs/install">Gcloud cli</a></li><li><a href="https://api.slack.com/messaging/webhooks#getting_started">Slack Webhook</a></li></ul><h3>Getting Started:</h3><p><strong>Export daily cost billing to Bigquery </strong>by navigating to the billing export tab in the GCP billing service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*iBM1DIxR974d8Jh0" /><figcaption>BigQuery Tab</figcaption></figure><p>Then enable the daily cost export, by selecting the desired <strong><em>project</em></strong> and <strong><em>Dataset ID. </em></strong>Note these values as they will be needed for the cloud function later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mSKj8z6rrv4ZCZH_" /><figcaption>BiqQuery Billing Export</figcaption></figure><p><strong>Create a Service Account</strong> in GCP with the following two roles to give Cloud Scheduler permission to trigger your cloud function daily and permission for the cloud function to read billing reports in BigQuery.</p><p><strong><em>roles/bigquery.jobUser</em></strong></p><p><strong><em>roles/cloudfunction.invoker</em></strong></p><h3>Creating Cloud function:</h3><p>Next we will create a cloud scheduler to trigger a cron job and a cloud function, which queries BigQuery to get the latest service costs and checks to see if any large cost increases or decreases occurred.</p><p>To get started we will clone the <a href="https://github.com/premisedata/gcp-tutorials/tree/main/003-cost-alerts">gcp-cost-alerts repo</a>, which contains <em>main.py</em> where the relevant logic is contained and a <em>.goblet/config.json</em> where the cloud function configuration can be set.</p><p>Next you will need to install <a href="https://pypi.org/project/goblet-gcp/">goblet-gcp</a> to your python environment, which will handle the deployment of your cloud function and cloud scheduler. You can install using</p><pre>pip install goblet-gcp</pre><p>Next you will need to set the corresponding variables in <em>config.json</em> in the <em>.goblet</em> folder. This includes <strong>BILLING_ID</strong> which is your organization’s Billing ID, <strong>BILLING_ORG</strong> which is id for your organization, <strong>SLACK_WEBHOOK</strong> which is used to send messages to a Slack channel, <strong>BQ_TABLE</strong> which is the BigQuery table name for your daily cost exports and finally <strong>serviceAccountEmail </strong>which is the email corresponding to the service account you created in the earlier step.</p><p>Now to deploy the cloud function all you will need to run is the following command where PROJECT_ID is the GCP project and REGION_ID is the GCP region you wish to deploy your cloud function.</p><pre>goblet deploy -p PROJECT_ID -l REGION _ID</pre><p>The cloud function uses several threshold variables to determine what messages to forward to Slack or any other integration you would wish to add. These values are found near the top of <em>main.py</em> and can be changed before deploying if desired.</p><p><strong>PERCENTAGE </strong>is the percent changed from the previous day that would trigger an alert and is defaulted to 1.1, which corresponds to a 10% change.</p><p><strong>AMOUNT_CHANGED </strong>is a set dollar amount change that would trigger an alert since for highly used services a large dollar change might still be below the 10% percent threshold. This is defaulted to 500 corresponding to a $500 change.</p><p><strong>AMOUNT </strong>is the minimum spend that will trigger an alert since a $1 to $2 change is technically a 100% change, but shouldn’t be alerted on. The default is set to $250.</p><p>The <strong>Cloud Scheduler</strong> can be customized in the <em>app.schedule</em> function located in <em>main.py</em>. Currently the default is for 3pm EST. The reason it is so late in the day is that it does take time for GCP to export all of the cost data to BigQuery so in order to have your function execute on the previous day’s complete day it is advisable to run the cloud function in the afternoon.</p><h3>Conclusion:</h3><p>We now have a cloud function that checks your daily GCP spend for any large cost increases or decreases and notifies a Slack channel. This will allow you to rest a little easier knowing that any trials of new services or changes to existing services that go wrong will be detected quickly, preventing unexpected billing charges later on. Feel free to customize the cloud function to fit your needs and let us know if you have any suggestions for improvements or integrations you would like us to add. If you enjoyed this blog, then check out our other <a href="https://github.com/premisedata/gcp-tutorials">tutorials</a> or explore additional content on our newly launched <a href="https://engineering.premise.com/">engineer blog</a>!</p><p>If you found this tutorial helpful you should check out another tutorial on <a href="https://engineering.premise.com/tutorial-low-usage-alerting-on-slack-for-google-cloud-platform-gcp-cc68ac8ca4d">Low Usage Alerting</a>.</p><p><strong><em>Premise is constantly looking to hire top-tier engineering talent to help us improve our front-end, mobile offerings and cloud infrastructure. Come find out why we’re consistently named among the top places to work in Silicon Valley by visiting our </em></strong><a href="https://bit.ly/3wnTrLn"><strong><em>Careers</em></strong></a><strong><em> page.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46fd26ae3f6a" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/tutorial-cost-spike-alerting-for-google-cloud-platform-gcp-46fd26ae3f6a">Tutorial: Cost Spike Alerting for Google Cloud Platform (GCP)</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cleaning up your Google Cloud Environment: Safety Guaranteed*]]></title>
            <link>https://engineering.premise.com/cleaning-up-your-google-cloud-environment-safety-guaranteed-2de51fb8620a?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2de51fb8620a</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud-custodian]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 18:25:32 GMT</pubDate>
            <atom:updated>2021-07-12T18:25:32.817Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use Cloud Custodian’s new metric filters to clean up your Google Cloud environment while minimizing any potential impacts.</h4><p><strong><em>By Austen Novis, Software Engineer</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_HC2eW2jlX4S0YXc" /><figcaption>Photo by <a href="https://unsplash.com/@whaleitsjessica?utm_source=medium&amp;utm_medium=referral">Jessica Tan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is every engineer’s goal to have a clean cloud environment that has no rogue infrastructure and adheres to least privilege permissions while having strict accountability for every cloud resource.</p><p>However, in practice this is rarely the case, especially for fast moving startups that accumulate tech debt as they grow and innovate. As the cloud environment becomes larger and moves away from its ideal state, security risks increase as vulnerable pieces of infrastructure may lay dormant such as overprivileged security accounts and open firewalls, not to mention wasted costs for extraneous resources.</p><p>It is therefore very important to continuously and proactively keep cloud environments as close to the desired state as possible, ideally through automation.</p><p>This requires going through several steps to <strong>discover</strong> any misconfigurations or outdated resources, and then ultimately execute the <strong>actions</strong> to remediate these problems. However, we noticed that implementing these steps were not enough.</p><p>In order to automate the discovery and action processes we also needed to ensure that any actions we took would not <strong>impact</strong> the company. This is not a simple task especially with resources such as firewalls and service accounts that may be used by multiple resources and have the potential to break a lot of business critical processes.</p><p>In order to discover and take actions on outdated and noncompliant resources we use an open source tool called <a href="https://cloudcustodian.io/">Cloud Custodian</a>. Cloud Custodian is a stateless rule engine that enforces custom policy definitions, using an easy to use yaml based DSL, on your cloud resources.</p><p>In a few lines of configuration we can quickly determine what resources we would want to remove, and with many of Cloud Custodian’s built in actions, actually act on them. However, we were not comfortable executing these policies since we did not understand the ramifications that these actions could have. Luckily, GCP has over a hundred <a href="https://cloud.google.com/monitoring/api/metrics_gcp">prebuilt cloud metrics</a>, including many metrics that track resource usage allowing you to understand potential impacts of any action. Premise recently made several contributions to Cloud Custodian enabling new GCP resource filters backed by these metrics, which now allows us to create complete policies that find vulnerable resources, check their utilization, and ultimately remove or modify them.</p><p>We will now go through several examples to learn how to safely remove vulnerabilities to notoriously difficult infrastructure components to assess, such as firewall rules, service accounts, service account keys, and bucket policies. While nothing is guaranteed*, using these new metric filters have been proven to work safely and effectively, providing an improved cloud environment, while ensuring no disruptions to your engineers and customers.</p><h3>Setting Up Cloud Custodian</h3><p>Cloud Custodian is a Python application and supports Python 3 on Linux, MacOS and Windows.</p><p>To install run the following commands:</p><pre>pip install c7n<br>pip install c7n_gcp</pre><p>To run Cloud Custodian you will also need to be authenticated to GCP. If you are not already authenticated you will first need to install <a href="https://cloud.google.com/sdk/docs/install">gcloud</a>.(the GCP Command Line Interface).</p><p>Then run the following command:</p><pre>gcloud auth application-default login</pre><p>Executing the command will open a browser window with prompts to finish configuring your credentials. For more information on this command, <a href="https://cloud.google.com/sdk/gcloud/reference/auth/login">view its documentation</a>.</p><h3>Running Cloud Custodian</h3><p>Cloud Custodian uses policies to interact with cloud resources. A policy is simply a YAML file that follows a predetermined schema to describe what you want Custodian to do.</p><p>There are three main components to a policy:</p><ul><li><strong>Resource</strong>: the type of resource to run the policy against</li><li><strong>Filters</strong>: criteria to produce a specific subset of resources</li><li><strong>Actions</strong>: directives to take on the filtered set of resources</li></ul><p>The example below illustrates a policy that filters for compute engine resources named test, and then performs the “stop” action on each resource that matches that filter.</p><pre>policies:<br>- name: my-first-policy<br>  description: |<br>   Stops all compute instances that are named &quot;test&quot;<br>  resource: gcp.instance<br>  filters:<br>  - type: value<br>    key: name<br>    value: test<br>  actions:<br>  - type: stop</pre><p>To execute this policy in your project you would simply execute the following command, where custodian.yml is the file that contains your project.</p><pre>GOOGLE_CLOUD_PROJECT=&quot;project-id&quot; custodian run --output-dir=. custodian.yml</pre><p>Adding the flag <em>--dryrun</em> is useful since it ensures that the actions will not be run, so you can see what resources would be affected by the policy before executing any destructive actions.</p><p>Next we will go through various examples that use GCP’s metrics to remove sensitive resources while ensuring no impacts to current workloads.</p><h3>Custodian Policies</h3><p>The following policies can be found and downloaded from our <a href="https://github.com/premisedata/gcp-tutorials/tree/main/002-cloud-custodian-metric-filters"><strong>git repo</strong></a>.</p><h4>Detecting and Disabling Unused Service Accounts</h4><p>Having old and unused Service Accounts presents security risks as these can be used to access resources and sensitive company data.</p><p>Anyone who can assume a service account will be able to access anything that that service account has permission to. It is therefore important to always limit service accounts to only the permissions they need and to remove any unused service accounts. However, disabling service accounts are tricky since it can break applications by removing its permission to access critical resources.</p><p>Using Cloud Custodian, we are able to write and execute a policy that checks for any service accounts across all projects that have not been used in the past month and then disable them. We can then write an additional policy to delete any disabled service accounts to complete the service account cleanup. The metric we used is <em>service_account</em>/<em>authn_events_count, </em>which tracks how many times that service account has been used in a certain period. We selected 30 days, but this can be customized to a shorter timeframe if desired. To run the policy make sure to have the code downloaded from <a href="https://github.com/premisedata/gcp-tutorials/blob/main/002-cloud-custodian-metric-filters/unused_service_accounts.yml">GitHub</a> or copy the policy directly.</p><pre>GOOGLE_CLOUD_PROJECT=&quot;project-id&quot; custodian run -- output-dir=. unused_service_account.yml --dryrun</pre><p>To execute the disable action remove the <em>dryrun</em> flag from the previous command.</p><pre>polices:<br>- name: unused-service-accounts<br>  resource: gcp.service-account<br>  filters:<br>  - type: metrics<br>    name: iam.googleapis.com/service_account/authn_events_count<br>    value: -1<br>    days: 30<br>    missing-value: -1<br>    op: eq<br>    aligner: ALIGN_SUM<br>  actions:<br>  - disable</pre><h4>Detecting and Deleting Unused Service Accounts Keys</h4><p>Similar to the risks of service accounts, service account keys allow for potential malicious users to assume all of the permissions granted by the corresponding service account.</p><p>While it is good practice to rotate your keys often, it can be difficult to determine if legacy keys are being used and what the implications are for deleting the keys. In order to safely delete service account keys, we can use a similar metric as service accounts called <em>service_account/key/authn_events_count</em>, which tracks the usage of service account keys.</p><p>In addition to the metric filter, we will add an additional filter that ensures we are only deleting user created keys and not interfering with any internal Google keys.</p><pre>policies:<br>- name: unused-service-account-keys<br>  resource: gcp.service-account-key<br>  filters:<br>  - type: value<br>    key: keyType<br>    value: SYSTEM_MANAGED<br>    op: ne<br>  - type: metrics<br>    name: iam.googleapis.com/service_account/key/authn_events_count<br>    value: -1<br>    days: 30<br>    missing-value: -1<br>    op: eq<br>    aligner: ALIGN_SUM<br>  actions:<br>  - delete</pre><p>To run the policy make sure to have the code downloaded from <a href="https://github.com/premisedata/gcp-tutorials/blob/main/002-cloud-custodian-metric-filters/unused_service_account_keys.yml">GitHub</a> or copy the above policy directly. To execute the delete action remove the <em>dryrun</em> flag.</p><pre>GOOGLE_CLOUD_PROJECT=&quot;project-id&quot; custodian run --output-dir=. unused_service_account_keys.yml --dryrun</pre><h4>Setting Uniform Bucket Access</h4><p>GCP Buckets allow for access to be granted by IAM policies or ACL’s. However, using <a href="https://cloud.google.com/storage/docs/uniform-bucket-level-access">uniform bucket-level</a> access is recommended by google, because it unifies and simplifies how access is granted to Cloud Storage resources.</p><p>Therefore, the goal is to enable uniform bucket access to all buckets, without impacting any current users who may be using ACL policies to access their buckets. We are able to use the metric <em>authz/acl_based_object_access_count</em> to determine what buckets are using ACL policies for authentication and only enable uniform-access to those buckets that are not actively using ACL policies.</p><pre>policies:<br>- name: enable-uniform-bucket-access<br>  resource: gcp.bucket<br>  filters:<br>  - iamConfiguration.uniformBucketLevelAccess.enabled: false<br>  - type: metrics<br>    name: storage.googleapis.com/authz/acl_based_object_access_count<br>    value: -1<br>    days: 30<br>    missing-value: -1<br>    op: eq<br>    aligner: ALIGN_COUNT<br>  actions:<br>  - type: set-uniform-access<br>    state: true</pre><p>To run the policy, make sure to have the code downloaded from <a href="https://github.com/premisedata/gcp-tutorials/blob/main/002-cloud-custodian-metric-filters/enable_uniform_bucket_access.yml">GitHub</a> or copy the above policy directly. To execute the set-uniform-access action remove the <em>dryrun</em> flag.</p><pre>GOOGLE_CLOUD_PROJECT=&quot;project-id&quot; custodian run --output-dir=. enable_uniform_bucket_access.yml --dryrun</pre><h4>Detecting and Disabling Unused Firewalls</h4><p>Firewalls are another resource that have a direct impact on cloud security and are difficult to remediate.</p><p>While dormant and over-permissive firewalls have the potential to open up machines to attack, deleting an actively used firewall can severely impact the company by potentially disabling network traffic and restriction connections.</p><p>In order to safely remove unused firewall rules we use the <em>subnet/firewall_hit_count</em> metric to filter for unused firewalls and then call the disable action. Note that this metric applies only to firewalls for which Firewall Logging has been turned on. Once you can verify that the firewalls have not impacted operations you can execute a follow up policy that deletes any disabled firewalls.</p><pre>policies:<br>- name: unused-firewalls<br>  resource: gcp.firewall<br>  filters:<br>  - type: metrics<br>    name:   firewallinsights.googleapis.com/subnet/firewall_hit_count<br>    aligner: ALIGN_COUNT<br>    days: 30<br>    value: -1<br>    missing-value: -1<br>    op: eq<br>  actions:<br>  - disable</pre><p>To run the policy make sure to have the code downloaded from <a href="https://github.com/premisedata/gcp-tutorials/blob/main/002-cloud-custodian-metric-filters/unused_firewalls.yml">GitHub</a> or copy the above policy directly. To execute the disable action remove the <em>dryrun</em> flag.</p><pre>GOOGLE_CLOUD_PROJECT=&quot;project-id&quot; custodian run --output-dir=. unused_firewalls.yml --dryrun</pre><h4>Detecting Underutilized Instances</h4><p>Another use case for these GCP metrics is to reduce cloud costs by finding underutilized resources such as virtual machines.</p><p>In this example, we can use the <em>instance/cpu/utilization</em> metric to filter instances that fall below a certain threshold, which in this case is 10%. These filtered instances can then be acted upon using any of C<a href="https://cloudcustodian.io/docs/gcp/resources/instance.html#actions">loud Custodian’s built in actions</a> including adding labels, or stopping the instances if they are not being used.</p><pre>policies:<br> - name: instance-utilization<br>   resource: gcp.instance<br>   filters:<br>     - type: metrics<br>       name: compute.googleapis.com/instance/cpu/utilization<br>       aligner: ALIGN_MEAN<br>       days: 30<br>       value: 10<br>       op: less-than</pre><p>To run the policy make sure to have the code downloaded from <a href="https://github.com/premisedata/gcp-tutorials/blob/main/002-cloud-custodian-metric-filters/instance_utilization.yml">GitHub</a> or copy the above policy directly.</p><pre>GOOGLE_CLOUD_PROJECT=&quot;project-id&quot; custodian run --output-dir=. instance_utilization.yml</pre><h3>Multi Project Execution</h3><p>The previous examples can be limiting in large GCP accounts, since those policies as is can only be triggered on one project at a time.</p><p>Fortunately, Cloud Custodian has an additional package called <a href="https://cloudcustodian.io/docs/tools/c7n-org.html?highlight=c7n%20org">c7n-org</a> that allows for the same custodian policies to be triggered against all projects or even a desired subset. c7n-org can be installed via the following pip command.</p><pre>pip install c7n-org</pre><p>To execute a policy against multiple projects, you simply need a <em>projects.yml</em> file that includes a list of projects to run against and then run the following command where <em>policy.yml</em> is the desired policy to run.</p><pre>c7n-org run -c projects.yml -s output -u policy.yml --dryrun</pre><h3>Conclusion</h3><p>As you already know, it is important from a security and cost perspective to always be proactive in discovering and acting on any misconfigured and unused resources.</p><p>While there are many tools that aid in both the discovery phase and action phase, you will also need to understand the impacts those affected resources would have in order to minimize any potential disruptions. We learned about Cloud Custodian and how to write policies that not only find and remove notoriously dangerous cloud resources, but to do so safely using GCP’s built in metric filters. Hopefully, this provides the confidence you need in order to keep your cloud environments clean and less cluttered.</p><p><strong><em>Premise is constantly looking to hire top-tier engineering talent to help us improve our front-end, mobile offerings and cloud infrastructure. Come find out why we’re consistently named among the top places to work in Silicon Valley by visiting our </em></strong><a href="https://bit.ly/3wnTrLn"><strong><em>Careers</em></strong></a><strong><em> page.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2de51fb8620a" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/cleaning-up-your-google-cloud-environment-safety-guaranteed-2de51fb8620a">Cleaning up your Google Cloud Environment: Safety Guaranteed*</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Publishing GitHub Findings to Security Command Center]]></title>
            <link>https://engineering.premise.com/tutorial-publishing-github-findings-to-security-command-center-2d1749f530bc?source=rss-8b06b96dee6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d1749f530bc</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[security-command-center]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Austen Novis]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 15:20:23 GMT</pubDate>
            <atom:updated>2021-06-16T15:20:23.893Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>By Austen Novis, Software Engineer</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PWnnZnn1fojjTdB_" /><figcaption>Photo by <a href="https://unsplash.com/@cedericvandenberghe?utm_source=medium&amp;utm_medium=referral">Cederic Vandenberghe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://cloud.google.com/security-command-center">Security Command Center</a> (SCC) is a centralized security and risk management service in<a href="https://cloud.google.com/"> Google Cloud Platform </a>(GCP). It allows you to view security vulnerabilities and misconfigurations of your cloud assets in one place. Additionally, SCC will automatically perform scans on your cloud resources and provide immediate insights and recommendations on your cloud assets.</p><p>However, your organization might have other security findings that are unrelated to GCP such as findings from endpoint protection software, and you would want to have those findings to also be centralized and viewable in Security Command Center</p><p>A nice feature of SCC is that you can publish your own custom findings, which can be related to your GCP cloud assets or more importantly on resources outside of GCP. This allows SCC to be your single source of truth for all security related issues in your company.</p><p>Outside of GCP, one of the biggest vulnerabilities companies have is GitHub, where there are several serious risks. These include data exfiltration, credential leaking, and application vulnerabilities. GitHub has taken proactive steps to help customers deal with these risks by providing automatic <a href="https://github.com/features/security/">security scans</a>, including<a href="https://docs.github.com/en/code-security/secret-security/about-secret-scanning"> secret scanning</a>, <a href="https://docs.github.com/en/code-security/secure-coding/about-code-scanning">code vulnerability scanning</a>, and <a href="https://docs.github.com/en/code-security/supply-chain-security/about-alerts-for-vulnerable-dependencies">dependency scanning</a>. By default, the results of these scans are saved in GitHub, which adds another tool security teams will have to constantly monitor and perform actions on.</p><p>In order to centralize all security related findings in SCC we built a custom serverless solution that forwards all relevant information from GitHub’s security scans to SCC. This includes creating new findings in SCC as GitHub creates an alert and automatically resolving findings in SCC as they are resolved in GitHub.</p><p>The following tutorial will walk you through all the steps required to automatically forward GitHub findings to GCP’s SCC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*fT5jC-NcpdvKiCOa" /><figcaption>Github to Security Command Center Flow</figcaption></figure><h3>Prerequisites:</h3><ul><li>GCP Account with <a href="https://cloud.google.com/security-command-center">Security Command Center</a> enabled</li><li>GitHub Account with at least one repo with security scanning enabled</li><li>Python environment (&gt;3.7)</li><li><a href="https://cloud.google.com/sdk/docs/install">Gcloud cli</a></li></ul><h3>Getting Started:</h3><p><strong>Create a Service Account</strong> in GCP with the following two roles to give your webhook permission to create, update, and resolve security center findings.</p><p><strong><em>roles/securitycenter.assetsViewer</em></strong></p><p><strong><em>roles/securitycenter.findingsEditor</em></strong></p><p><strong>Create a new security center</strong> <strong>Source </strong>called GitHub. Unfortunately you cannot do this currently via gcloud or console and it must be <a href="https://cloud.google.com/security-command-center/docs/how-to-api-create-manage-security-sources#python">via code or post api request</a>. In python, you can run the following script. Make sure you have the <em>securitycenter</em> library which you can install with</p><blockquote>pip install google-cloud-securitycenter</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab4ae3cd5f2144a70e4e40354be3d9b7/href">https://medium.com/media/ab4ae3cd5f2144a70e4e40354be3d9b7/href</a></iframe><h3>Creating Cloudfunction:</h3><p>Next we will create the serverless webhook using a GCP cloudfunction. This webhook receives Github’s security scan events and contains the logic to push or resolve the corresponding findings in SCC. To get started we will clone the <a href="https://github.com/premisedata/gcp-tutorials/tree/main/001-github-to-scc">github-to-scc repo</a>, which contains <em>main.py</em> where the relevant logic is contained and a .goblet/config.json where the cloudfunction configuration can be set.</p><p>Next you will need to install <a href="https://pypi.org/project/goblet-gcp/"><em>goblet-gcp</em></a> to your python environment, which will handle the deployment of your cloudfunction. You can install using</p><blockquote>pip install goblet-gcp</blockquote><p>Next you will need to set the corresponding variables in <em>config.json</em> in the <em>.goblet</em> folder. This includes <strong>ORGANIZATION</strong> which is your organization ID, <strong>SOURCE</strong> which is the id for the GitHub source you created in the earlier step, <strong>GITHUB_SECRET</strong> which is used to secure your webhook and will be needed later when you create the webhook on GitHub and finally <strong>serviceAccountEmail </strong>which is the service account you created in the earlier step.</p><p>Now to deploy the cloudfunction all you will need to run is the following command where PROJECT_ID is the GCP project and REGION_ID is the GCP region you wish to deploy your webhook to.</p><blockquote>goblet deploy — p PROJECT_ID — l REGION _ID</blockquote><p>The goblet deploy command will return the cloudfunction url that you need to provide to github. You can also get the url via the console or gcloud api.</p><h3>Creating GitHub Webhook</h3><p>Finally we will need to create the GitHub webhook which will forward the relevant security alerts to our cloudfunction endpoint. This can be done either on a per-repo basis or at the organizational level. To create the webhook, navigate to the settings tab on your repo or org and click on the “add webhook” button. In the <strong>Payload URL</strong> field, input the cloudfunction http endpoint from the previous step. Set <strong>Content type</strong> to application/json and the <strong>Secret </strong>to the secret you used in the previous step. Finally toggle the <em>“Let me Select individual events’’</em> and select the following events:</p><p><strong><em>Secret scanning alerts</em></strong></p><p><strong><em>Repository vulnerability alerts</em></strong></p><p><strong><em>Code scanning alerts</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ywkpXsioPvleL47x" /></figure><p>Finally click on <em>“Add webhook”</em> and you everything is now connected!</p><h3>Conclusion:</h3><p>We now have a Github webhook that forwards GitHub security events to the cloudfunction endpoint. That cloudfunction then creates or resolves findings in SCC. You can then view your findings in SCC under the sources tab and click on GitHub. The findings will contain links to your repo making it easy to navigate back into GitHub to view and fix the corresponding vulnerabilities.</p><p><strong><em>Premise is constantly looking to hire top-tier engineering talent to help us improve our front-end, mobile offerings and cloud infrastructure. Come find out why we’re consistently named among the top places to work in Silicon Valley by visiting our </em></strong><a href="https://bit.ly/3wnTrLn"><strong><em>Careers</em></strong></a><strong><em> page.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d1749f530bc" width="1" height="1" alt=""><hr><p><a href="https://engineering.premise.com/tutorial-publishing-github-findings-to-security-command-center-2d1749f530bc">Tutorial: Publishing GitHub Findings to Security Command Center</a> was originally published in <a href="https://engineering.premise.com/">Engineering at Premise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>