<?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 Sean Kim on Medium]]></title>
        <description><![CDATA[Stories by Sean Kim on Medium]]></description>
        <link>https://medium.com/@sean.kim_24621?source=rss-124b11785b71------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VYRZwYsZCbMjCL0fzSLj-w.png</url>
            <title>Stories by Sean Kim on Medium</title>
            <link>https://medium.com/@sean.kim_24621?source=rss-124b11785b71------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:48:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sean.kim_24621/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[Send Slack Messages from Snowflake with Snowpark External Network Access]]></title>
            <link>https://medium.com/snowflake/send-slack-messages-from-snowflake-with-snowpark-external-network-access-8e3e42a7cde2?source=rss-124b11785b71------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3e42a7cde2</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[alerts]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[external-access]]></category>
            <dc:creator><![CDATA[Sean Kim]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 19:26:41 GMT</pubDate>
            <atom:updated>2024-08-05T02:14:33.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*s3NFSBzTVRz3VoenlNMilg.png" /><figcaption>Created with Midjourney</figcaption></figure><p><em>(Note: Some time after this blog was published, Snowflake added native capability to send notifications to Slack, as well as Microsoft Teams and PagerDuty. Check it out here: </em><a href="https://docs.snowflake.com/en/user-guide/notifications/webhook-notifications"><em>https://docs.snowflake.com/en/user-guide/notifications/webhook-notifications</em></a><em>)</em></p><h3>Background</h3><p><a href="https://docs.snowflake.com/en/developer-guide/external-network-access/external-network-access-overview">Snowpark external access</a> (currently in public preview on AWS) opens up a raft of new possible use cases with your Python or Java scripts you run within the Snowflake Data Cloud. Recently, I’ve been helping a few customers set up a way for Snowflake to send messages from Snowflake directly to Slack via its incoming webhook URL.</p><p>Unlike Snowflake’s already existing <a href="https://docs.snowflake.com/en/sql-reference/external-functions-introduction">External Functions</a> feature, which requires the customer to set up a separate HTTPS proxy service (such as an API gateway) as well as a remote service, the integration is completely set up within Snowflake, simplifying the set-up significantly.</p><p>This blog will go through a simple set up of the process.</p><h3>Use Cases</h3><p>Just about anything you can potentially do in Snowflake that’s worth surfacing in a Slack message is a good use case here! Some examples I can think of immediately:</p><ul><li>Send insights and visualisations generated from your data in Snowflake. This can be anything from high-level business metrics or custom reports or visualisations specific to a Slack channel.</li><li>Notifications and alerting of existing Snowpark code</li><li>Monitoring of Snowflake pipelines, configurations or access logs</li></ul><h3>Setup</h3><p>To follow along in your own account, you will need the following:</p><ul><li>Snowflake account, with access to a role with privileges to create the objects required, as well as read access to the SNOWFLAKE.ACCOUNT_USAGE schema.</li><li>A Slack account</li></ul><h4>Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0S0ANB77ZOjiMdSmDjQwA.png" /></figure><h4>1. Create a Slack app</h4><p>Creating a Slack app is simple. Go to <a href="https://api.slack.com/apps">https://api.slack.com/apps</a> and click on the “Create New App” button, then go through the prompts. For this example, I opted to create one “From scratch” into my own private Slack workspace</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*LehOb3E7JIQP40WyfNZSeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*_38r2DY4HX_nsPiNO9q35A.png" /></figure><h4>2. Generate a Webhook URL from Slack Apps UI</h4><p>Navigate to Features &gt;&gt; Incoming Webhooks, then click on “Add New Webhook to Workspace” to generate a new webhook. We’ll be prompted to select a channel to post. This can be any channel, including direct messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*d6s01QthqogC1glxvtBX4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*zAon8LhL0PmwZFpljQhgKQ.png" /></figure><p>Once that’s done, we should see a new Webhook URL generated. We’ll need to use this URL to set up the integration from the Snowflake side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*CXNlT5am-OA9BDmM6RcR4w.png" /><figcaption>Save the URL for later!</figcaption></figure><h4>3. Create Snowflake Network Rule</h4><p>Snowflake does not allow access to an external location unless the location is explicitly added within a NETWORK RULE, so we’ll create one for the Slack webhook location:</p><pre>CREATE OR REPLACE NETWORK RULE slack_webhook_network_rule<br>  MODE = EGRESS<br>  TYPE = HOST_PORT<br>  VALUE_LIST = (&#39;hooks.slack.com&#39;);</pre><h4>4. Store Webhook URL as a secret</h4><p>Anybody with access to the Webhook URL can potentially send arbitrary messages to your Slack workspace, so it’s important to store this information as a secret, rather than hardcode this information in your code. Snowflake provides a SECRETS object where secrets such as passwords, OAuth tokens or any other secure strings that can be retrieved programmatically by your Python code. We’ll create one with the Webhook URL we’ve generated from the Slack App UI:</p><pre>CREATE OR REPLACE SECRET slack_app_webhook_url<br>    type = GENERIC_STRING<br>    secret_string = &#39;https://hooks.slack.com/services/XXXXXXXXXX/XXXXXXXXXXXX/XXXXXXXXXXXXXXXX&#39;<br>    comment = &#39;Slack Webhook URL you have created from the Slack App UI&#39;;</pre><h4>5. Create an External Access Integration</h4><p>We will now integrate the NETWORK RULE and SECRET into a EXTERNAL ACCESS INTEGRATION :</p><pre>CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION slack_webhook_access_integration<br>  ALLOWED_NETWORK_RULES = (slack_webhook_network_rule)<br>  ALLOWED_AUTHENTICATION_SECRETS = (slack_app_webhook_url)<br>  ENABLED = true;</pre><h4>6. Create a Python Stored Procedure to send a simple message</h4><p>For our first example, we will send a simple text message to Slack from a Python Stored Procedure.</p><p>Note that we need to declare the EXTERNAL ACCESS INTEGRATION as well as the SECRETS in the Stored Procedure definition. This will allow us to programmatically pull down the Webhook URL stored in the SECRETS object with the _snowflake module exposed to Python UDFs and Stored Procedures.</p><pre>CREATE OR REPLACE PROCEDURE send_slack_message(MSG string)<br>RETURNS STRING<br>LANGUAGE PYTHON<br>RUNTIME_VERSION = 3.10<br>HANDLER = &#39;main&#39;<br>EXTERNAL_ACCESS_INTEGRATIONS = (slack_webhook_access_integration)<br>SECRETS = (&#39;slack_url&#39; = slack_app_webhook_url)<br>PACKAGES = (&#39;snowflake-snowpark-python&#39;, &#39;requests&#39;)<br>EXECUTE AS CALLER<br>AS<br>$$<br>import snowflake.snowpark as snowpark<br>import json<br>import requests<br>import _snowflake<br>from datetime import date<br><br>def main(session, msg): <br>    # Retrieve the Webhook URL from the SECRET object<br>    webhook_url = _snowflake.get_generic_secret_string(&#39;slack_url&#39;)<br><br>    slack_data = {<br>     &quot;text&quot;: f&quot;Snowflake says: {msg}&quot;<br>    }<br><br>    response = requests.post(<br>        webhook_url, data=json.dumps(slack_data),<br>        headers={&#39;Content-Type&#39;: &#39;application/json&#39;}<br>    )<br>    if response.status_code != 200:<br>        raise ValueError(<br>            &#39;Request to slack returned an error %s, the response is:\n%s&#39;<br>            % (response.status_code, response.text)<br>        )<br>    <br>    return &quot;SUCCESS&quot;<br>$$;</pre><p>Once this is created, you can now send a simple message to Slack! Try it out by calling the Stored Procedure:</p><pre>CALL send_slack_message(&#39;Hello world!&#39;)</pre><p>Which should hopefully send the message straight to the Slack channel or DM you’ve selected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wrwa_BrioU9omtOd5EQNQ.png" /></figure><h4>7. (Optional) Send a cost report with Snowflake-generated visualisations</h4><p>Slack Applications have far more capabilities aside from sending simple text messages. We can enrich it with additional formatting, images or even interactive elements such as buttons.</p><p>This optional section will show you an example of extending our Stored Procedure to generate a Snowflake cost report with Snowpark DataFrame APIs, along with a seaborn bar chart served via a Presigned URL.</p><p>First we’ll need to create a Stage that will allow us to store plot images, along with any other unstructured data you’d like to share:</p><pre>CREATE OR REPLACE STAGE plot_stage ENCRYPTION = (TYPE = &#39;SNOWFLAKE_SSE&#39;);</pre><p>We will then introduce some new functions to the Python code. First, some simple Snowpark DataFrame API code to extract Snowflake credit spend from the last 30 days:</p><pre>def generate_credit_spend_summary(session) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;<br>        Queries Snowflake ACCOUNT_USAGE views to generate a compute cost report <br>        for the past 30 days.<br>    &quot;&quot;&quot;<br>    <br>    dataframe = session.table(&#39;snowflake.account_usage.metering_daily_history&#39;).\<br>        filter(col(&quot;usage_date&quot;) &gt;= dateadd(&#39;day&#39;, lit(-30), current_date())).\<br>        group_by(col(&quot;usage_date&quot;)).\<br>        agg(sum_(&quot;credits_billed&quot;).alias(&quot;credits_billed&quot;)).\<br>        sort(col(&quot;usage_date&quot;), ascending=False)<br><br>    dataframe_pd = dataframe.to_pandas()<br><br>    return dataframe_pd</pre><p>Next, a plotting function that generates a basic bar chart with the seaborn packages, save the plot to a Snowflake stage, then generate a Presigned URL from it:</p><pre>def generate_plot(session, df: pd.DataFrame) -&gt; str:<br>    &quot;&quot;&quot;<br>        Generates plot, saves it to a Snowflake Stage, and outputs the Presigned URL<br>    &quot;&quot;&quot;<br>    <br>    # Set the figure size<br>    plt.figure(figsize=(8, 4))<br><br>    sns.barplot(x=&#39;USAGE_DATE&#39;, y=&#39;CREDITS_BILLED&#39;, color=&#39;blue&#39;, data=df)<br><br>    # Rotate x-axis labels for better visibility (optional)<br>    plt.xticks(rotation=45)<br><br>    # Set labels and title<br>    plt.xlabel(&#39;Date&#39;)<br>    plt.ylabel(&#39;Credits&#39;)<br>    plt.title(&#39;Credit spend - Last 30 days&#39;)<br><br>    plt.tight_layout()<br>    plt.savefig(&#39;/tmp/credit_spend_l30days.png&#39;)<br><br>    session.file.put(&#39;/tmp/credit_spend_l30days.png&#39;, &#39;@PLOT_STAGE&#39;, overwrite=True, auto_compress=False)<br><br>    # Generate a Presigned URL with a TTL of 24 hours<br>    df = session.sql(&quot;SELECT GET_PRESIGNED_URL(@PLOT_STAGE, &#39;credit_spend_l30days.png&#39;, 86400) as image_url&quot;).collect()<br>    <br>    return df[0][0]</pre><p>Finally, we will edit the main handler to send a message along with the image and some additional commentary:</p><pre>def main(session): <br>    &quot;&quot;&quot;<br>        Main SPROC handler.<br>    &quot;&quot;&quot;<br><br>    # Retrieve Slack Webhook URL from the SECRET object<br>    webhook_url = _snowflake.get_generic_secret_string(&#39;slack_url&#39;)<br>    <br>    credit_spend_summary_df = generate_credit_spend_summary(session)<br>    image_url = generate_plot(session, credit_spend_summary_df)<br><br>    slack_data = {<br>        &quot;blocks&quot;: [<br>            {<br>                &quot;type&quot;: &quot;header&quot;,<br>                &quot;text&quot;: {<br>                    &quot;type&quot;: &quot;plain_text&quot;,<br>                    &quot;text&quot;: f&quot;Snowflake credit spend report for {date.today()}&quot;,<br>                }<br>            },<br>            {<br>                &quot;type&quot;: &quot;divider&quot;<br>            },<br>            {<br>                &quot;type&quot;: &quot;section&quot;,<br>                &quot;text&quot;: {<br>                    &quot;type&quot;: &quot;mrkdwn&quot;,<br>                    &quot;text&quot;: f&quot;Total credits spent in the past 30 days: *{credit_spend_summary_df[&#39;CREDITS_BILLED&#39;].sum()}*&quot;<br>                }<br>            },<br>            {<br>                &quot;type&quot;: &quot;image&quot;,<br>                &quot;title&quot;: {<br>                    &quot;type&quot;: &quot;plain_text&quot;,<br>                    &quot;text&quot;: &quot;Daily Snowflake credit spend&quot;<br>                },<br>                &quot;block_id&quot;: &quot;image4&quot;,<br>                &quot;image_url&quot;: image_url,<br>                &quot;alt_text&quot;: &quot;Snowflake credit spend report&quot;<br>            }<br>        ]<br>    }<br><br>    response = requests.post(<br>        webhook_url, data=json.dumps(slack_data),<br>        headers={&#39;Content-Type&#39;: &#39;application/json&#39;}<br>    )<br>    if response.status_code != 200:<br>        raise ValueError(<br>            &#39;Request to slack returned an error %s, Response:\n%s&#39;<br>            % (response.status_code, response.text)<br>        )<br>    <br>    return &quot;SUCCESS&quot;</pre><p>Putting it all together into our new Stored Procedure:</p><pre>CREATE OR REPLACE PROCEDURE slack_snowflake_cost_report()<br>RETURNS STRING<br>LANGUAGE PYTHON<br>RUNTIME_VERSION = 3.8<br>HANDLER = &#39;main&#39;<br>EXTERNAL_ACCESS_INTEGRATIONS = (slack_webhook_access_integration)<br>SECRETS = (&#39;slack_url&#39; = slack_app_webhook_url)<br>PACKAGES = (&#39;snowflake-snowpark-python&#39;, &#39;seaborn&#39;, &#39;matplotlib&#39;, &#39;requests&#39;, &#39;pandas&#39;)<br>EXECUTE AS CALLER<br>AS<br>$$<br>import snowflake.snowpark as snowpark<br>from snowflake.snowpark.functions import col, dateadd, current_date, sum as sum_, lit<br>import json<br>from datetime import date<br>import pandas as pd<br>import requests<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import _snowflake<br><br><br>def generate_credit_spend_summary(session) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;<br>        Queries Snowflake ACCOUNT_USAGE views to generate a compute cost report <br>        for the past 30 days.<br>    &quot;&quot;&quot;<br>    <br>    dataframe = session.table(&#39;snowflake.account_usage.metering_daily_history&#39;).\<br>        filter(col(&quot;usage_date&quot;) &gt;= dateadd(&#39;day&#39;, lit(-30), current_date())).\<br>        group_by(col(&quot;usage_date&quot;)).\<br>        agg(sum_(&quot;credits_billed&quot;).alias(&quot;credits_billed&quot;)).\<br>        sort(col(&quot;usage_date&quot;), ascending=False)<br><br>    dataframe_pd = dataframe.to_pandas()<br><br>    return dataframe_pd<br><br>    <br>def generate_plot(session, df: pd.DataFrame) -&gt; str:<br>    &quot;&quot;&quot;<br>        Generates plot, saves it to a Snowflake Stage, and outputs the Presigned URL<br>    &quot;&quot;&quot;<br>    <br>    # Set the figure size<br>    plt.figure(figsize=(8, 4))<br><br>    sns.barplot(x=&#39;USAGE_DATE&#39;, y=&#39;CREDITS_BILLED&#39;, color=&#39;blue&#39;, data=df)<br><br>    # Rotate x-axis labels for better visibility (optional)<br>    plt.xticks(rotation=45)<br><br>    # Set labels and title<br>    plt.xlabel(&#39;Date&#39;)<br>    plt.ylabel(&#39;Credits&#39;)<br>    plt.title(&#39;Credit spend - Last 30 days&#39;)<br><br>    plt.tight_layout()<br>    plt.savefig(&#39;/tmp/credit_spend_l30days.png&#39;)<br><br>    session.file.put(&#39;/tmp/credit_spend_l30days.png&#39;, &#39;@PLOT_STAGE&#39;, overwrite=True, auto_compress=False)<br><br>    # Generate a Presigned URL with a TTL of 15s<br>    df = session.sql(&quot;SELECT GET_PRESIGNED_URL(@PLOT_STAGE, &#39;credit_spend_l30days.png&#39;, 15) as image_url&quot;).collect()<br>    <br>    return df[0][0]<br><br>    <br>def main(session): <br>    &quot;&quot;&quot;<br>        Main SPROC handler.<br>    &quot;&quot;&quot;<br><br>    # Retrieve Slack Webhook URL from the SECRET object<br>    webhook_url = _snowflake.get_generic_secret_string(&#39;slack_url&#39;)<br>    <br>    credit_spend_summary_df = generate_credit_spend_summary(session)<br>    image_url = generate_plot(session, credit_spend_summary_df)<br><br>    slack_data = {<br>        &quot;blocks&quot;: [<br>            {<br>                &quot;type&quot;: &quot;header&quot;,<br>                &quot;text&quot;: {<br>                    &quot;type&quot;: &quot;plain_text&quot;,<br>                    &quot;text&quot;: f&quot;Snowflake credit spend report for {date.today()}&quot;,<br>                }<br>            },<br>            {<br>                &quot;type&quot;: &quot;divider&quot;<br>            },<br>            {<br>                &quot;type&quot;: &quot;section&quot;,<br>                &quot;text&quot;: {<br>                    &quot;type&quot;: &quot;mrkdwn&quot;,<br>                    &quot;text&quot;: f&quot;Total credits spent in the past 30 days: *{credit_spend_summary_df[&#39;CREDITS_BILLED&#39;].sum()}*&quot;<br>                }<br>            },<br>            {<br>                &quot;type&quot;: &quot;image&quot;,<br>                &quot;title&quot;: {<br>                    &quot;type&quot;: &quot;plain_text&quot;,<br>                    &quot;text&quot;: &quot;Daily Snowflake credit spend&quot;<br>                },<br>                &quot;block_id&quot;: &quot;image4&quot;,<br>                &quot;image_url&quot;: image_url,<br>                &quot;alt_text&quot;: &quot;Snowflake credit spend report&quot;<br>            }<br>        ]<br>    }<br><br>    response = requests.post(<br>        webhook_url, data=json.dumps(slack_data),<br>        headers={&#39;Content-Type&#39;: &#39;application/json&#39;}<br>    )<br>    if response.status_code != 200:<br>        raise ValueError(<br>            &#39;Request to slack returned an error %s, Response:\n%s&#39;<br>            % (response.status_code, response.text)<br>        )<br>    <br>    return &quot;SUCCESS&quot;<br>$$;</pre><p>As with the simple message example, simply call the Stored Procedure to generate the message:</p><pre>CALL slack_snowflake_cost_report();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11G8Ynno5Bz5_TWJjZK5Qg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3e42a7cde2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/send-slack-messages-from-snowflake-with-snowpark-external-network-access-8e3e42a7cde2">Send Slack Messages from Snowflake with Snowpark External Network Access</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Snowpipe with AWS Eventbridge]]></title>
            <link>https://medium.com/snowflake/automating-snowpipe-with-aws-eventbridge-a5ef27504949?source=rss-124b11785b71------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5ef27504949</guid>
            <category><![CDATA[eventbridge]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sean Kim]]></dc:creator>
            <pubDate>Tue, 30 May 2023 17:37:10 GMT</pubDate>
            <atom:updated>2023-05-31T22:04:01.529Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating Snowpipe with Amazon EventBridge</h3><h4>A more powerful and flexible pipeline for auto-loading data into Snowflake</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*Ms2YANrBZ3hDkkPwgs_3wg.png" /></figure><p>Snowflake <a href="https://docs.snowflake.com/release-notes/2023-04#amazon-eventbridge-support-for-snowpipe-auto-ingest-preview">has (rather quietly!) released</a> support for Snowpipe auto-ingest with Amazon EventBridge, in public preview. This option provides an alternative to existing approaches that require configuring a S3 Event Notification.</p><p>This blog will dive deep into this new option help you decide whether this approach suits your current Snowflake + AWS architecture, and guide you through the process of setting this up.</p><h3>Background</h3><p>Since its release into GA way back in December 2018, Snowpipe provided an mechanism for Data Engineers to set up low-latency event-driven ingestion pipelines from cloud storage services, such as Amazon S3, to Snowflake.</p><p>Snowflake has previously offered three main options for automating Snowpipe on AWS:</p><ol><li>Route S3 Event Notifications directly to a Snowflake-managed Amazon Simple Queue Service (SQS)</li><li>Route S3 Event Notifications to a Snowflake-managed Amazon Simple Queue Service (SQS) via a customer-managed Amazon Simple Notification Service (SNS)</li><li>Hand-roll your own automation via the <a href="https://docs.snowflake.com/en/user-guide/data-load-snowpipe-rest-apis">Snowpipe REST API</a></li></ol><h3>Challenges with Existing Methods</h3><p>The first two options remain the most common method and remains to this day a robust solution with minimal set-up and configuration required to get up and running.</p><p>However, at larger organisational scales where multiple teams or services require access to the same events, some challenges may pop up, primarily due to limitations with Amazon S3 Event Notifications:</p><ul><li>Amazon S3 Notifications cannot <a href="https://repost.aws/knowledge-center/lambda-s3-event-configuration-error">route events from overlapping prefixes/suffixes</a>. Teams often needed to work around this by introducing a broker service in-between S3 notifications and Snowpipe SQS, typically with services such as SNS or Lambda.</li><li>PUT notification API performs an <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketNotificationConfiguration.html">atomic operation</a>, which overwrites any existing configuration on a bucket. Therefore, if notifications are deployed by multiple services, each service needed to ensure configuration updates don’t overwrite each other.</li><li>S3 Notifications are not deployed as a discrete resource by some Infrastructure-as-Code tools such as CloudFormation, and instead handled as a property of the S3 bucket itself. This made automated deployments with CI/CD challenging if the team/org deploys services using these notifications from multiple repositories.</li></ul><p>If any of these points resonate with your current team and architecture, read on!</p><h3>Benefits of Amazon Eventbridge</h3><p>Amazon Web Services, in the meanwhile, made numerous strides in allowing customers to build powerful event-driven architectures at scale, most notably through the release of <a href="https://aws.amazon.com/eventbridge/">Amazon EventBridge</a> in mid-2019, with additional capability to <a href="https://aws.amazon.com/blogs/aws/new-use-amazon-s3-event-notifications-with-amazon-eventbridge/">directly send S3 events to it in late 2021</a>.</p><p>This new method of handling and processing S3 events provides a number of benefits, including but not limited to:</p><ul><li>Flexible <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-patterns-content-based-filtering.html">event filtering</a> capabilities</li><li>Fan-out to a <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-targets.html">larger number of services</a></li><li><a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-archive.html">Archive and replay</a></li><li><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_Events.html">Flexible deployment options via IaaC</a>, allowing users to deploy Event Buses, Rules and Targets as separate resources.</li></ul><p>Naturally, many customers have requested a direct integration between Snowpipe and Eventbridge. In response, Snowflake is now offering support for automation of Snowpipe via S3 events routed via EventBridge while doing away with S3 Event Notifications altogether!</p><h3>Setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YO1xuBmeQQsAHUcJfnt2qw.png" /></figure><p>We will create a simple pipeline with an Amazon S3 bucket with Eventbridge events configured, a Eventbridge rule, SNS topic and Snowpipe. We will then test with a simple data generator that uploads JSON records with randomised data into S3, under the landing/ prefix.</p><h4>0. Prerequisites</h4><blockquote><strong>Note:</strong> Amazon Eventbridge for S3 events is not part of the free tier. Please see <a href="https://aws.amazon.com/eventbridge/pricing/">pricing</a> for more details. At $1 per million events triggered it won’t break the bank but it’s not $0 either!</blockquote><ul><li>A Snowflake account with ACCOUNTADMIN privileges (Consider signing up for a <a href="https://signup.snowflake.com/">free trial account</a> — highly recommended you select the AWS edition for this exercise)</li><li>An AWS account with enough privileges.</li><li>AWS CLI with access keys set up.</li></ul><p>This set-up takes multiple steps across a number of services so this will be demonstrated via AWS CLI commands for simplicity.</p><h4>1. Create S3 bucket with EventBridge Notifications</h4><blockquote><strong>Note</strong>: We recommend you set up your S3 buckets in the same region as your Snowflake account.</blockquote><p>We can create a S3 bucket and enabled S3 EventBridge Notifications from the CLI. This can alternatively be easily done via the Management Console, with all other settings left to default.</p><pre>aws s3api create-bucket \<br>  --bucket &lt;your-bucket-name&gt; \<br>  --region &lt;your-region&gt; \<br>  --create-bucket-configuration LocationConstraint=&lt;your-region&gt;<br><br>aws s3api put-bucket-notification-configuration \<br>  --bucket &lt;your-bucket-name&gt; \<br>  --notification-configuration=&#39;{ &quot;EventBridgeConfiguration&quot;: {} }&#39;</pre><h4>2. Set up secure access between Amazon S3 and Snowflake</h4><p>I’d recommend following the excellent <a href="https://docs.snowflake.com/en/user-guide/data-load-s3-config-storage-integration">step-by-step official documentation</a> on setting up secure access between AWS and Snowflake via a Storage Integration.</p><p>After following the guide, you should have the following set up which you will need for later steps:</p><ul><li>IAM Role with an IAM policy granting access to your S3 bucket, with trust relationship set-up to allow the Snowflake IAM User to assume the role</li><li>A Snowflake STORAGE INTEGRATION configured for the S3 path and IAM Role</li></ul><h4>3. Set up Simple Notification Service</h4><p>We will now create a Simple Notification Service (SNS) topic where Eventbridge sends events to.</p><pre>aws sns create-topic --name eventbridge-to-snowpipe-topic</pre><p>Snowpipe subscribes to the SNS topic directly. This means we need to grant permissions for Snowflake IAM User to subscribe to this topic. Snowflake provides a function that generates the IAM policy for you:</p><pre>select system$get_aws_sns_iam_policy(&#39;arn:aws:sns:&lt;your-aws-region&gt;:&lt;your-account-no&gt;:eventbridge-to-snowpipe-topic&#39;);</pre><p>Which returns the following:</p><pre>{<br>  &quot;Version&quot; : &quot;2012-10-17&quot;,<br>  &quot;Statement&quot; : [<br>    {<br>      &quot;Sid&quot; : &quot;1&quot;,<br>      &quot;Effect&quot; : &quot;Allow&quot;,<br>      &quot;Principal&quot; : {<br>        &quot;AWS&quot; : &quot;arn:aws:iam::&lt;snowflake-aws-account-no&gt;:user/&lt;snowflake-aws-iam-username&gt;&quot;<br>      },<br>      &quot;Action&quot; : [&quot;sns:Subscribe&quot;],<br>      &quot;Resource&quot; : [&quot;arn:aws:sns:&lt;your-aws-region&gt;:&lt;your-account-no&gt;:eventbridge-to-snowpipe-topic&quot;]<br>    }<br>  ]<br>}</pre><p>We then merge this into the existing SNS resource policy as an additional element under the &quot;Statement&quot; list. This can be done easily from the Management Console, or via the CLI:</p><pre>aws sns set-topic-attributes \<br>--topic-arn arn:aws:sns:&lt;your-aws-region&gt;:&lt;your-account-no&gt;:eventbridge-to-snowpipe-topic \<br>--attribute-name Policy \<br>--attribute-value &#39;{ <br>    &quot;Version&quot;: &quot;2008-10-17&quot;, <br>    &quot;Id&quot;: &quot;__default_policy_ID&quot;, <br>    &quot;Statement&quot;: [ <br>        { <br>            &quot;Sid&quot;: &quot;__default_statement_ID&quot;, <br>            &quot;Effect&quot;: &quot;Allow&quot;, <br>            &quot;Principal&quot;: { &quot;AWS&quot;: &quot;*&quot; }, <br>            &quot;Action&quot;: [ <br>                &quot;sns:GetTopicAttributes&quot;, <br>                &quot;sns:SetTopicAttributes&quot;, <br>                &quot;sns:AddPermission&quot;, <br>                &quot;sns:RemovePermission&quot;, <br>                &quot;sns:DeleteTopic&quot;, <br>                &quot;sns:Subscribe&quot;, <br>                &quot;sns:ListSubscriptionsByTopic&quot;, <br>                &quot;sns:Publish&quot; <br>            ], <br>            &quot;Resource&quot;: &quot;arn:aws:sns:&lt;your-aws-region&gt;:&lt;your-account-no&gt;:eventbridge-to-snowpipe-topic&quot;, <br>            &quot;Condition&quot;: { <br>                &quot;StringEquals&quot;: {<br>                    &quot;AWS:SourceOwner&quot;: &quot;&lt;your-account-no&gt;&quot; <br>                } <br>            } <br>        },<br>        {<br>          &quot;Sid&quot; : &quot;1&quot;,<br>          &quot;Effect&quot; : &quot;Allow&quot;,<br>          &quot;Principal&quot; : {<br>            &quot;AWS&quot; : &quot;arn:aws:iam::&lt;snowflake-aws-account-no&gt;:user/&lt;snowflake-aws-iam-username&gt;&quot;<br>          },<br>          &quot;Action&quot; : [&quot;sns:Subscribe&quot;],<br>          &quot;Resource&quot; : [&quot;arn:aws:sns:&lt;your-aws-region&gt;:&lt;your-account-no&gt;:eventbridge-to-snowpipe-topic&quot;]<br>        }<br>    ] <br>}&#39;</pre><h4>4. Set up Eventbridge Rule &amp; Target</h4><p>All AWS-generated events are routed to the default Event Bus, which should already exist in your AWS account. Therefore, we only need to create an EventBridge Rule &amp; Target that filters on S3 events from our new bucket and sends to the SNS topic we’ve just created:</p><pre>aws events put-rule --name eventbridge-to-sns-rule \<br>--event-pattern &#39;{<br>    &quot;source&quot;: [ &quot;aws.s3&quot; ], <br>    &quot;detail-type&quot;: [ &quot;Object Created&quot; ],<br>    &quot;region&quot;: [ &quot;&lt;your-aws-region&gt;&quot; ],<br>    &quot;resources&quot;: [ &quot;arn:aws:s3:::&lt;your-buckets-name&gt;&quot; ],<br>    &quot;detail&quot;: { <br>        &quot;bucket&quot;: { &quot;name&quot;: [ &quot;&lt;your-buckets-name&gt;&quot; ] },<br>        &quot;object&quot;: { &quot;key&quot;: [ { &quot;prefix&quot;: &quot;landing/&quot; } ] }<br>    } <br>}&#39; \<br>--state ENABLED \<br>--description &quot;EventBridge rule for S3 object creation&quot;<br><br>aws events put-targets \<br>--rule eventbridge-to-sns-rule \<br>--targets &quot;Id&quot;=&quot;1&quot;,&quot;Arn&quot;=&quot;arn:aws:sns:&lt;your-aws-region&gt;:&lt;your-account-no&gt;:eventbridge-to-snowpipe-topic&quot;</pre><p>EventBridge Rules support up to five targets per rule. This means you can also leverage the same rule to push the same event to other services you’d like, which could simplify your overall event-driven architecture on AWS.</p><h4>5. Set up Snowflake</h4><p>Now let’s create the landing zone in Snowflake where the data will be ingested into, including the Snowpipe and landing table:</p><pre>use role ACCOUNTADMIN;<br><br>--Create DB &amp; Schema <br>create or replace database SNOWPIPE_EVENTBRIDGE_DEMO;<br>create or replace schema SNOWPIPE_EVENTBRIDGE_DEMO.LANDING;<br><br>use database SNOWPIPE_EVENTBRIDGE_DEMO;<br>use schema LANDING;<br><br>--Create stage object<br>--You should already have a STORAGE INTEGRATION created from Step 2.<br>create or replace stage eventbridge_s3_stage<br>url = &#39;s3://&lt;your-s3-bucket-name&gt;/landing/&#39;<br>storage_integration = &lt;your-storage-integration-name&gt;<br><br>--Landing table<br>create or replace table snowpipe_eventbridge_landing (<br>  record variant<br>);<br><br>--Snowpipe<br>create or replace pipe eventbridge_pipe<br>auto_ingest = true<br>aws_sns_topic = &#39;arn:aws:sns:&lt;your-aws-region&gt;:&lt;your-account-no&gt;:eventbridge-to-snowpipe-topic&#39;<br>as <br>    copy into snowpipe_eventbridge_landing<br>    from @eventbridge_s3_stage<br>    file_format = ( type = &#39;JSON&#39; );<br></pre><h4>6. Load data into S3</h4><p>Now with the pipeline set up, we can try loading some data into S3. Here’s a simple bash script that generates a JSON record every 15 seconds and uploads to S3:</p><pre>#!/bin/bash<br><br># S3 bucket information<br>BUCKET_NAME=&quot;&lt;your-bucket-name&gt;&quot;<br>REGION=&quot;&lt;your-aws-region&gt;&quot;<br><br># Loop forever<br>while true; do<br>  # Generate a random JSON record<br>  json_record=$(jq -n &#39;{id: $id, name: $name, age: $age}&#39; --arg id $(uuidgen) --arg name $(shuf -n 1 names.txt) --arg age $(shuf -i 18-60 -n 1))<br><br>  # Upload the record to S3<br>  aws s3 cp - s3://${BUCKET_NAME}/landing/$(date +%Y-%m-%d-%H-%M-%S).json --region ${REGION} &lt;&lt;&lt; &quot;${json_record}&quot;<br><br>  # Wait 15 seconds before generating the next record<br>  sleep 15<br>done</pre><h4>7. Check that data is landing</h4><p>Whenever new data is loaded into S3, the following sequence should trigger automatically:</p><ul><li>S3 sends a PutObject event to the default Eventbridge Event Bus</li><li>The Eventbridge Rule is invoked, routing the event to the SNS topic</li><li>SNS topic then pushes the event payload to a Snowflake-managed SQS queue, which informs Snowpipe of the arrival of the new data in S3</li><li>Snowpipe copies files into a queue, from which they are loaded into the landing table SNOWPIPE_EVENTBRIDGE_LANDING.</li></ul><p>Within a minute or so of starting the bash script, you should be able to see data landing in the SNOWPIPE_EVENTBRIDGE_LANDING table.</p><h4>Troubleshooting</h4><p>On Snowflake side, you can query either the COPY_HISTORY information schema view or call the SYSTEM$PIPE_STATUS() function:</p><pre>--Files loaded into the table in the past hour<br>select *<br>from table(<br>    information_schema.copy_history(<br>        TABLE_NAME=&gt;&#39;SNOWPIPE_EVENTBRIDGE_LANDING&#39;, <br>        START_TIME=&gt; DATEADD(hours, -1, CURRENT_TIMESTAMP())<br>    )<br>)<br>order by last_load_time desc;<br><br>--Returns current status of the pipe<br>select SYSTEM$PIPE_STATUS(&#39;EVENTBRIDGE_PIPE&#39;);</pre><p>You can also check permissions between S3 and Snowflake. One way I like to use to check for any 403 errors is to query the stage directly: select $1 from @eventbridge_s3_stage</p><p>On the AWS side, here is a list of common things you can look at if data isn’t flowing into Snowflake, and nothing is reported when checking Snowflake’s COPY HISTORY view:</p><ul><li>From Cloudwatch, you can check the number of invocations of the Eventbridge Rule. If there aren’t any, check that the event pattern associated with the rule is correctly formed and defined (S3 prefix shenanigans is a common one!)</li><li>Ensure that Snowflake has permissions to subscribe to the SNS topic</li><li>Ensure that the Eventbridge rule has permissions to publish to the SNS topic. Errors here commonly occur if you overwrite or erase the existing SNS topic resource policy.</li></ul><h3>Conclusion</h3><p>Integration of Amazon Eventbridge with Snowpipe enables a more powerful and flexible method of automating loading of data from Amazon S3 into Snowflake. With flexible event routing, deployment and integrations with other services, you can easily integrate Snowflake ingestion pipelines into a cost-effective event-driven architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5ef27504949" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/automating-snowpipe-with-aws-eventbridge-a5ef27504949">Automating Snowpipe with AWS Eventbridge</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>