<?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 Yohei Onishi on Medium]]></title>
        <description><![CDATA[Stories by Yohei Onishi on Medium]]></description>
        <link>https://medium.com/@yoheionishi?source=rss-b425735bc044------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r6GW7ho2M1j3Occdf__9jw.jpeg</url>
            <title>Stories by Yohei Onishi on Medium</title>
            <link>https://medium.com/@yoheionishi?source=rss-b425735bc044------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:25:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yoheionishi/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[Scheduled dbt model deployment for Snowflake using AWS ECS and Airflow]]></title>
            <link>https://medium.com/snowflake/scheduled-dbt-model-deployment-for-snowflake-using-aws-ecs-and-airflow-32e3223cb0cf?source=rss-b425735bc044------2</link>
            <guid isPermaLink="false">https://medium.com/p/32e3223cb0cf</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Yohei Onishi]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 17:00:27 GMT</pubDate>
            <atom:updated>2022-12-11T17:00:27.416Z</atom:updated>
            <content:encoded><![CDATA[<p>In my project, I introduced Terraform for Snowflake configuration management and deployment 2 years ago. I initially tried to deploy almost everything, but I have decided to use popular data transformation tool called dbt core (OSS version of dbt) for data object deployment such as table and view due to the following reasons.</p><ul><li>Deployment time has been increased as a number of Terraform resources grows. Terraform requires larger amount of computing resources to update Terraform state.</li><li>Terraform uses HCL to describe Terraform resources. SQL is much easier for most of our Snowflake users to understand than HCL.</li><li>dbt is becoming de facto standard for data transformation layer.</li></ul><p>In this article, I will explain how to schedule dbt model deployment for Snowflake using AWS ECS and Airflow.</p><h3>How to deploy dbt models</h3><p>dbt supports not just simple table or view deployment. It also supports complex table update like incremental table update and Slowly Changing Dimension Type 1 or 2. So we have to support 2 different type of deployment for dbt models.</p><ul><li>(1) One-time table or view deployment</li><li>(2) Scheduled table replacement or incremental table update</li></ul><p>We only supported the approach (1) using existing CICD pipeline using Terraform. So we needed to support new approach (2).</p><h3>Requirements for scheduled dbt model deployment</h3><p>We had to meet the following requirements to scheduled dbt model deployment.</p><ul><li>Git repository server and CICD pipeline managed in our private Gitlab server by CCOE (Cloud Center of Excellence) team</li><li>We are using AWS MWAA (Managed Workflow for Apache Airflow) for centralized schedule job execution so dbt model deployment should be scheduled in Airflow.</li><li>dbt command should be segregated from Airflow. If it depends on old Airflow library version, we might not be able to use newer version of dbt.</li></ul><h3>CICD pipeline architecture</h3><p>We have built a CICD pipeline architecture as follows.</p><p><em>Note that our Gitlab server and ECR repositories are managed by CCOE (Cloud Center of Excellence) team. My Data Engineering Team only manages Airflow and ECS cluster in our separate AWS accounts.</em></p><ol><li>dbt model source code is managed in our Gitlab repository. New changes must be merged to our repository.</li><li>One-time model deployment is done by CICD pipeline when we merged new change to our repository.</li><li>CICD pipeline also build and push a container image for dbt model source code to ECR repository.</li><li>Airflow DAG trigger AWS ECS Fargate task for dbt model deployment. Note that ECS cluster and ECS task definition must be deployed in advance.</li><li>The container image will be loaded from ECR to ECS.</li><li>dbt command is executed in container, and it updates a table.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*YcKjdpDHEOST1tICbSUypg.png" /><figcaption>dbt model deployment pipeline</figcaption></figure><h3>Small tips to support 2 different type of deployment</h3><p>To support 2 different type of deployment, dbt needs to be able to detect which model should be deployed in scheduled jobs. We are using a tag as below for this requirement.</p><p><a href="https://docs.getdbt.com/reference/resource-configs/tags">tags | dbt Developer Hub</a></p><pre>{{<br>  config(<br>   tags=&quot;scheduled&quot;<br>  )<br>}}</pre><p>We exclude models with <strong>tags:scheduled</strong> when we do one-time deployment to avoid model deployment in unexpected timing.</p><pre>dbt run — exclude tag:scheduled</pre><p>On the other hand, we run specific model as below in a scheduled ECS container.</p><pre>dbt run — select model_name</pre><h3>Summary</h3><p>In this article, I explained the approach we use to support one time and scheduled dbt model deployment in my projects.</p><p>I understand that many dbt users use dbt Cloud for dbt model deployment scheduling. By using external job scheduling like Airflow, we can implement more complex job scheduling such as coordinating job execution with other jobs.</p><p>Hope this article help my readers understand available dbt model deployment options.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32e3223cb0cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/scheduled-dbt-model-deployment-for-snowflake-using-aws-ecs-and-airflow-32e3223cb0cf">Scheduled dbt model deployment for Snowflake using AWS ECS and Airflow</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[How to reduce Snowflake compute cost for high frequent data loading by ETL tool]]></title>
            <link>https://medium.com/snowflake/why-high-frequent-data-loading-becomes-expensive-in-snowflake-9c6d43ac14ab?source=rss-b425735bc044------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c6d43ac14ab</guid>
            <category><![CDATA[data-superhero]]></category>
            <dc:creator><![CDATA[Yohei Onishi]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 08:09:05 GMT</pubDate>
            <atom:updated>2022-10-09T16:55:53.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*Nymlk7oQ53UlO8Eg5NwjJA.png" /><figcaption>Near real time data pipeline using AWS DMS and Snowflake</figcaption></figure><p>AWS DMS and Snowpipe would be one of the most popular tools when you replicate data from on-premise database or AWS RDS database to Snowflake table in near real time because of the following reasons.</p><ul><li>AWS DMS (Data Migration Service) is AWS’s official database migration service.</li><li>AWS DMS does not support Snowflake but can export data to S3 bucket.</li><li>Once new file is upload in S3 bucket, Snowpipe can load the file to target Snowflake table immediately.</li></ul><p>If you choose this approach, you will load entire transaction history of the source table to target table. If you want to know the latest records for each primary key or unique key instead of entire history, you also need to maintain the latest records in another table using Stream and Task just like the upper pipeline in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*s87wHp8gI2wL4bv3nAYImg.png" /><figcaption>(1) AWS DMS + Snowpipe vs (2) Direct table sync using ETL tool</figcaption></figure><p>This is cost-efficient approach as compute cost for Snowpipe is quite cheap, but you might feel you do not want to implement Stream and Task just to replicate data.</p><p>Some RDBMS also provides database migration tool that can directly sync source table to target table in Snowflake just like the lower pipeline in the above diagram. This can reduce development cost compared with DMS and Snowpipe approach, so I tried this in my project, but it turns out that warehouse cost for this type of high frequent data loading is quite expensive.</p><p>This issue would also happen when you use ETL service like Fivetran. It is not an issue on specific tool. I will explain why high frequent data loading is expensive in this article.</p><h3>Why warehouse cost for high frequent data loading is expensive?</h3><ul><li>(1) DMS and Snowpipe</li><li>(2) Direct table sync by DB migration tool</li></ul><p>If you compare how warehouse is used in these 2 approaches, you would notice that (1) Snowpipe approach uses Snowflake managed warehouse, which automatically optimize computing resources used in your workload. This can reduce warehouse cost. See below URL for more about Snowpipe cost.</p><p><a href="https://docs.snowflake.com/en/user-guide/data-load-snowpipe-billing.html">Understanding Billing for Snowpipe Usage - Snowflake Documentation</a></p><p>On the other hand, (2) direct table sync by DB migration tool uses a user managed warehouse. In our project, default configurations for the warehouse was like follows. If the tool loads data frequently such as every minute, it would keep the warehouse running. Snowflake also even start new warehouse when new data comes in before the auto suspend time has passed. This would also increase compute cost.</p><ul><li>Multi cluster warehouse</li><li>Default scaling policy: Snowflake tries to keep latency minimum by starting a new warehouse</li><li>Default auto suspend time: 10 minutes</li></ul><p>Snowflake warehouse cost is calculated based on warehouse size * a number of warehouses * duration of warehouse running instead of data volume. Even if data volume is small, warehouse cost would increase if more warehouses runs in longer time. See the below URLs for more about warehouse cost.</p><ul><li><a href="https://docs.snowflake.com/en/user-guide/credits.html">Understanding Virtual Warehouse, Storage, and Cloud Services Usage - Snowflake Documentation</a></li><li><a href="https://docs.snowflake.com/en/user-guide/warehouses-considerations.html">Warehouse Considerations - Snowflake Documentation</a></li></ul><h3>What can we do to reduce warehouse cost?</h3><p>As already explained, Snowflake warehouse cost is calculated based on warehouse size * a number of warehouses * duration of warehouse running.</p><p>In this pricing model, high frequent small data loading is not cost-efficient. So it would be better to think if you really need it and the cost is acceptable. If not, you should decrease frequency of data loading such as hourly, daily, etc. and load larger amount of data at a time and stop the warehouse.</p><p>In that case, you can change the following configurations if you prefer minimum cost approach. Note that warehouse cache is cleared once when a warehouse is restarted. There is some latency to restart a warehouse, so there are some risk that latency of your queries would increase.</p><ul><li>Set economy to scaling policy: Snowflake will try not to start new warehouse</li><li>Make auto suspend time shorter than the default value (10 minutes)</li></ul><h3>Summary</h3><p>In this article, I have explained Snowflake warehouse pricing model, especially for the case where you use external ETL tool such as AWS DMS or Fivetran. Depending on your use case and budge for infra cost, you need to understand the pricing model and change configurations of your warehouse to optimize your warehouse workload and computing cost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c6d43ac14ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/why-high-frequent-data-loading-becomes-expensive-in-snowflake-9c6d43ac14ab">How to reduce Snowflake compute cost for high frequent data loading by ETL tool</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[How to use an encrypted private key in key pair authentication with Terraform plugin for Snowflake]]></title>
            <link>https://medium.com/snowflake/how-to-use-an-encrypted-private-key-in-key-pair-authentication-with-terraform-plugin-for-snowflake-ba5ea63278ec?source=rss-b425735bc044------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba5ea63278ec</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-superhero]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[cipher]]></category>
            <dc:creator><![CDATA[Yohei Onishi]]></dc:creator>
            <pubDate>Thu, 26 May 2022 17:37:45 GMT</pubDate>
            <atom:updated>2022-05-27T10:16:33.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*2OPSEZk6BQmKyNLoZM5iSw.png" /></figure><h3>Background</h3><p><a href="https://registry.terraform.io/providers/Snowflake-Labs/snowflake/latest/docs">Snowflake official Terraform provider</a> is implemented in <a href="https://docs.snowflake.com/en/user-guide/go-driver.html">Go Snowflake Driver</a> so it can support all the authentication method supported in Go Driver.</p><p><a href="https://registry.terraform.io/providers/Snowflake-Labs/snowflake/latest/docs#authentication">https://registry.terraform.io/providers/Snowflake-Labs/snowflake/latest/docs#authentication</a></p><blockquote>The Snowflake provider support multiple ways to authenticate:</blockquote><blockquote>Password</blockquote><blockquote>OAuth Access Token</blockquote><blockquote>OAuth Refresh Token</blockquote><blockquote>Browser Auth</blockquote><blockquote>Private Key</blockquote><blockquote>In all cases account, username, and region are required.</blockquote><p>I have been using private key for Snowflake resource deployment using Terraform.</p><p>When I introduced Snowflake and Terraform provider in my projects in Feb 2021, it did not support encrypted private key for key pair authentication as discussed in the page. To use unencrypted private key for key pair authentication, I had to store the private key in AWS Secret Manager then retrieve the key during deployment so we do not need to expose the private key key in Git repo.</p><p><a href="https://github.com/Snowflake-Labs/terraform-provider-snowflake/discussions/440">https://github.com/Snowflake-Labs/terraform-provider-snowflake/discussions/440</a></p><p>However, the driver currently support encrypted private key as of May 2022 so I will introduce about key pair authentication in Terraform driver for Snowflake.</p><h3>PoC environment</h3><p>I have verified the feature using the following environment.</p><ul><li>MacOS 10.15.6</li><li>openssl version LibreSSL 2.8.3</li><li>Terraform v1.1.7 on darwin_amd64</li><li>provider registry.terraform.io/snowflake-labs/snowflake v0.33.1</li></ul><h3><strong>Generate a key pair</strong></h3><p>The following URL explains how to generate a key pair for Snowflake clients.</p><p><a href="https://docs.snowflake.com/en/user-guide/key-pair-auth.html#step-1-generate-the-private-key">https://docs.snowflake.com/en/user-guide/key-pair-auth.html#step-1-generate-the-private-key</a></p><p>The document use this command for key pair generation.</p><pre>cd ~/.ssh<br>openssl genrsa -out snowflake_key 4096<br>openssl rsa -in snowflake_key -pubout -out snowflake_key.pub<br>openssl pkcs8 -topk8 -inform pem -in snowflake_key -outform PEM -v2 aes-256-cbc -out snowflake_key.p8</pre><p>However, Terraform will fail if you use a private key generated using the command above.</p><blockquote>could not build dsn for snowflake connection: Private Key could not be parsed: Could not parse encrypted private key with passphrase, only ciphers aes-128-cbc, aes-128-gcm, aes-192-cbc, aes-192-gcm, aes-256-cbc, aes-256-gcm, and des-ede3-cbc are supported: pkcs8: only PBES2 supported</blockquote><p>The error message suggests us to use the following ciphers.</p><ul><li>aes-128-cbc</li><li>aes-128-gcm</li><li>aes-192-cbc</li><li>aes-192-gcm</li><li>aes-256-cbc</li><li>aes-256-gcm</li><li>des-ede3-cbc</li></ul><p>The following Terraform driver document also explain the same thing mentioned above.</p><p><a href="https://registry.terraform.io/providers/Snowflake-Labs/snowflake/latest/docs#keypair-authentication-passhrase">https://registry.terraform.io/providers/Snowflake-Labs/snowflake/latest/docs#keypair-authentication-passhrase</a></p><pre>cd ~/.ssh</pre><pre>openssl genrsa -out snowflake_key 4096</pre><pre>openssl rsa -in snowflake_key -pubout -out snowflake_key.pub</pre><pre>openssl pkcs8 -topk8 -inform pem -in snowflake_key -outform PEM -v2 aes-256-cbc -out snowflake_key.p8</pre><ul><li>The second command generate a RDS private key (unencrypted). <a href="https://www.openssl.org/docs/man1.1.1/man1/openssl-genrsa.html">https://www.openssl.org/docs/man1.1.1/man1/openssl-genrsa.html</a></li><li>The third command generate a public key for the private key above.</li><li>The fourth command generate an encrypted private key using a cipher aes-256-cbc. Please refer the following URL for more about AES 256 CBC.https://datatracker.ietf.org/doc/html/rfc3602</li></ul><h3>Apply the public key for a Snowflake user for deployment</h3><p>As mentioned in the document below, you need to apply the content of the public key to Snowflake user you use for deployment.</p><p><a href="https://docs.snowflake.com/en/user-guide/key-pair-auth.html#step-4-assign-the-public-key-to-a-snowflake-user">https://docs.snowflake.com/en/user-guide/key-pair-auth.html#step-4-assign-the-public-key-to-a-snowflake-user</a></p><pre>ALTER USER terraform SET RSA_PUBLIC_KEY = “””xxxxxx”””</pre><h3><strong>Set the encrypted private key in Terraform provider configuration</strong></h3><p>As mentioned in the document below, you need to set private key file path in Terraform provider configuration.</p><p><a href="https://registry.terraform.io/providers/Snowflake-Labs/snowflake/latest/docs#example-provider-configuration">https://registry.terraform.io/providers/Snowflake-Labs/snowflake/latest/docs#example-provider-configuration</a></p><pre>provider &quot;snowflake&quot; {<br>  username = &quot;terraform&quot;<br>  account  = &quot;xxx&quot;<br>  private_key_path       = &quot;./rsa_key.p8&quot;<br>  role                   = &quot;xxxx&quot;<br>}</pre><p>You can provide passphrase as an environment variable as below. Most of all major CICD service such as GitHub Actions, Gitlab CI/CD, AWS Code Build support secure way to store credential. You can use it to store passphrase securely in CICD pipeline.</p><pre>SNOWFLAKE_PRIVATE_KEY_PASSPHRASE=xxxx terraform plan --out out.tfplan</pre><h3>Summary</h3><p>I explained how to use encrypted private key in key pair authentication for Terraform driver for Snowflake in this article.</p><ul><li>Security requirement for private key is becoming more strict. You should use security configuration recommended in Cloud Service or tool you are using.</li><li>You need to provide passphrase to decrypt your encrypted private key.</li><li>You can provide passphrase as environment Variable.</li></ul><p>I hope this article would help DevOps engineers who use Snowflake :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba5ea63278ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/how-to-use-an-encrypted-private-key-in-key-pair-authentication-with-terraform-plugin-for-snowflake-ba5ea63278ec">How to use an encrypted private key in key pair authentication with Terraform plugin for Snowflake</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[Connecting an AWS Glue job with Snowflake Private Endpoint using Private Link]]></title>
            <link>https://medium.com/snowflake/connecting-aws-glue-job-with-snowflake-private-endpoint-using-private-link-e9c13af4e14f?source=rss-b425735bc044------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c13af4e14f</guid>
            <category><![CDATA[aws-privatelink]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[data-superhero]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Yohei Onishi]]></dc:creator>
            <pubDate>Sun, 08 May 2022 07:45:35 GMT</pubDate>
            <atom:updated>2022-05-09T05:52:01.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>When you want to transform data in Snowflake for your data analytics use case, you would usually implement data transformation logic in SQL and create a view or a table. On the other hand, if the logic is too complicated to implement in SQL, <a href="https://docs.snowflake.com/en/developer-guide/snowpark/index.html">Snowpark</a>, which is Snowflake version of Data Frame API, would comes in handy. Your data transformation logic in Data Frame will be transformed into SQL and your data will be processed in Snowflake.</p><p>However, only Snowpark Scala API is in generally available as of May 2022, <a href="https://www.snowflake.com/blog/https-www-snowflake-com-blog-snowday-python-comes-to-snowpark/">Snowpark Python API</a> is still in Private Preview, which is not available in production system. As an alternative solution of Snowpark Python API, <a href="https://aws.amazon.com/glue/">AWS Glue</a>, which is serverless Spark service in AWS, would be very useful.</p><p>In this article, I will explain how to connect Glue job with Snowflake, especially via VPC endpoint using <a href="https://aws.amazon.com/privatelink/">AWS Private Link</a>. AWS Private Link is widely used in large enterprises to connect VPCs in their own AWS accounts with 3rd party services in AWS. If you are using Private Link for your Snowflake account, your Glue job requires custom Glue connection with VPC configuration to connect with Snowflake private endpoint.</p><h3>Network configuration</h3><p>Assume that you have network configuration as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*S43YqCdnIO2b4rG1UzQMXw.png" /></figure><ul><li>Your Snowflake account must be deployed in AWS.</li><li>VPCs in both AWS accounts are already connected by AWS Private Link. Please follow the below instruction for how to set up Private Link.</li></ul><p><a href="https://docs.aws.amazon.com/vpc/latest/privatelink/endpoint-services-overview.html">https://docs.aws.amazon.com/vpc/latest/privatelink/endpoint-services-overview.html</a><br> <a href="https://docs.snowflake.com/en/user-guide/admin-security-privatelink.html">https://docs.snowflake.com/en/user-guide/admin-security-privatelink.html</a></p><ul><li>Your Glue job will be deployed in your AWS VPC then connect to your Snowflake account via VPC endpoint using Private Link. Note that you need a Glue connection in a VPC when your target JDBC database is also in the VPC. <a href="https://docs.aws.amazon.com/glue/latest/dg/connection-JDBC-VPC.html">https://docs.aws.amazon.com/glue/latest/dg/connection-JDBC-VPC.html</a></li><li>As far as I know, Glue connection does not support Snowflake JDBC URL directly. In this case, you need to create a Glue connector first then create a Glue connection for Snowflake JDBC URL from the connection. <a href="https://docs.aws.amazon.com/glue/latest/ug/connectors-chapter.html">https://docs.aws.amazon.com/glue/latest/ug/connectors-chapter.html</a></li></ul><h3>Glue job Set up</h3><p>In this section, I will explain how to set up Glue job that can connect to Snowflake private endpoint using Private Link.</p><h4>Private Link must be set up in advance</h4><p>Assume that you have already completed the following configurations.</p><ul><li>Private Link between your own AWS VPC and Snowflake’s VPC.</li><li>You can connect to Snowflake via Private Endpoint.</li></ul><p>If not, please follow the instructions below.</p><ul><li><a href="https://docs.aws.amazon.com/vpc/latest/privatelink/endpoint-services-overview.html">https://docs.aws.amazon.com/vpc/latest/privatelink/endpoint-services-overview.html</a></li><li><a href="https://docs.snowflake.com/en/user-guide/admin-security-privatelink.html">https://docs.snowflake.com/en/user-guide/admin-security-privatelink.html</a></li></ul><h4>Create a Glue connector</h4><p>As mentioned previously, you need to create a Glue connector before you create a Glue connection for Snowflake JDBC. To create a Glue connector, please follow the following instruction.</p><p><a href="https://docs.aws.amazon.com/glue/latest/ug/connectors-chapter.html?icmpid=docs_glue_studio_helppanel#creating-connectors">https://docs.aws.amazon.com/glue/latest/ug/connectors-chapter.html?icmpid=docs_glue_studio_helppanel#creating-connectors</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrwtcUeRwQexlVHEPA4qHA.png" /></figure><ul><li>Connector S3 URL: S3 URL you upload custom code</li><li>Name: Connector name</li><li>Connector type: JDBC</li><li>Class name: net.snowflake.client.jdbc.SnowflakeDriver</li><li>JDBC URL base: <a href="https://$account-id.$region-name.privatelink.snowflakecomputing.com/%60">https://$account-id.$region-name.privatelink.snowflakecomputing.com:443/</a></li><li>$account-id and $region-name must be replaced with appropriate values.</li><li>URL parameter delimiter: &amp;</li></ul><h4>Create a Glue connection</h4><p>You can create a Glue connection in the details page of the Glue connector you previously created. Please follow this instruction to create a Glue connection.<br><a href="https://docs.aws.amazon.com/glue/latest/ug/connectors-chapter.html?icmpid=docs_glue_studio_helppanel#creating-connections">https://docs.aws.amazon.com/glue/latest/ug/connectors-chapter.html?icmpid=docs_glue_studio_helppanel#creating-connections</a></p><ul><li>Name: Connection Name</li><li>Description: (Optional)</li><li>Connection access</li><li>Connection credential type: default</li><li>Additional URL parameters: (Optional)</li><li>You can add parameters to your JDBC URL. Please refer this URL for more details. <a href="https://docs.snowflake.com/en/user-guide/jdbc-configure.html#jdbc-driver-connection-string">https://docs.snowflake.com/en/user-guide/jdbc-configure.html#jdbc-driver-connection-string</a></li><li>Network options</li><li>VPC: Choose the VPC you set up Private Link</li><li>Subnet: Choose a subnet from the VPC</li><li>Security groups: Choose a security group for a Glue job</li><li>The security group must have inbound and outbound configurations mentioned in this URL. <a href="https://docs.aws.amazon.com/glue/latest/dg/setup-vpc-for-glue-access.html">https://docs.aws.amazon.com/glue/latest/dg/setup-vpc-for-glue-access.html</a></li></ul><h4>Download Snowflake JDBC/Spark Driver</h4><p>The following drivers (jar files) are required to connect to Snwoflake using JDBC and load data into Data Frame.</p><ul><li>JDBC <a href="https://docs.snowflake.com/en/user-guide/jdbc-download.html">https://docs.snowflake.com/en/user-guide/jdbc-download.html</a></li><li>Spark <a href="https://docs.snowflake.com/en/user-guide/spark-connector-install.html">https://docs.snowflake.com/en/user-guide/spark-connector-install.html</a></li><li>Choose spark-snowflake_2.12 since Glue version 3.0 only support Scala version 2.12.</li></ul><p>Then upload the jar files to your S3 bucket.</p><h4>Create a Glue job</h4><p>You can create a new Glue job from the Glue connection details page.</p><p><a href="https://docs.aws.amazon.com/glue/latest/dg/add-job.html">https://docs.aws.amazon.com/glue/latest/dg/add-job.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mtxy3XMzHNUH6YIwmG74Rg.png" /></figure><ul><li>Basic properties</li><li>Name: Glue job name</li><li>Description: (Optional)</li><li>IAM Role: Choose an IAM role for the Glue job</li><li>Minimum requirement of the IAM role is AWSGlueServiceRole and read access to the driver jar files on the s3 bucket.</li><li>If you need to access more AWS resources, please attach more IAM policy.<br> <a href="https://docs.aws.amazon.com/glue/latest/dg/using-identity-based-policies.html#access-policy-examples-aws-managed">https://docs.aws.amazon.com/glue/latest/dg/using-identity-based-policies.html#access-policy-examples-aws-managed</a></li><li>Type: Spark</li><li>Glue version: 3.0</li><li>Please refer this URL for more details about each Glue version. <a href="https://docs.aws.amazon.com/glue/latest/dg/release-notes.html?icmpid=docs_glue_studio_helppanel">https://docs.aws.amazon.com/glue/latest/dg/release-notes.html?icmpid=docs_glue_studio_helppanel</a></li><li>Language: Python 3</li><li>Advanced properties</li><li>Script filename: (default name is the same as job name)</li><li>Script path: S3 URL for Glue job script</li><li>Spark UI logs path: S3 URL for Spark UI logs</li><li>Temporary path: S3 URL for working directory</li><li>Connections: Choose the Glue connection you created</li><li>Libraries</li><li>Dependent JARs path: S3 URLs for JDBC and dSpark drivers. You need to use “,” to specify more than 1 URL.</li><li>e.g. s3://mybucket/snowflake-jdbc-xxx.jar,s3://mybucket/snowflake-spark-xxx.jar</li><li>Job parameters</li><li>It would be better to provide Snowflake connection parameters for better reusability. I will provide password as a parameter this time but the password should be provide as a secret in Secret Manager.</li><li>URL: <a href="https://$account-id.$region-name.privatelink.snowflakecomputing.com/%60">https://$account-id.$region-name.privatelink.snowflakecomputing.com:443/</a></li><li>$account-id and $region-name must be replaced with appropriate values.</li><li>ACCOUNT: Snowflake account name</li><li>WAREHOUSE: Warehouse name</li><li>DB: Database name</li><li>SCHEMA: Schema name</li><li>USERNAME: User name</li><li>PASSWORD: Password</li><li>Script — Unlock the script editor and paste the following sample code. ”table_name” is a source table and ”new_table_name” is a target table for the Glue job. This sample code assume that the Snowflake user has READ access for the source table and write access to the target table.<br><a href="https://community.snowflake.com/s/article/How-To-Use-AWS-Glue-With-Snowflake">https://community.snowflake.com/s/article/How-To-Use-AWS-Glue-With-Snowflake</a></li></ul><pre>import sys<br>from awsglue.transforms import *<br>from awsglue.utils import getResolvedOptions<br>from pyspark.context import SparkContext<br>from awsglue.context import GlueContext<br>from awsglue.job import Job<br>from py4j.java_gateway import java_import<br>SNOWFLAKE_SOURCE_NAME = &quot;net.snowflake.spark.snowflake&quot;;</pre><pre>## <a href="http://twitter.com/params">@params</a>: [JOB_NAME, URL, ACCOUNT, WAREHOUSE, DB, SCHEMA, USERNAME, PASSWORD]<br>args = getResolvedOptions(sys.argv, [&#39;JOB_NAME&#39;, &#39;URL&#39;, &#39;ACCOUNT&#39;, &#39;WAREHOUSE&#39;, &#39;DB&#39;, &#39;SCHEMA&#39;, &#39;USERNAME&#39;, &#39;PASSWORD&#39;])<br>sc = SparkContext()<br>glueContext = GlueContext(sc)<br>spark = glueContext.spark_session<br>job = Job(glueContext)<br>job.init(args[&#39;JOB_NAME&#39;], args)<br>java_import(spark._jvm, &quot;net.snowflake.spark.snowflake&quot;)</pre><pre>## uj = sc._jvm.net.snowflake.spark.snowflake<br>spark._jvm.net.snowflake.spark.snowflake.SnowflakeConnectorUtils.enablePushdownSession(spark._jvm.org.apache.spark.sql.SparkSession.builder().getOrCreate())<br>sfOptions = {<br>&quot;sfURL&quot; : args[&#39;URL&#39;],<br>&quot;sfAccount&quot; : args[&#39;ACCOUNT&#39;],<br>&quot;sfUser&quot; : args[&#39;USERNAME&#39;],<br>&quot;sfPassword&quot; : args[&#39;PASSWORD&#39;],<br>&quot;sfDatabase&quot; : args[&#39;DB&#39;],<br>&quot;sfSchema&quot; : args[&#39;SCHEMA&#39;],<br>&quot;sfWarehouse&quot; : args[&#39;WAREHOUSE&#39;],<br>}</pre><pre>## Read from a Snowflake table into a Spark Data Frame<br>df = spark.read.format(SNOWFLAKE_SOURCE_NAME).options(**sfOptions).option(&quot;dbtable&quot;, &quot;table_name&quot;).load()</pre><pre>## Perform any kind of transformations on your data and save as a new Data Frame: df1 = df.[Insert any filter, transformation, or other operation]<br>## Write the Data Frame contents back to Snowflake in a new table<br>df.write.format(SNOWFLAKE_SOURCE_NAME).options(**sfOptions).option(&quot;dbtable&quot;, &quot;new_table_name&quot;).mode(&quot;overwrite&quot;).save() job.commit()</pre><h3>Run the Glue job</h3><p>After you save the Glue job, you can run the job by pushing the Run button. If no issues with your configuration, the job will complete successfully with <strong>Succeeded</strong> status. Please check if the target table is created in the schema.</p><h3>Conclusion</h3><p>This article introduced AWS Glue job for complex data processing solution.</p><ul><li>If you connect from Glue job to Snowflake private endpoint using Private Link, you need to create a Glue connection with VPC configuration.</li><li>Glue connection does not directly support Snowflake JDBC URL so you need to create custom Glue connection from Glue connector.</li></ul><p>Hope this article for you to set up a Glue job for Snowflake private endpoint.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c13af4e14f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/connecting-aws-glue-job-with-snowflake-private-endpoint-using-private-link-e9c13af4e14f">Connecting an AWS Glue job with Snowflake Private Endpoint using Private Link</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[ISYE6501x: Introduction to Analytics Modeling]]></title>
            <link>https://medium.com/@yoheionishi/isye6501x-introduction-to-analytics-modeling-21af260b6f79?source=rss-b425735bc044------2</link>
            <guid isPermaLink="false">https://medium.com/p/21af260b6f79</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[courses-and-training]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Yohei Onishi]]></dc:creator>
            <pubDate>Sun, 17 May 2020 03:57:15 GMT</pubDate>
            <atom:updated>2020-05-17T04:12:46.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9WKPubUkG5rQXBEm1D1bA.png" /><figcaption>Verified Certificate of Achievement</figcaption></figure><p>I successfully completed “<a href="https://www.edx.org/course/introduction-to-analytics-modeling">ISYE6501x: Introduction to Analytics Modeling</a>” which is one of the series in the “<a href="https://www.edx.org/micromasters/gtx-analytics-essential-tools-and-methods">Analytics: Essential Tools and Methods MicroMasters program</a>” from <a href="https://www.gatech.edu/academics/degrees/masters/analytics-online-degree-oms-analytics">Georgia Tech University</a>.</p><p>This course covers a wide range of analytics modelling techniques and real-world examples. Analytics modelling is a technique to understanding business requirement and data, generating predictions, and making business decisions, according to this course. It includes not just machine learning but also statistical modelling, probability distributions, simulation, optimization, etc.</p><p>This course teaches you important techniques to apply analytics modelling to real-world problems such as evaluating and comparing data/models. I think this is much more useful to learn practical techniques than most of the deep learning courses, which usually do not teach data/model evaluations so much.</p><p>In this course, you must write an analytics model using R except optimization model, which you are asked to implement using a GUI tool or Python’s PySim module. So you should be familiar with R before you start the course. “<a href="https://www.manning.com/books/r-in-action-second-edition">R in Action</a>” and “<a href="https://www.amazon.com/Mastering-Machine-Learning-prediction-algorithms-ebook/dp/B01N5XJ3O0">Mastering Machine Learning with R</a>”.</p><p>For more about the details, please refer to the course website. <a href="https://lnkd.in/gj2m75g">https://lnkd.in/gj2m75g</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21af260b6f79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to switch JDK versions on Mac]]></title>
            <link>https://medium.com/@yoheionishi/how-to-switch-jdk-versions-on-mac-1d5c5f95347b?source=rss-b425735bc044------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d5c5f95347b</guid>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Yohei Onishi]]></dc:creator>
            <pubDate>Fri, 06 Dec 2019 01:36:25 GMT</pubDate>
            <atom:updated>2019-12-06T01:36:25.218Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the easiest way to switch JDK versions I have ever seen.</p><p><a href="https://www.kevinhooke.com/2017/10/05/switching-java-versions-on-mac-os/">Switching Java versions on Mac OS</a></p><p>You can check Java HOME for specific JDK version using Mac specific utilities like this.</p><pre>/usr/libexec/java_home -v 1.8<br>/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home</pre><p>By adding this script in your .bashrc or .zshrc, you will set a command to set JDK to specific version. In this example, I set 1.8 as default JDK version.</p><pre>alias j8=&quot;export JAVA_HOME=`/usr/libexec/java_home -v 1.8`; java -version&quot; <br>alias j11=&quot;export JAVA_HOME=`/usr/libexec/java_home -v 11`; java -version&quot;<br>j8</pre><p>If you want to change it to Java 11, you just run this command.</p><pre>$ j11<br>openjdk version &quot;11.0.5&quot; 2019-10-15 OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.5+10) OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.5+10, mixed mode)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d5c5f95347b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitOps: VPC内リソースにアクセスするDataflowジョブのデプロイをCloud BuildとGKEで自動化する]]></title>
            <link>https://medium.com/google-cloud-jp/gitops-vpc%E5%86%85%E3%83%AA%E3%82%BD%E3%83%BC%E3%82%B9%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%E3%81%99%E3%82%8Bdataflow%E3%82%B8%E3%83%A7%E3%83%96%E3%81%AE%E3%83%87%E3%83%97%E3%83%AD%E3%82%A4%E3%82%92cloud-build%E3%81%A8gke%E3%81%A7%E8%87%AA%E5%8B%95%E5%8C%96%E3%81%99%E3%82%8B-9a4d69ccef96?source=rss-b425735bc044------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a4d69ccef96</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[apache-beam]]></category>
            <dc:creator><![CDATA[Yohei Onishi]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 05:34:44 GMT</pubDate>
            <atom:updated>2019-09-11T05:34:44.367Z</atom:updated>
            <content:encoded><![CDATA[<p>みなさまこんにちわ！大西と申します。gcpugへの投稿は今回が初めての投稿です。</p><p>筆者は、普段、小売企業でデータエンジニアとして働いており、主に各種システムからBigQueryへデータをロードするパイプラインをComposerやDataflowで開発する業務をやっています。</p><p>皆さん、GCP上で各種デプロイを自動化する場合、Cloud Buildを活用されていると思います。筆者も、業務で開発しているDataflowジョブのデプロイを自動化する際に、まずCloud Buildだけを使ってお手軽にビルド・単体テスト・デプロイを自動化しようとしました。しかし、後述するDataflowジョブのデプロイ時の制約により、Cloud Buildだけではデプロイを完結できず、GKE上にKubernetes jobをデプロイし、VPC内からDataflowジョブをデプロイするという、ちょっとした工夫を入れる必要がありました。</p><p>本記事では、表題の通り、VPC内リソースにアクセスするDataflowジョブのデプロイをCloud BuildとGKEで自動化した際に苦労した点・各種TIPSなどを紹介します。</p><p>（注）</p><ul><li>本記事で紹介している内容は、DataflowがVPC内リソースにアクセスする際に考慮が必要なものであり、GCS、BigQuery、PubSubなどインターネットに公開されたサービスを利用する場合は、関係ないことにご注意ください。</li><li>記事執筆時点でCloud BuildはVPC内へのアクセスに対応していません。Cloud Buildが対応した場合、GKEを利用する必要は無くなります。</li></ul><h3>記事の背景：DataflowジョブがVPC内リソースにアクセスする際、デプロイもVPC内でやる必要があった</h3><p>まず、記事の背景となる、私が開発したDataflowジョブの概要を説明します。</p><figure><img alt="Dataflowジョブデプロイ時の制約" src="https://cdn-images-1.medium.com/max/1024/1*je7LMOZu7RUmSNf-T4z0DA.png" /></figure><ul><li>本ジョブは、Apache Beam Java SDKを使ってScalaで実装されており、VPC内に立てたKafkaクラスタ（GKE上に構築）に接続し、外部システムから受け取ったメッセージを一部加工し、BigQueryテーブルにストリーミングデータとして挿入するという処理を行います。</li><li>このKafkaクラスタは、インターネットに外部エンドポイント（Network Load Balancer）、VPC内部に内部エンドポイント（Internal TCP load balancer）を公開しています。外部システムはインターネット越しに外部エンドポイントへTLS接続し、Dataflowなど外部に公開する必要のないリソースはVPC内の内部エンドポイントに接続します。</li><li>ここで、Apache Beamのライブラリを用いて実装されたDataflowジョブは、デプロイされる際に、まずパイプラインのDAG（タスクの依存関係の有向グラフ）情報を構築し、各種エラーを確認した上で、DataflowのサービスにDAG情報が送信されて、GCEのワーカノードにジョブがデプロイされます。この時のエラーチェックの過程で、パイプライン上で依存しているリソース（本件の場合は、GCSバケット、BigQueryテーブル、KafkaブローカをデプロイしたGKEノード）に一通り接続が可能なことを確認する作業を行うため、Datflowジョブが内部エンドポイントを利用する場合、VPC外部からデプロイ不可となります。</li><li>（参考）Dataflowのデプロイの詳細については<a href="https://cloud.google.com/dataflow/docs/guides/deploying-a-pipeline?hl=ja">公式ドキュメント</a>を参照ください。</li><li>実際にデプロイ時の振る舞いを確認するため、VPC内外でデプロイできるを確認しています。まず、VPC内にGCEインスタンスを立て、その上でデプロイする場合は、内部エンドポイントおよび外部エンドポイント両方ともデプロイできました。VPC外部（例えば、ラップトップ）からデプロイする場合は、外部エンドポイントにしか接続できませんでした。</li></ul><h3>Dataflowジョブのデプロイプロセスの確認：Jarを実行する所だけVPC内で実行が必要</h3><p>上記の通り、Kafkaブローカの内部エンドポイントに接続するには、VPC内からデプロイが必要であることが分かりました。デプロイの方法を検討する前にDataflowジョブのビルド・デプロイプロセスのうち、実際にどの部分はVPC外でも良くて、どこからVPC内でやる必要があるのか以下の通り、整理しました。<br>このプロセスにおいて、(1)と(2) はKafkaの内部エンドポイントに接続しないため、VPC外部でも実行できます。(3)は、エラーチェックの過程でVPC内にアクセスが必要なため、VPC内で実行する必要があります。<br>（注）もし、Apache Beamを用いたDataflowジョブのビルド・デプロイについて詳しくない場合は、<a href="https://beam.apache.org/documentation/runners/dataflow/">Apache Beamのドキュメント</a>を参照ください。</p><p>(1) コードをビルドする 不要</p><ul><li>デプロイに必要な実行可能なJarファイルが生成される。</li></ul><p>(2) 単体テストを実行する。</p><p>(3) （コンパイルと単体テストに成功した場合）実行可能Jarを実行する。 必要</p><ul><li>Apache Beamを使ったアプリケーション開発では、依存ライブラリを全て梱包し、実行可能なJarを生成する</li><li>このJarファイルを実行すると、DAG情報（タスクの依存関係をグラフ表現したもの）を構築し、各種エラーチェックが行われる。<br>エラーチェックには、依存するサービス（今回はGCS、BigQuery、GKE上のKafka）への接続確認も含まれる。</li><li>この部分はVPC内部で実行する必要がある。</li></ul><p>(4) （エラーチェックに問題ない場合）DAG情報がGCP上のDataflowサービスに送信される。</p><ul><li>3が成功すれば4以降はDataflowサービス内で行われるため、ユーザは気にする必要はなし。</li></ul><p>(5) Dataflowサービス内でDAGの最適化や実際のデプロイ処理が行われる（詳細は省略）。</p><h3>VPC内でデプロイする方法の整理</h3><p>一連のデプロイプロセスの整理により、ビルド結果の実行可能Jarファイルを実行する所だけ、VPC内部で実施する必要があることを確認しました。ここから実際のデプロイ方法として検討した案と最終的にGKEを使うことを選んだ理由を説明します。</p><p>(1) Jenkinsジョブでビルド・デプロイ</p><ul><li>VPC内にJenkinsサーバを立てる。Github webhookでジョブを起動し、一連のビルド・デプロイを実施する。</li><li>チームが別のプロジェクトでJenkinsを使っており、Jenkinsに慣れていた。</li><li>しかし、サーバを保守する必要がある。</li></ul><p>(2) デプロイ処理（jar実行）だけKubernetes jobで実施</p><ul><li>Cloud Buildでビルド・単体テストを実行し、実行可能Jarファイルを生成する。</li><li>JarファイルをDockerイメージに入れて、Container Registryにpushする。</li><li>Cloud BuildからKubernetes jobを実行し、ジョブの中でJarを実行する。</li></ul><p>まず、安直な方法として、VPC内のGCE上にJenkinsを立て、Webhookでジョブを起動し、一連のビルド・デプロイをやろうと考えました。しかし、せっかくマネージドサービスを駆使して、サーバ管理の労力を排除しようとしているのだから、それはやめようとなり、この案はボツとなりました。</p><p>次に、GKE上で単発のジョブを実行させる案を検討しました。Dataflowのデプロイを検討する時点で、すでにKafkaブローカをGKE上にデプロイしていたため、Kubernetesについては概要を把握しており、Kubernetesにはサーバプロセスをデプロイするほか、単発のジョブを実行させる機能があることも把握していました（<a href="https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/">リンク</a>を参照）。この機能を利用すると、Jarを実行する部分をVPC内で実行できる上、ジョブを実行するときだけリソースを確保するため、サーバプロセスを監視する必要もありません。</p><p>また、本件以外にアプリケーションのデプロイをVPC内で行う必要が出た場合に同じ方法を採用できそうだと考え、Kubernetes jobでデプロイする案を採用しました。</p><h3>Cloud BuildとGKEを使ったデプロイ方法</h3><p>ここからは実際にどうやってデプロイしているかご紹介します。全体の流れは以下の図の通りです。本アプローチはGKEのチュートリアル「Cloud Build を使用した GitOps スタイルの継続的デリバリー」を参考にしています。</p><ul><li>（1〜3）Cloud Buildのジョブトリガーでブランチの変更を検知すると、ビルドジョブが実行され、Dataflowジョブのデプロイに必要な成果物一式がDockerイメージ化し、Container Registryにpushされる。</li><li>（4〜6）kubectlにKubernetesマニフェストファイルを指定し、Dataflowジョブデプロイ用のKubernetesジョブをGKEクラスタ上にデプロイする。</li><li>（7〜9）Kubernetesジョブ内では、実行可能Jar（Apache Beamのビルド結果）を実行し、Dataflowジョブが実際にデプロイされる。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9R3ManYEiB-8mvK66Ow9dg.png" /><figcaption>Cloud BuildとGKEを使ったDataflowのデプロイプロセス</figcaption></figure><p>次に各ステップでのジョブ実行に必要な成果物を紹介します。</p><h4>(1) PRをマージする〜（2）ジョブトリガーでジョブを起動する</h4><p>Cloud Buildは、ジョブトリガーという機能を使い、リポジトリのブランチに対する変更を検知して、ジョブを起動することができます。ジョブトリガーについては、<a href="https://cloud.google.com/cloud-build/docs/running-builds/automate-builds?hl=ja">GCPのドキュメント</a>を参照ください。</p><p>筆者は、<a href="https://www.terraform.io/">terraform</a>でジョブトリガーを作成しています。その場合、<a href="https://www.terraform.io/docs/providers/google/r/cloudbuild_trigger.html">GCPのプラグイン</a>を用いて、まず以下のようなモジュールを作成します。</p><ul><li>複数のジョブ（DAG）に対応するため、各ジョブの設定を配列としてまとめたdag_listを渡し、各ジョブに対してトリガーを作成するようにしています。</li><li>trigger_templateが、ジョブトリガーの設定箇所です。ここでは、トリガーを設定したい、リポジトリとブランチを指定しています。</li><li>substitutionsは、環境に応じて可変の箇所を変数値で置き換えるために使います。開発環境・環境・本番環境と同じビルド手順を使いたい場合は、CloudBuildのビルド手順を記述するYAMLファイルは共通にし、substitutionsで変数値を置き換えると良いでしょう。詳細は<a href="https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values?hl=ja">GCPのドキュメント</a>を参照ください。</li></ul><pre>resource &quot;google_cloudbuild_trigger&quot; &quot;composer_build_trigger&quot; {<br>  count          = length(var.dag_list)<br>  description    = &quot;Push to ${var.dag_list[count.index][&quot;branch_name&quot;]} branch&quot;<br>  included_files = var.triggerlist<br> <br>  trigger_template {<br>    branch_name = var.dag_list[count.index][&quot;branch_name&quot;]<br>    repo_name   = var.dag_list[count.index][&quot;repo_name&quot;]<br>  }<br> <br>  substitutions = {<br>    _BOOTSTRAP_SERVERS          = var.bootstrap_servers<br>    _PROJECT                   = var.dag_list[count.index][&quot;project&quot;]<br>    _BUILD_IMAGE_NAME           = &quot;${var.dag_list[count.index][&quot;dataflow_job_name&quot;]}-build&quot;<br>    _CLOUDSDK_COMPUTE_ZONE      = var.zone<br>    _CLOUDSDK_CONTAINER_CLUSTER = var.gke_cluster_name<br>    _NETWORK                    = var.network<br>    _SUBNETWORK                 = var.subnetwork<br>    _DATAFLOW_JOB_NAME          = var.dag_list[count.index][&quot;dataflow_job_name&quot;]<br>    _K8S_JOB_NAME               = &quot;${var.dag_list[count.index][&quot;dataflow_job_name&quot;]}-deploy&quot;<br>    _SCHEMA_REGISTRY_URL        = var.schema_registry_url<br>    _SERVICE_ACCOUNT            = var.dag_list[count.index][&quot;sevice_account&quot;]<br>    _SOURCE_BUCKET              = var.dag_list[count.index][&quot;source_bucket&quot;]<br>  }<br> <br>  filename = &quot;cloudbuild.yaml&quot;<br>}</pre><p>環境に合わせた値を指定している箇所は以下の通りです。DAGによって可変の箇所はリストで指定し、共通設定は配列外で指定しています。</p><pre>module &quot;cloudbuild-dataflow-stream-dags-deployment&quot; {<br>  source              = &quot;path/to/modules/cloudbuild-dataflow-stream-dags-deployment&quot;<br>  service_name        = &quot;dags-sync&quot;<br>  zone                = &quot;asia-northeast1&quot;<br>  gcp_project         = local.gcp_project<br>  env                 = &quot;dev&quot;<br>  triggerlist         = [&quot;**&quot;]<br>  gke_cluster_name    = &quot;kafka&quot;<br>  bootstrap_servers   = &quot;kafka.example.com\\:9090&quot;<br>  schema_registry_url = &quot;https\\:\\/\\/schema.example.co,&quot;<br>  network             = &quot;default&quot;<br>  subnetwork          = &quot;default&quot;<br>  kms_location        = local.region<br>  dag_list = [<br>    {<br>      repo_name           = &quot;your-repo-name1&quot;<br>      branch_name         = &quot;develop&quot;<br>      project             = &quot;your-project&quot;<br>      dataflow_job_name   = &quot;your-job-name1&quot;<br>      sevice_account      = &quot;<a href="/service/mailto:sa-name@your-project.iam.gserviceaccount.com">sa-name@your-project.iam.gserviceaccount.com</a>&quot;<br>      source_bucket       = &quot;you-bucket&quot;<br>    },<br>    {<br>      repo_name           = &quot;your-repo-name2&quot;<br>      branch_name         = &quot;develop&quot;<br>      project             = &quot;your-project&quot;<br>      dataflow_job_name   = &quot;your-job-name2&quot;<br>      sevice_account      = &quot;<a href="/service/mailto:sa-name@your-project.iam.gserviceaccount.com">sa-name@your-project.iam.gserviceaccount.com</a>&quot;<br>      source_bucket       = &quot;you-bucket&quot;<br>    }<br>  ]<br>}</pre><h4>（3）Dataflowジョブのデプロイ用のDockerイメージをpushする〜（6）実際にKubernetesジョブをデプロイする</h4><p>Cloud Buildのジョブトリガーの設定で、Cloud Buildのビルド手順の設定ファイルをcloudbuild.yamlと指定しました。これはビルド対象のリポジトリのルートフォルダに左記のファイル名で設定ファイルを置くこと指定しています。</p><ol><li>デプロイ用スクリプトを生成する・・・リポジトリには、Jarファイルを実行する際のオプションをテンプレート化したデプロイスクリプトを用意しています。環境ごとに可変な変数値はCloud Buildのsubstitutionsで提供するため、ビルド手順の中で実際の値に置き換えます。</li><li>Dataflowジョブデプロイ用のイメージをビルドする・・・Kubernetesジョブとしてデプロイするには、コンテナイメージに固める必要があるため、デプロイに必要なファイル一式を含むイメージを作成します。</li><li>Container Registryへイメージをpushする・・・ビルドしてできたイメージをpushします。</li><li>Kubernetesジョブのマニフェストファイルを生成する・・・Kubernetesジョブのマニフェストファイルはジョブに関する設定ファイルです。マニフェストファイルもリポジトリにはテンプレートのみ置いており、ここでは環境あるいはコミットによって異なる値を置き換える処理をやり、実際のデプロイに使えるマニフェストファイルを生成しています。</li><li>DataflowジョブをデプロイするKubernetesジョブを起動する・・・kubectl applyにマニフェストファイルを指定し、Kubernetesジョブをデプロイします。</li><li>ジョブが完了するまで待機する</li><li>ジョブのリソースを削除する・・・ジョブ実行完了後もPodが残り続けるため、完了後は明示的にジョブを削除します。</li></ol><pre>steps:<br># デプロイ用のスクリプト（後述）を生成する<br>- name: &#39;gcr.io/cloud-builders/gcloud&#39;<br>  id: Generate deploy script<br>  entrypoint: /bin/sh<br>  args:<br>    - &#39;-c&#39;<br>    - |<br>      sed &quot;s/PROJECT/${PROJECT_ID}/g&quot; scripts/dataflow/deploy-update.sh.tpl | \<br>      sed &quot;s/DATAFLOW_JOB_NAME/${_DATAFLOW_JOB_NAME}/g&quot; | \<br>      sed &quot;s/SERVICE_ACCOUNT/${_SERVICE_ACCOUNT}/g&quot; | \<br>      sed &quot;s/SOURCE_BUCKET/${_SOURCE_BUCKET}/g&quot; | \<br>      sed &quot;s/BOOTSTRAP_SERVERS/${_BOOTSTRAP_SERVERS}/g&quot; | \<br>      sed &quot;s/SUBNETWORK/${_SUBNETWORK}/g&quot; | \<br>      sed &quot;s/NETWORK/${_NETWORK}/g&quot; | \<br>      sed &quot;s/SCHEMA_REGISTRY_URL/${_SCHEMA_REGISTRY_URL}/g&quot; &gt; scripts/dataflow/deploy-update.sh<br># Dataflowジョブデプロイ用のイメージをビルドする<br>- name: &#39;gcr.io/cloud-builders/docker&#39;<br>  id: Build image<br>  args:<br>    - &#39;build&#39;<br>    - &#39;-t&#39;<br>    - &#39;gcr.io/$PROJECT_ID/${_BUILD_IMAGE_NAME}:$SHORT_SHA&#39;<br>    - &#39;.&#39;<br> <br># Container Registryへイメージをpushする<br>- name: &#39;gcr.io/cloud-builders/docker&#39;<br>  id: Push image<br>  args:<br>    - &#39;push&#39;<br>    - &#39;gcr.io/$PROJECT_ID/${_BUILD_IMAGE_NAME}:$SHORT_SHA&#39;<br> <br># Kubernetesジョブのマニフェストファイルを生成する<br>- name: &#39;gcr.io/cloud-builders/gcloud&#39;<br>  id: Generate manifest<br>  entrypoint: /bin/sh<br>  args:<br>    - &#39;-c&#39;<br>    - |<br>      sed &quot;s/GCP_PROJECT/${PROJECT_ID}/g&quot; kubernetes.yaml.tpl | \<br>      sed &quot;s/BUILD_IMAGE_NAME/${_BUILD_IMAGE_NAME}/g&quot; | \<br>      sed &quot;s/COMMIT_SHA/${SHORT_SHA}/g&quot; &gt; kubernetes.yaml<br> <br># DataflowジョブをデプロイするKubernetesジョブを起動する<br>- name: &#39;gcr.io/cloud-builders/kubectl&#39;<br>  id: Deploy<br>  args:<br>    - &#39;apply&#39;<br>    - &#39;-f&#39;<br>    - &#39;kubernetes.yaml&#39;<br>  env:<br>    - &#39;CLOUDSDK_COMPUTE_ZONE=${_CLOUDSDK_COMPUTE_ZONE}&#39;<br>    - &#39;CLOUDSDK_CONTAINER_CLUSTER=${_CLOUDSDK_CONTAINER_CLUSTER}&#39;<br> <br># ジョブが完了するまで待機する<br>- name: &#39;gcr.io/cloud-builders/kubectl&#39;<br>  id: Wait<br>  args:<br>    - &#39;wait&#39;<br>    - &#39;--for=condition=complete&#39;<br>    - &#39;--timeout=600s&#39;<br>    - &#39;job/${_K8S_JOB_NAME}&#39;<br>  env:<br>    - &#39;CLOUDSDK_COMPUTE_ZONE=${_CLOUDSDK_COMPUTE_ZONE}&#39;<br>    - &#39;CLOUDSDK_CONTAINER_CLUSTER=${_CLOUDSDK_CONTAINER_CLUSTER}&#39;<br> <br># ジョブのリソースを削除する<br>- name: &#39;gcr.io/cloud-builders/kubectl&#39;<br>  id: Clean up<br>  args:<br>    - &#39;delete&#39;<br>    - &#39;job&#39;<br>    - &#39;${_K8S_JOB_NAME}&#39;<br>  env:<br>    - &#39;CLOUDSDK_COMPUTE_ZONE=${_CLOUDSDK_COMPUTE_ZONE}&#39;<br>    - &#39;CLOUDSDK_CONTAINER_CLUSTER=${_CLOUDSDK_CONTAINER_CLUSTER}&#39;</pre><p>cloudbuild.yamlの最初に生成しているデプロイ用のスクリプトのテンプレートは以下のようなものを使っています。英大文字で書かれた箇所が環境によって可変であり、Cloud Buildによって実際の値に置換されます。Apache BeamコードのDataflowへのデプロイの詳細については、<a href="https://beam.apache.org/documentation/runners/dataflow/">Apache Beamの公式ドキュメント</a>を参照ください。</p><pre>#!/usr/bin/env bash<br>#dataflow-update.sh.tpl<br>region=asia-northeast1<br>runner=DataflowRunner<br>appVersion=0.1.0<br>scalaVersion=2.12<br>java -jar target/scala-${scalaVersion}/app-name-${appVersion}.jar \<br>  --region=${region} \<br>  --runner=${runner} \<br>  --project=DATAFLOW_PROJECT \<br>  --jobName=DATAFLOW_JOB_NAME \<br>  --serviceAccount=SERVICE_ACCOUNT \<br>  --sourceBucket=SOURCE_BUCKET \<br>  --tempLocation=gs://SOURCE_BUCKET/JOB_NAME/tmp \<br>  --bootstrapServers=BOOTSTRAP_SERVERS \<br>  --network=NETWORK \<br>  --subnetwork=<a href="https://www.googleapis.com/compute/v1/projects/DATAFLOW_PROJECT/regions/$%7Bregion%7D/subnetworks/SUBNETWORK">https://www.googleapis.com/compute/v1/projects/DATAFLOW_PROJECT/regions/${region}/subnetworks/SUBNETWORK</a> \<br>  --schemaRegistryUrl=SCHEMA_REGISTRY_URL \<br>  --streaming=true \<br>  --experiments=enable_stackdriver_agent_metrics \<br>  --update</pre><p>そしてKubenetesジョブで使うDockerイメージをビルドするDockerfileは以下の通りです。筆者はScalaでDataflowのコードを書いており、ベースイメージとしてsbtを使っていますが、公式のサンプルと同様にMavenを使うことももちろん可能です。</p><pre>FROM mozilla/sbt:8u212_1.2.8<br>COPY ./project/ ./project<br>COPY ./scripts/ ./scripts<br>COPY ./src/ ./src<br>COPY ./build.sbt .<br>RUN sbt clean assembly<br>FROM openjdk:8u222-jdk<br>ARG SCALA_VERSION=&quot;2.12&quot;<br>ARG APP_VERSION=&quot;0.1.0&quot;<br>COPY --from=0 /target/scala-$SCALA_VERSION/app-name-$APP_VERSION.jar ./target/scala-$SCALA_VERSION/<br>COPY --from=0 /scripts/ ./scripts</pre><p>最後にKubernetesジョブのデプロイに使うマニフェストファイルのテンプレートは以下の通り。英大文字の箇所はCloud Buildによって実際の値に置換されます。実際にやっていることは、前述で紹介したシェルスクリプトを実行することのみです。</p><pre>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: your-job-name1-deploy<br>spec:<br>  # automatically clean up finished job<br>  ttlSecondsAfterFinished: 0<br>  template:<br>    metadata:<br>      name: your-job-name1-deploy<br>    spec:<br>      containers:<br>        - name: your-job-name1-deploy<br>          image: gcr.io/GCP_PROJECT/BUILD_IMAGE_NAME:COMMIT_SHA<br>          command: [&quot;bash&quot;]<br>          args: [&quot;scripts/dataflow/deploy-update.sh&quot;]<br>      # Do not restart containers after they exit<br>      restartPolicy: Never</pre><h3>まとめ</h3><p>本記事では、VPC内のリソースにアクセスするDataflowジョブはVPC内でしかデプロイを完結できないという制約を克服するため、Cloud BuildからVPC内にKubernetesジョブを起動し、そのジョブからデプロイを行うというアプローチを取ることで、JenkinsなどCIサーバを管理せずに、比較的に簡単なCI/CDパイプラインを構築できることを紹介しました。</p><p>今回のアプローチは、Dockerイメージさえ作ってしまえば、Kubernetes上で好きなジョブを実行させることができるため、かなり自由度の高いアプローチだと言えます。読者のみなさまも、ぜひ活用ください！もし本記事がみなさまの日々の開発の助けになれば幸いです。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a4d69ccef96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud-jp/gitops-vpc%E5%86%85%E3%83%AA%E3%82%BD%E3%83%BC%E3%82%B9%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%E3%81%99%E3%82%8Bdataflow%E3%82%B8%E3%83%A7%E3%83%96%E3%81%AE%E3%83%87%E3%83%97%E3%83%AD%E3%82%A4%E3%82%92cloud-build%E3%81%A8gke%E3%81%A7%E8%87%AA%E5%8B%95%E5%8C%96%E3%81%99%E3%82%8B-9a4d69ccef96">GitOps: VPC内リソースにアクセスするDataflowジョブのデプロイをCloud BuildとGKEで自動化する</a> was originally published in <a href="https://medium.com/google-cloud-jp">google-cloud-jp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>