<?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 Ritesh Thakur on Medium]]></title>
        <description><![CDATA[Stories by Ritesh Thakur on Medium]]></description>
        <link>https://medium.com/@thakur.ritesh19?source=rss-6c7ee8750f9f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c6H_ZsxR1ZCD3zWCdjGHdQ.jpeg</url>
            <title>Stories by Ritesh Thakur on Medium</title>
            <link>https://medium.com/@thakur.ritesh19?source=rss-6c7ee8750f9f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:00:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thakur.ritesh19/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[Streaming data to Google BigQuery using Storage Write API]]></title>
            <link>https://medium.com/@thakur.ritesh19/streaming-data-to-google-bigquery-using-storage-write-api-c36fb3af8600?source=rss-6c7ee8750f9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c36fb3af8600</guid>
            <category><![CDATA[storage-write-api]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ritesh Thakur]]></dc:creator>
            <pubDate>Wed, 01 May 2024 23:56:25 GMT</pubDate>
            <atom:updated>2024-05-20T20:34:53.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*BmWePiMxKKZWiQllrE2bVA.png" /></figure><p>I had recently faced a problem at work with “<strong>Load jobs per day</strong>” limit that Google Cloud (hereon GCP) sets for Bigquery (hereon BQ) data loads. In order to work our way around this, we switched to streaming loads (instead of batch loads) using Google’s Streaming API. I recently came across <a href="https://cloud.google.com/bigquery/docs/write-api">this</a> document by Google and decided that I want to switch from using Streaming API to Storage Write API. Here is why:</p><blockquote>The BigQuery Storage Write API is a unified data-ingestion API for BigQuery. It combines streaming ingestion and batch loading into a single high-performance API. You can use the Storage Write API to stream records into BigQuery in real time or to batch process an arbitrarily large number of records and commit them in a single atomic operation.</blockquote><blockquote><strong>Advantages of using the Storage Write API</strong></blockquote><blockquote><strong>Exactly-once delivery semantics.</strong> The Storage Write API supports exactly-once semantics through the use of stream offsets. <br><strong>Stream-level transactions.</strong> You can write data to a stream and commit the data as a single transaction. If the commit operation fails, you can safely retry the operation.<br><strong>Transactions across streams.</strong> Multiple workers can create their own streams to process data independently. <br><strong>Efficient protocol.</strong> The Storage Write API is more efficient than the older insertAll method because it uses gRPC streaming rather than REST over HTTP. The Storage Write API also supports binary formats in the form of protocol buffers, which are a more efficient wire format than JSON. Write requests are asynchronous with guaranteed ordering.<br><strong>Schema update detection.</strong> If the underlying table schema changes while the client is streaming, then the Storage Write API notifies the client.<br><strong>Lower cost</strong>. The Storage Write API has a significantly lower cost than the older streaming API. In addition, you can ingest up to 2 TiB per month for free. <a href="https://cloud.google.com/bigquery/docs/write-api"><em>[1]</em></a></blockquote><p>When I was working on Streaming data to Google BigQuery using Storage Write API, I realized that no one stop guide exists for such a setup in Python, so I decided to create one. Additional work was needed because in order to stream data to Google BigQuery using Storage Write API, we have to work with Google’s protocol buffers. I did not want to manually generate and then compile a proto file, so I try to generate and compile “.proto” files using code. Without delaying much, let us get into the task.</p><p><strong>My script does following things:</strong></p><ol><li><strong>Takes project_id, dataset_id, table_id, data (JSON), credentials for BQ and write API separately</strong></li><li><strong>Download schema of destination table and generate corresponding “.proto” file</strong></li><li><strong>Compile “.proto” file to have Python descriptor file</strong></li><li><strong>Stream data to BQ</strong></li></ol><p>I will first paste the code snippet and then explain it in detail:</p><pre>import sys<br>import logging<br>import grpc_tools.protoc<br><br>from google.cloud import bigquery_storage_v1<br>from google.cloud.bigquery_storage_v1 import types<br>from google.cloud.bigquery_storage_v1 import writer<br>from google.protobuf import descriptor_pb2<br>from google.cloud import bigquery<br><br># Setting up logger level<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br># Files can only be written in /tmp directory hence we will be genrating schema.proto and compiled proto in /tmp<br>sys.path.append(&#39;/tmp&#39;)<br><br># Datatypes in Proto are different from those of Bigquery. This is a mapper that maps BQ datatypes to proto datatypes.<br># This will need more datatypes as needed<br>DATA_TYPE_MAPPING = {<br>    &quot;STRING&quot;: &quot;string&quot;,<br>    &quot;INTEGER&quot;: &quot;sint64&quot;,<br>    &quot;FLOAT&quot;: &quot;float&quot;,<br>    &quot;BYTES&quot;: &quot;bytes&quot;,<br>    &quot;TIMESTAMP&quot;: &quot;string&quot;<br>}<br><br><br># Function to serialize row&#39;s data in proto format<br>def create_row_data(data, schema):<br>    import schema_pb2<br>    row = schema_pb2.Schema()<br>    for field in schema:<br>        field_name = field.name<br>        field_value = data.get(field_name)<br><br>        # Only set the field if the value is not None<br>        if field_value is not None:<br>            setattr(row, field_name, field_value)<br>    return row.SerializeToString()<br><br><br># Function to generate proto file basis the schema that a given table has configured<br>def generate_proto_file(schema, file_path):<br>    proto_file = &quot;syntax = \&quot;proto2\&quot;;\n\npackage schema;\n\n&quot;<br>    proto_message = &quot;message Schema {\n&quot;<br><br>    for index, field in enumerate(schema):<br>        field_name = field.name<br>        field_type = field.field_type<br><br>        if field_type not in DATA_TYPE_MAPPING:<br>            raise ValueError(f&quot;Field type {field_type} not supported by Proto yet&quot;)<br>        proto_field = f&quot;  required {DATA_TYPE_MAPPING[field_type]} {field_name} = {index + 1};\n&quot;<br>        proto_message += proto_field<br><br>    proto_message += &quot;}\n&quot;<br>    proto_message = proto_file + proto_message<br>    with open(file_path, &quot;w&quot;) as proto_file:<br>        proto_file.write(proto_message)<br><br>    logger.info(&quot;Proto file generated successfully&quot;)<br><br><br>def stream_data_to_bigquery(project_id, dataset_id, table_id, data, bq_cred=None, write_cred=None):<br>    # Configuring Bigquery client to fetch table&#39;s schema<br>    bq_client = bigquery.Client(credentials=bq_cred)<br>    table_ref = bq_client.get_table(f&quot;{project_id}.{dataset_id}.{table_id}&quot;)<br>    schema = table_ref.schema<br><br>    # Generating proto file basis the schema that a given table has configured<br>    proto_file_path = &quot;/tmp/schema.proto&quot;<br>    generate_proto_file(schema, proto_file_path)<br><br>    # Compiling the proto file to generate the python file<br>    grpc_tools.protoc.main([&#39;protoc&#39;, &#39;-I/tmp&#39;, &#39;--python_out=/tmp&#39;, proto_file_path])<br>    logger.info(&quot;Compiled proto file successfully&quot;)<br><br>    # THis import cannot be outside the function as the proto file is generated dynamically<br>    import schema_pb2<br><br>    # Following code is used to write data to Bigquery using storage write API but in a streaming fashion<br>    client = bigquery_storage_v1.BigQueryWriteClient(credentials=write_cred)<br>    parent = client.table_path(project_id, dataset_id, table_id)<br>    write_stream = types.WriteStream()<br>    write_stream.type_ = types.WriteStream.Type.COMMITTED<br>    write_stream = client.create_write_stream(<br>        parent=parent, write_stream=write_stream<br>    )<br>    stream_name = write_stream.name<br><br>    request_template = types.AppendRowsRequest()<br>    request_template.write_stream = stream_name<br><br>    proto_schema = types.ProtoSchema()<br>    proto_descriptor = descriptor_pb2.DescriptorProto()<br>    schema_pb2.Schema.DESCRIPTOR.CopyToProto(proto_descriptor)<br>    proto_schema.proto_descriptor = proto_descriptor<br>    proto_data = types.AppendRowsRequest.ProtoData()<br>    proto_data.writer_schema = proto_schema<br>    request_template.proto_rows = proto_data<br><br>    append_rows_stream = writer.AppendRowsStream(client, request_template)<br><br>    # Setting batch size to 500<br>    batch_size = 500<br>    for i in range(0, len(data), batch_size):<br>        batch_data = data[i:i + batch_size]<br><br>        proto_rows = types.ProtoRows()<br>        for row in batch_data:<br>            proto_rows.serialized_rows.append(create_row_data(row, schema))<br><br>        request = types.AppendRowsRequest()<br>        proto_data = types.AppendRowsRequest.ProtoData()<br>        proto_data.rows = proto_rows<br>        request.proto_rows = proto_data<br><br>        response_future = append_rows_stream.send(request)<br>        logger.info(f&quot;Result {response_future.result()}&quot;)<br><br>    logger.info(f&quot;Data successfully streamed to {project_id}.{dataset_id}.{table_id} table&quot;)<br><br>    append_rows_stream.close()</pre><p>lines 20–25:<br>Here I am defining a mapper for datatypes since datatypes defined by BQ are different than those of a <a href="https://protobuf.dev/programming-guides/proto2/"><strong>protocol buffer</strong></a><strong>. </strong>This mapper is pretty limited in my example, but feel free to expand this for your use case.</p><p>lines 29–35:<br>“<strong>create_row_data</strong>” function serializes a given row from our data into a format compatible with our “<strong>.proto</strong>” file. Output from this function will later be used to directly stream data to BQ.</p><p>lines 39–57:<br>“<strong>generate_proto_file</strong>” function is used to generate “<strong>.proto</strong>” file from schema. Schema is pulled from BQ (lines 62–64) and passed to this function. In order to get a better sense of this function, I will first paste how a “<strong>.proto</strong>” file looks like:</p><pre>syntax = “proto2”;<br><br>package tutorial;<br><br>message Metric {<br> required string a = 1;<br> required sint64 b = 2;<br> required float c = 3;<br> required bytes d = 4;<br>}</pre><p>I simply iterate over a given table’s schema and use string manipulation to generate a “<strong>.proto</strong>” file.</p><p>lines 62–68:<br>Fetches a given table’s schema and passes it to “<strong>generate_proto_file</strong>” to generate a “<strong>.proto</strong>” file.</p><p>lines 71–72:<br>I user grpcio.tools to compile “<strong>.proto</strong>” file. A compiled “<strong>.proto</strong>” file for Python looks like following:</p><pre># -*- coding: utf-8 -*-<br># Generated by the protocol buffer compiler.  DO NOT EDIT!<br># source: abc.proto<br># Protobuf Python Version: 5.26.1<br>&quot;&quot;&quot;Generated protocol buffer code.&quot;&quot;&quot;<br>from google.protobuf import descriptor as _descriptor<br>from google.protobuf import descriptor_pool as _descriptor_pool<br>from google.protobuf import symbol_database as _symbol_database<br>from google.protobuf.internal import builder as _builder<br># @@protoc_insertion_point(imports)<br><br>_sym_db = _symbol_database.Default()<br><br><br><br><br>DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b&#39;\n\tabc.proto\x12\x08tutorial\&quot;4\n\x06Metric\x12\t\n\x01\x61\x18\x01 \x02(\t\x12\t\n\x01\x62\x18\x02 \x02(\x12\x12\t\n\x01\x63\x18\x03 \x02(\x02\x12\t\n\x01\x64\x18\x04 \x02(\x0c&#39;)<br><br>_globals = globals()<br>_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)<br>_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, &#39;abc_pb2&#39;, _globals)<br>if not _descriptor._USE_C_DESCRIPTORS:<br>  DESCRIPTOR._loaded_options = None<br>  _globals[&#39;_METRIC&#39;]._serialized_start=23<br>  _globals[&#39;_METRIC&#39;]._serialized_end=75<br># @@protoc_insertion_point(module_scope)</pre><p>NOTES: <br>1. If your “<strong>.proto</strong>” file’s name is “<strong>abc.proto</strong>”, compiled file will always be “<strong>abc_pb2.py</strong>” (where pb2 stands for Protobuf 2)<br>2. At this point you can see all the occurrences of “<strong>/tmp</strong>” directory. This is because I will be running my code on Cloud Function and files can only be written to “<strong>/tmp</strong>” directly in Cloud Functions</p><p>line 75:<br>At this point, it is worth mentioning that I am importing my compiled proto file, schema_pb2, inside function because compiled proto file is generated during runtime. Having this import outside throws an error since at that point, schema_pb2, is missing.</p><p>lines 78–98:<br>In these lines I am configuring my write stream’s writer client.</p><p>lines 101–115:<br>Using a batch size of 500, I am streaming 500 rows at a given time. For each individual row in our JSON data, I am first serializing my row using “<strong>create_row_data</strong>”. 500 of those rows are appended and sent together to BQ.</p><p>Using this method, one can stream data to Google BigQuery using a high-performance Storage Write API at 50% of cost compared to Streaming API.</p><p>Happy Data Ingestion!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*l1MbkBxkErH089JJWCTzjA.png" /><figcaption>Credit: <a href="https://dataedo.com/cartoon/we-have-data-now-what">https://dataedo.com/cartoon/we-have-data-now-what</a></figcaption></figure><p>Credits:<br>1.<a href="https://cloud.google.com/bigquery/docs/write-api">https://cloud.google.com/bigquery/docs/write-api</a><br>2. <a href="https://stackoverflow.com/questions/71024985/error-there-was-a-problem-opening-the-stream-when-using-bigquery-storage-write">https://stackoverflow.com/questions/71024985/error-there-was-a-problem-opening-the-stream-when-using-bigquery-storage-write</a><br>3. <strong>Image:</strong> <a href="https://cloud.google.com/bigquery/docs/write-api">https://cloud.google.com/bigquery/docs/write-api</a><br>4. <a href="https://protobuf.dev/programming-guides/proto2/">https://protobuf.dev/programming-guides/proto2/</a><br>5. <a href="https://medium.com/@bravnic/bigquery-storage-write-api-at-scale-7affcc2d7a93">https://medium.com/@bravnic/bigquery-storage-write-api-at-scale-7affcc2d7a93</a><br>6. <a href="https://stackoverflow.com/questions/72644555/is-there-any-way-to-use-protobuf-compiler-in-python-without-using-subprocess">https://stackoverflow.com/questions/72644555/is-there-any-way-to-use-protobuf-compiler-in-python-without-using-subprocess</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c36fb3af8600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying SFTPGo on Google Kubernetes Engine using Terraform]]></title>
            <link>https://medium.com/@thakur.ritesh19/deploying-sftpgo-on-google-kubernetes-engine-using-terraform-befc51d2c174?source=rss-6c7ee8750f9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/befc51d2c174</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[sftpgo]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[sftp]]></category>
            <dc:creator><![CDATA[Ritesh Thakur]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 02:25:06 GMT</pubDate>
            <atom:updated>2023-11-14T02:32:52.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*khbuSiiMesZ2J3h_IXAvOA.png" /></figure><p>SFTPGo is an open-source project which provides an interactive, intuitive and robust SFTP service. In order to deploy SFTPGo as a scalable and highly available service, we deployed SFTPGo on a Google Kubernetes Engine (hereafter GKE) and Cloud SQL (SFTPGO’s DB) using SFTPGo Docker image. Users can see original source code for SFTPGo <a href="https://github.com/drakkan/sftpgo">here</a> for better insight into this amazing service (Kudos to author). I am taking a dive into, “How to deploy SFTPGO on GKE using Terraform” because neither could I find one stop article nor did Chat GPT help me for this and I realized more often than not, developers might need to deploy SFTPGO on GKE using Terraform. Without any further delay, let us get to the task at hand. I will be breaking down the article into following steps:</p><ol><li><strong>Creating a Project in GCP</strong></li><li><strong>Creating and configuring Cloud SQL</strong></li><li><strong>Creating Artifact Registry and Image</strong></li><li><strong>Creating a GKE cluster, workload and service</strong></li></ol><p>Code can similarly be broken down into modules, where each module serves one of the steps above. Each of the steps can then be called by a main.tf at root level. Here is my directory structure I have used for this article (Ignore the ones not circled in red, they are just examples):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*FRzqF65gjzBV8JhvFEGsAA.png" /></figure><p>Readers can feel free to skip a section if they are already acquainted with any of the aforementioned setups. Some of the sections are basic, but I wanted to put end-to-end deployment process for my readers. Do not let length of this article discourage you, most of it is just code samples :)</p><p><strong>Prerequisites:</strong></p><ol><li>GCP Billing Account</li><li>Access Key (for deploying resources)</li></ol><h3>Creating <strong>a Project in GCP</strong></h3><p>To create a GCP Project using Terraform I am using following code:</p><pre>provider &quot;google&quot; {<br>  credentials = var.credentials<br>}<br><br>resource &quot;google_project&quot; &quot;development_project&quot; {<br> name = var.project_display_name<br> project_id = var.project_id<br> folder_id = var.folder_id<br> billing_account = var.billing_account<br> lifecycle {<br> prevent_destroy = true<br> }<br>}</pre><h3>C<strong>reating and configuring Cloud SQL</strong></h3><p>First we need to enable the required API:</p><pre>resource &quot;google_project_service&quot; &quot;sql_admin_api&quot; {<br>  project = var.project_id<br>  service = &quot;sqladmin.googleapis.com&quot;<br>}</pre><p>I have written a small shell script that tests if SQL API is up, after enabling , or not. This is important, because we want to proceed only if API is ready to serve our oncoming requests.</p><p>Here is the shell script:</p><pre>#!/bin/bash<br><br>PROJECT=$1<br>SERVICE=$2<br># Initialize a flag indicating whether compute.googleapis.com is found<br>found=false<br>while [ &quot;$found&quot; = false ]; do<br>  # Fetch the list of enabled services<br>  services=$(gcloud services list --project=&quot;$PROJECT&quot; --format=&quot;value(NAME)&quot;)<br>  # Converting all api names to lowercase<br>  service_lowercase=$(echo &quot;$services&quot; | tr &#39;[:upper:]&#39; &#39;[:lower:]&#39;)<br>  # Convert service to be found to lowercase for case-insensitive comparison<br>  target_service=&quot;$SERVICE&quot;<br>  target_service_lowercase=$(echo &quot;$target_service&quot; | tr &#39;[:upper:]&#39; &#39;[:lower:]&#39;)<br>  # Check if the lowercase version of &quot;compute.googleapis.com&quot; is in the list of services<br>  # shellcheck disable=SC2199<br>  # shellcheck disable=SC2076<br>  if [[ &quot;${service_lowercase[@],,}&quot; =~ &quot;${target_service_lowercase}&quot; ]]; then<br>    echo &quot;$SERVICE found in the list of services.&quot;<br>    found=true # Set the flag to true to exit the loop<br>  else<br>    echo &quot;$SERVICE not found in the list of services. Retrying in 10 seconds...&quot;<br>    sleep 10 # Sleep for 10 seconds before retrying<br>  fi<br>done</pre><p>Here is how I call API checking shell script from Terraform:</p><pre>resource &quot;null_resource&quot; &quot;wait_for_sql_admin_api&quot; {<br>  depends_on = [google_project_service.sql_admin_api]<br><br>  provisioner &quot;local-exec&quot; {<br>    command     = &quot;bash ../resources/check_api_exists.sh ${var.project_id} sqladmin.googleapis.com&quot;<br>    working_dir = path.module<br>  }<br>}</pre><p>After API is up, I use following code to deploy SQL instance:</p><pre>esource &quot;google_sql_database_instance&quot; &quot;sql_instance_inertia&quot; {<br>  name                = var.sql_db_name<br>  database_version    = &quot;MYSQL_8_0&quot;<br>  project             = var.project_id<br>  region              = &quot;us-west1&quot;<br>  depends_on          = [google_project_service.sql_admin_api, null_resource.wait_for_sql_admin_api]<br>  deletion_protection = false<br><br>  settings {<br>    tier = &quot;db-f1-micro&quot;<br><br>    backup_configuration {<br>      enabled = true<br>    }<br><br>    ip_configuration {<br>      ipv4_enabled = true<br>      require_ssl  = false<br>      authorized_networks {<br>        name  = &quot;allow-specific-ip-range&quot;<br>        value = &quot;0.0.0.0/0&quot;<br>      }<br>    }<br>  }<br>}<br><br>output &quot;sql_external_ip_address&quot; {<br>  value = google_sql_database_instance.sql_instance_inertia.public_ip_address<br>}</pre><p>Notice how I use “depends_on” to first wait and see if the SQL API is enabled, yet or not. This is important because we can create “SQL Instance” only when SQL API is ready. It is also worth noting how output from a Terraform module is captured as output (sql_external_ip_address in this case). We will be later using this output to configure SQL for our SFTPGo.</p><p>Following code is used to create DB and User in our newly created SQL instance:</p><pre>resource &quot;google_sql_database&quot; &quot;sftpgo_database&quot; {<br>  project    = var.project_id<br>  name       = &quot;sftpgo&quot;<br>  instance   = google_sql_database_instance.sql_instance_inertia.name<br>  depends_on = [google_sql_database_instance.sql_instance_inertia]<br>}<br><br>resource &quot;google_sql_user&quot; &quot;sftpgo_db_user&quot; {<br>  project    = var.project_id<br>  host       = &quot;%&quot;<br>  name       = var.sftp_sql_db_username<br>  instance   = google_sql_database_instance.sql_instance_inertia.name<br>  password   = var.sftp_sql_db_password<br>  depends_on = [google_sql_database.sftpgo_database]<br>}</pre><p>At this point we have a working SQL instance which is ready to accept connections.</p><h3>Cr<strong>eating Artifact Registry and Image</strong></h3><p>Like previous step, we need to enable the required API for this step as well:</p><pre>resource &quot;google_project_service&quot; &quot;artifact_registry_api&quot; {<br>  project = var.project_id<br>  service = &quot;artifactregistry.googleapis.com&quot;<br>}</pre><p>You can refer to the shell script provided in previous section. Same script can be called to check if “Artifact Registry API” is up or not. We will use following Terraform code to do so.</p><pre>resource &quot;null_resource&quot; &quot;wait_for_artifact_registry_api&quot; {<br>  depends_on = [google_project_service.artifact_registry_api]<br><br>  provisioner &quot;local-exec&quot; {<br>    command     = &quot;bash ../resources/check_api_exists.sh ${var.project_id} artifactregistry.googleapis.com&quot;<br>    working_dir = path.module<br>  }<br>}</pre><p>Thereafter, I use following code to create “Artifact Registry” in GCP:</p><pre>resource &quot;google_artifact_registry_repository&quot; &quot;test-sftpgo-image-repo&quot; {<br>  project       = var.project_id<br>  location      = var.registry_region<br>  repository_id = var.registry_name<br>  description   = &quot;This repository is used to store SFTPGo image&quot;<br>  format        = &quot;DOCKER&quot;<br>  depends_on    = [null_resource.wait_for_artifact_registry_api]<br>}</pre><p>Notice how I use “depends_on” to first wait and see if the API is enabled, yet or not. This is important because we can create “Artifact Registry” only when Artifact Registry API is ready.</p><p>I have created a directory named “Docker” at the same level as my main.tf for this step. Inside my directory I have a “Dockerfile” and a directory “config” with SSH keys needed by SFTPGo. It can be easily configured to be pulled directly from Google Secrets as well.</p><p>Here is the <strong>Dockerfile</strong>:</p><pre>FROM drakkan/sftpgoARG SQL_USERNAME<br>ARG SQL_PASSWORD<br>ARG HOST_IP<br>USER root<br>RUN mkdir /etc/sftpgo/env.d/<br>RUN echo &quot;SFTPGO_DATA_PROVIDER__DRIVER=mysql&quot; &gt;&gt; /etc/sftpgo/env.d/mysql.env &amp;&amp; \<br>    echo &quot;SFTPGO_DATA_PROVIDER__NAME=sftpgo&quot; &gt;&gt; /etc/sftpgo/env.d/mysql.env &amp;&amp; \<br>    echo &quot;SFTPGO_DATA_PROVIDER__HOST=${HOST_IP}&quot; &gt;&gt; /etc/sftpgo/env.d/mysql.env &amp;&amp; \<br>    echo &quot;SFTPGO_DATA_PROVIDER__PORT=3306&quot; &gt;&gt; /etc/sftpgo/env.d/mysql.env &amp;&amp; \<br>    echo &quot;SFTPGO_DATA_PROVIDER__USERNAME=${SQL_USERNAME}&quot; &gt;&gt; /etc/sftpgo/env.d/mysql.env &amp;&amp; \<br>    echo &quot;SFTPGO_DATA_PROVIDER__PASSWORD=${SQL_PASSWORD}&quot; &gt;&gt; /etc/sftpgo/env.d/mysql.env<br>RUN apt-get update &amp;&amp; apt-get install -y jq<br>RUN jq &quot;.data_provider.driver = \&quot;mysql\&quot; | .data_provider.name = \&quot;sftpgo\&quot; | .data_provider.host = \&quot;$HOST_IP\&quot; | .data_provider.port = 3306 | .data_provider.username = \&quot;$SQL_USERNAME\&quot; | .data_provider.password = \&quot;$SQL_PASSWORD\&quot;&quot; /etc/sftpgo/sftpgo.json &gt; temp.json &amp;&amp; \<br>    mv temp.json /etc/sftpgo/sftpgo.json<br>COPY config/. /var/lib/sftpgo/<br>RUN chown -R 1100:1100 /etc/sftpgo &amp;&amp; chown 1100:1100 /var/lib/sftpgo /srv/sftpgo<br>RUN chmod -R 777 /etc/sftpgo &amp;&amp; chmod -R 777 /var/lib/sftpgo /srv/sftpgo<br>USER 1100:1100</pre><p>I am then building the image and pushing it to Artifact Registry:</p><pre>resource &quot;null_resource&quot; &quot;build_and_push_image&quot; {<br>  triggers = {<br>    always_run = timestamp()<br>  }<br>  depends_on = [google_artifact_registry_repository.test-sftpgo-image-repo]<br><br>  provisioner &quot;local-exec&quot; {<br>    command = &lt;&lt;EOT<br>      cd ${path.module}/Docker<br>      docker build --build-arg SQL_USERNAME=${var.sftp_sql_db_username} --build-arg SQL_PASSWORD=${var.sftp_sql_db_password} --build-arg HOST_IP=${var.sql_host_ip} -t sftpgo:v1 .<br>      docker tag sftpgo:v1 ${var.registry_region}-docker.pkg.dev/${var.project_id}/${var.registry_name}/${var.registry_name}:latest<br>      gcloud auth configure-docker ${var.registry_region}-docker.pkg.dev<br>      docker push ${var.registry_region}-docker.pkg.dev/${var.project_id}/${var.registry_name}/${var.registry_name}:latest<br>    EOT<br>  }<br>}</pre><p>Notice how I use “depends_on” to first wait for creation of “Artifact Registry”. I am also passing the SQL instance IP, capured in previous step, to Dockerfile where they will be used to setup SFTPGO to SQL connection. At this point, go back and read Dockerfile (provided above), it will make more sense.</p><h3>C<strong>reating a GKE cluster, workload and service</strong></h3><p>Like previous step, we need to enable the required API for this step as well:</p><pre>resource &quot;google_project_service&quot; &quot;gke_api&quot; {<br>  project = var.project_id<br>  service = &quot;container.googleapis.com&quot;<br>}</pre><p>You can refer to the shell script provided in second section. Same script can be called to check if “GKE API” is up or not. We will use following Terraform code to do so.</p><pre>resource &quot;null_resource&quot; &quot;wait_for_artifact_registry_api&quot; {<br>  depends_on = [google_project_service.gke_api]<br><br>  provisioner &quot;local-exec&quot; {<br>    command     = &quot;bash ../resources/check_api_exists.sh ${var.project_id} container.googleapis.com&quot;<br>    working_dir = path.module<br>  }<br>}</pre><p>Thereafter I use following code to create “GKE Cluster”:</p><pre>resource &quot;google_container_cluster&quot; &quot;test_sftpgo_cluster&quot; {<br>  name                = var.gke_cluster_name<br>  location            = &quot;us-west1&quot;<br>  project             = var.project_id<br>  enable_autopilot    = true<br>  depends_on          = [null_resource.wait_for_artifact_registry_api]<br>  deletion_protection = false<br><br>  vertical_pod_autoscaling {<br>    enabled = true<br>  }<br><br>  node_config {<br>    oauth_scopes = [&quot;https://www.googleapis.com/auth/cloud-platform&quot;]<br>  }<br><br>  dns_config {<br>    cluster_dns = &quot;CLOUD_DNS&quot;<br>  }<br><br>  addons_config {<br>    http_load_balancing {<br>      disabled = false<br>    }<br>  }<br>}</pre><p>Notice how I use “depends_on” to first wait and see if the GKE API is enabled, yet or not. This is important because we can create “GKE Cluster” only when GKE API is ready.</p><p>I have created a directory named “Cluster Configuration” at the same level as my main.tf for this step. Inside my directory I have a “workload.yaml” and “service.yaml”.</p><p><strong>workload.yaml</strong>:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: &quot;{{WORKLOAD_NAME}}&quot;<br>spec:<br>  selector:<br>    matchLabels:<br>      app: &quot;{{WORKLOAD_NAME}}&quot;<br>  template:<br>    metadata:<br>      labels:<br>        app: &quot;{{WORKLOAD_NAME}}&quot;<br>    spec:<br>      nodeSelector:<br>        cloud.google.com/gke-spot: &quot;true&quot;<br>      containers:<br>        - name: &quot;{{WORKLOAD_NAME}}&quot;<br>          image: &quot;{{IMAGE_URL}}&quot;<br>          ports:<br>            - containerPort: 8080<br>            - containerPort: 2022<br>          resources:<br>            requests:<br>              cpu: 256m<br>              ephemeral-storage: 1Gi<br>              memory: 512m</pre><p><strong>service.yaml</strong>:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: test-sftpgo-service<br>  annotations:<br>    cloud.google.com/l4-rbs: &quot;enabled&quot;<br>spec:<br>  type: LoadBalancer<br>  externalTrafficPolicy: Cluster<br>  selector:<br>    app: &quot;{{WORKLOAD_NAME}}&quot;<br>  ports:<br>    - name: tcp-port<br>      protocol: TCP<br>      port: 8080<br>      targetPort: 8080<br>    - name: sftp-port<br>      protocol: TCP<br>      port: 2022<br>      targetPort: 2022</pre><p>I am then deploying GKE workload and service using following code:</p><pre>resource &quot;null_resource&quot; &quot;gke-sftpgo-deployment&quot; {<br>  triggers = {<br>    cluster_endpoint   = google_container_cluster.test_sftpgo_cluster.endpoint<br>    ca_certificate     = base64decode(google_container_cluster.test_sftpgo_cluster.master_auth[0].cluster_ca_certificate)<br>    client_certificate = base64decode(google_container_cluster.test_sftpgo_cluster.master_auth[0].client_certificate)<br>    client_key         = base64decode(google_container_cluster.test_sftpgo_cluster.master_auth[0].client_key)<br>  }<br>  depends_on = [google_container_cluster.test_sftpgo_cluster]<br><br>  provisioner &quot;local-exec&quot; {<br>    working_dir = &quot;${path.module}/cluster-configuration&quot;<br>    command     = &lt;&lt;EOT<br>      gcloud container clusters get-credentials ${var.gke_cluster_name} --region us-west1 --project test-inertia-thakurritesh32<br>      cat workload.yaml | \<br>      sed &#39;s|{{IMAGE_URL}}|&#39;&quot;${var.sftpgo_image_url}&quot;&#39;|&#39; | \<br>      sed &#39;s|{{WORKLOAD_NAME}}|&#39;&quot;${var.workload_name}&quot;&#39;|&#39; &gt; updated_workload.yaml<br>      kubectl apply -f updated_workload.yaml<br>      cat service.yaml | \<br>      sed &#39;s|{{WORKLOAD_NAME}}|&#39;&quot;${var.workload_name}&quot;&#39;|&#39; &gt; updated_service.yaml<br>      kubectl apply -f updated_service.yaml<br>    EOT<br>  }<br>}</pre><p>I am using shell’s “sed” command to pass/replace desired parameters required by my workload.yaml and service.yaml.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>At this point you have successfully deployed “SFTPGo on Google Kubernetes Engine using Terraform” and you can access the URL that GKE displays for your service under “Service and Ingress”. Enjoy fiddeling with SFTPGo and see if it meets your engineering needs or not :)</p><p>Happy Deployment !</p><p>Happy Potatoes because you survived this long post:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*2QhtuJI401YW70d5urBKZQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=befc51d2c174" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Docker images using Bitbucket Pipelines]]></title>
            <link>https://medium.com/@thakur.ritesh19/testing-docker-images-using-bitbucket-pipelines-c27f7fbdfd73?source=rss-6c7ee8750f9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c27f7fbdfd73</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[aws-ecr]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[bitbucket-pipelines]]></category>
            <category><![CDATA[bitbucket]]></category>
            <dc:creator><![CDATA[Ritesh Thakur]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 01:43:53 GMT</pubDate>
            <atom:updated>2023-09-08T01:51:24.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*m7UCoUmISC-nKpT7DtIRVw.png" /></figure><p>I had recently come across a very interesting problem where we wanted to test our Docker images before deploying them in AWS ECR. Even though we unit test the code that leads to a Docker image, we also wanted to test the image after it was built. Our Docker image does following things:</p><ol><li>Takes file path as an input</li><li>Runs ML job on file</li><li>Produces an output file</li></ol><p>Since we use Bitbucket Pipelines at my organization to do 100% of our deployments, we wanted to achieve this “integration testing” of Docker image using Bitbucket Pipelines.</p><p>I will first paste the code snippet and then explain it in detail:</p><pre>definitions:<br>  services:<br>    docker:<br>      memory: 2048<br>  steps:<br>    - step: &amp;build_test_push_image<br>        image: python:3.8<br>        oidc: true<br>        services:<br>          - docker<br>        name: &quot;Automatic image building, integration testing and AWS deployment&quot;<br>        caches:<br>          - pip<br>        script:<br>          # ---------------------------------------------------------------------------<br>          # AWS CLI &amp; jq installation Installation:<br>          - cd .<br>          - pip install --upgrade pip<br>          - pip install awscli<br>          - pip install wheel<br>          - apt-get update &amp;&amp; apt-get install -y jq<br>          # ---------------------------------------------------------------------------<br>          # Downloading dependent packages:<br>          - git clone git@bitbucket.org:a.git<br>          - git clone git@bitbucket.org:b.git<br>          - git clone git@bitbucket.org:c.git<br>          - git clone git@bitbucket.org:d.git<br>          - git clone git@bitbucket.org:e.git<br>          # ---------------------------------------------------------------------------<br>          # AWS CLI authentication:<br>          - export AWS_ROLE_ARN=$BITBUCKET_ACCESS_ROLE<br>          - export AWS_WEB_IDENTITY_TOKEN_FILE=$(pwd)/web-identity-token<br>          - echo $BITBUCKET_STEP_OIDC_TOKEN &gt; $(pwd)/web-identity-token<br>          # ---------------------------------------------------------------------------<br>          # Fetch the MQTT secret and store it in appropriate_files<br>          - mkdir -p config_mqtt<br>          - SECRET_ROOT_CA=$(aws secretsmanager get-secret-value --secret-id root-CA --region us-west-1)<br>          - echo &quot;$SECRET_ROOT_CA&quot; | jq -r &#39;.SecretString&#39; &gt; config_mqtt/${ACCOUNT_ID}-root-CA.pem<br>          - SECRET_KEYFILE=$(aws secretsmanager get-secret-value --secret-id keyfile --region us-west-1)<br>          - echo &quot;$SECRET_KEYFILE&quot; | jq -r &#39;.SecretString&#39; &gt; config_mqtt/${ACCOUNT_ID}-bt2-results.pem.key<br>          - SECRET_CERTFILE=$(aws secretsmanager get-secret-value --secret-id certfile --region us-west-1)<br>          - echo &quot;$SECRET_CERTFILE&quot; | jq -r &#39;.SecretString&#39;&gt; config_mqtt/${ACCOUNT_ID}-bt2-results.pem.crt<br>          # Fetch and export GCP Keys as ENV variables<br>          - export GCP_KEY=$(aws secretsmanager get-secret-value --secret-id $SECRET_KEY --region us-west-1 | jq -r &#39;.SecretString&#39;)<br>          # ---------------------------------------------------------------------------<br>          # Downloading config, input and expected output files for running Docker image<br>          - aws s3 sync s3://$INTEG_TEST_FILES_S3/ ./input_files --exclude &quot;*&quot; --include &quot;*_input.parquet&quot;<br>          - aws s3 sync s3://$INTEG_TEST_FILES_S3/ ./output_files --exclude &quot;*&quot; --include &quot;*_output.json&quot;<br>          - aws s3 sync s3://$INTEG_TEST_FILES_S3/ ./input_files --exclude &quot;*&quot; --include &quot;*.yml&quot;<br>          # ---------------------------------------------------------------------------<br>          # Building Docker image<br>          - docker build -t $IMAGE_NAME --build-arg &quot;ENV_PARAM=${GCP_KEY}&quot; .<br>          # ---------------------------------------------------------------------------<br>          # For each input file, running Docker to get output<br>          - |<br>            for input_file in ./input_files/*_input.parquet; do<br>             # Extract the base filename without extension<br>             base_filename=$(basename &quot;$input_file&quot; &quot;_input.parquet&quot;)<br>             docker run -v &quot;$(pwd)/input_files:/tmp&quot; &quot;${IMAGE_NAME}:latest&quot; &quot;/tmp/${base_filename}_input.parquet&quot; &quot;/tmp/config-v0.2.6.yml&quot; --pre-trained<br>            done<br>          # ---------------------------------------------------------------------------<br>          # For each output generated by Docker, comparing overall&#39;s result to expected output downloaded from S3<br>          - |<br>            for image_result in ./input_files/*_overall.json; do<br>             # Extract the base filename without extension (e.g., &quot;1&quot;)<br>             base_filename=$(basename &quot;$image_result&quot; &quot;_input_overall.json&quot;)<br>             # Form corresponding output filename<br>             output_file=&quot;./output_files/${base_filename}_output.json&quot;<br>             overall_value_generated=$(jq -r &#39;.Summary_sos_1.Overall&#39; &quot;$image_result&quot;)<br>             overall_value_expected=$(jq -r &#39;.Summary_sos_1.Overall&#39; &quot;$output_file&quot;)<br>             if [ &quot;$overall_value_generated&quot; == &quot;$overall_value_expected&quot; ]; then<br>               echo &quot;Generated overall result does match the expected overall result - TEST PASS for filename ${base_filename}_input.parquet&quot;<br>             else<br>               echo &quot;Generated overall result doesn&#39;t match the expected overall result - TEST FAIL for filename ${base_filename}_input.parquet&quot;<br>               exit 1<br>             fi<br>            done<br>          # ---------------------------------------------------------------------------<br>          # Uploading image to AWS ECR<br>          - export IMAGE_NAME_EXTENSION=&quot;latest&quot;<br>          - VERSION=$(&lt;VERSION.txt)<br>          - pipe: atlassian/aws-ecr-push-image:1.6.2<br>            variables:<br>              AWS_DEFAULT_REGION: &#39;us-west-1&#39;<br>              AWS_OIDC_ROLE_ARN: $BITBUCKET_ACCESS_ROLE<br>              IMAGE_NAME: &#39;$IMAGE_NAME:$IMAGE_NAME_EXTENSION&#39;<br>              TAGS: v$VERSION</pre><p>lines 15–21:<br>Here I am installing all the required libraries. “jq” will be used to read JSON files.</p><p>lines 22–28:<br>All the required Python packages are downloaded from Bitbucket repos. These will be copied inside Docker image using Dockerfile. From where they will be then installed using “pip”.</p><p>lines 29–33:<br>Using OIDC role, here AWS CLI is being authenticated. “<strong>BITBUCKET_ACCESS_ROLE</strong>” is a “<strong>Repository Variable</strong>” being used. Repository variables are feature of Bitbucket Pipelines and can be easily set using “Repository Settings” for each repository individually.</p><p>lines 34–44:<br>Here I am downloading certificates and credentials that my code inside Docker image will be using. Secrets are fetched from “<strong>AWS Secrets Manager</strong>” using AWS CLI.</p><p>lines 45–49:<br>Downloading files from S3 bucket. Name of S3 bucket is saved as “Repository Variable” named “<strong>INTEG_TEST_FILES_S3”. </strong>I download all inputs (in my case parquet and yml files) in “<strong>input_files</strong>” directory. Similarly, I download output files in “<strong>output_files</strong>” directory.</p><p>lines 50–52:<br>Building Docker image.</p><p>lines 53–60:<br>For all files in “input_files” directory, running files through Docker image. My Docker image saves output with same name as input file, suffixed with “overall”. Docker image also saves output file in the same directory as input file.</p><p>lines 61–77:<br>Since, my Docker image saves output in same location with some suffix appended, I account for that. I compare the expected output (downloaded from S3 under output_files directory) to Docker’s output stored under input_files after Docker processes them.<br>If output mismatches, I exit. This step fails the pipeline and stops deployment. In other case when all cases pass, I continue with deployment.</p><p>lines 78–87:<br>Here I am simply uploading built and tested Docker image to AWS ECR.</p><p>Using this method, one can unit test code (not show here), build image using unit tested code, integration test built image and then deploy image to AWS ECR (or wherever !)</p><p>Happy Deployment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c27f7fbdfd73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning jobs on AWS Fargate]]></title>
            <link>https://medium.com/@thakur.ritesh19/deploying-machine-learning-jobs-on-aws-fargate-db23565f2cdd?source=rss-6c7ee8750f9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/db23565f2cdd</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[aws-fargate]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Ritesh Thakur]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 00:23:07 GMT</pubDate>
            <atom:updated>2023-09-09T01:31:12.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*Av3n90jTbQglOzd_hAmgRQ.png" /></figure><p>Running inference on ML models, which are lightweight, on AWS Lambda is a widely accepted and practiced approach. However, when Model Training is needed a much more robust approach is needed, since model training can take hours if not days. In this post, I will try to demonstrate use of AWS S3, AWS Lambda and AWS Fargate for Machine Learning (ML) model training and inference. In the use case this post will be exploring, a user dumps a file to S3 from where the whole training/inference process is triggered. I have written a separate <a href="https://medium.com/@thakur.ritesh19/uploading-large-payloads-to-s3-using-api-gateway-lambda-102c9102520a">post</a> on how user can send a file&gt;10 MB to S3 using API Gateway. Without any further delay, let us get to the task at hand. I will be breaking down the article into following steps:</p><ol><li><strong>Creating a VPC in AWS.</strong></li><li><strong>Creating an EFS storage in AWS.</strong></li><li><strong>Creating an AWS ECS cluster.</strong></li><li><strong>Creating a Task definition in ECS.</strong></li><li><strong>Creating an “AWS Lambda” function.</strong></li></ol><p>Readers can feel free to skip a section if they are already acquainted with any of the aforementioned setups. Do not let length of this article discourage you, most of it is just images for easy reading :)</p><p><strong>Prerequisites:</strong></p><p>A fully function Docker image, that takes an input and gives output.</p><p><strong>Architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*Cu8pkv6Q2tH72TBhqi7wCQ.png" /></figure><h3>C<strong>reating a “VPC” in AWS</strong></h3><p>To create an “<strong>AWS VPC”</strong> follow these steps:</p><ul><li>Go to <a href="https://us-west-1.console.aws.amazon.com/vpc/home?region=us-west-1#Home:">this</a> link after logging into your respective AWS account.</li><li>Select a “region” of choice from top right corner of your page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Js1Gz1SBGnD2OseJM0LziA.png" /></figure><ul><li>Click on “<strong>Create VPC”</strong>.</li><li>Fill up the “<strong>Basic information</strong>” section like the following image then click “<strong>Create function</strong>” button on bottom-right side of screen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zxModxtnMTohn3XDLzKsA.png" /></figure><h3>C<strong>reating an EFS storage in AWS</strong></h3><p>To create an “<strong>AWS EFS”</strong> follow these steps:</p><ul><li>Go to <a href="https://us-west-1.console.aws.amazon.com/efs/home?region=us-west-1#/file-systems">this</a> link after logging into your respective AWS account.</li><li>Select a “region” of choice from top right corner of your page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Js1Gz1SBGnD2OseJM0LziA.png" /></figure><ul><li>Click on “<strong>Create file system”</strong>.</li><li>Give a “<strong>Name</strong>” and select “<strong>VPC</strong>” created in previous step “<strong>Creating a VPC” in AWS</strong>”</li><li>Create 2 “<strong>Access Points</strong>”. Both of these will be used later</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFCiiv1_zMCtErMMF8tndQ.png" /></figure><h3>Creating an AWS ECS Cluster</h3><p>To create an “<strong>AWS ECS Cluster”</strong> follow these steps:</p><ul><li>Go to <a href="https://us-west-1.console.aws.amazon.com/ecs/v2/clusters?region=us-west-1">this</a> link after logging into your respective AWS account.</li><li>Select a “region” of choice from top right corner of your page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Js1Gz1SBGnD2OseJM0LziA.png" /></figure><ul><li>Click on “<strong>Create cluster”</strong>.</li><li>Give a name for your cluster and select “<strong>AWS Fargate (serverless)</strong>” option. Then click on “<strong>Create</strong>”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*UriKNqshqvpPNQxX5Jk6eA.png" /></figure><h3>Creating an AWS ECS Task Definition</h3><p>To create an “AWS ECS Task Definition<strong>”</strong> follow these steps:</p><ul><li>Go to <a href="https://us-west-1.console.aws.amazon.com/ecs/v2/clusters?region=us-west-1">this</a> link after logging into your respective AWS account.</li><li>Select a “region” of choice from top right corner of your page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Js1Gz1SBGnD2OseJM0LziA.png" /></figure><ul><li>Click on “<strong>Create new task definition</strong>” and then select “<strong>Create new task definition with JSON</strong>”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*EKivRxWghKqKfUHcJ43G5A.png" /></figure><ul><li>Following JSON can be used to create a “<strong>Task Definition</strong>”</li></ul><pre>{<br>    &quot;family&quot;: &quot;TASK_FAMILY_NAME&quot;,<br>    &quot;containerDefinitions&quot;: [<br>        {<br>            &quot;name&quot;: &quot;ets-ai&quot;,<br>            &quot;image&quot;: &quot;AI_IMAGE_TO_RUN&quot;,<br>            &quot;cpu&quot;: 2048,<br>            &quot;memory&quot;: 4096,<br>            &quot;portMappings&quot;: [<br>                {<br>                    &quot;containerPort&quot;: 80,<br>                    &quot;hostPort&quot;: 80,<br>                    &quot;protocol&quot;: &quot;tcp&quot;<br>                }<br>            ],<br>            &quot;essential&quot;: true,<br>            &quot;command&quot;: [<br>                &quot;&quot;,<br>                &quot;&quot;,<br>                &quot;&quot;<br>            ],<br>            &quot;environment&quot;: [],<br>            &quot;mountPoints&quot;: [<br>                {<br>                    &quot;sourceVolume&quot;: &quot;database&quot;,<br>                    &quot;containerPath&quot;: &quot;/tmp&quot;,<br>                    &quot;readOnly&quot;: false<br>                }<br>            ],<br>            &quot;volumesFrom&quot;: [],<br>            &quot;logConfiguration&quot;: {<br>                &quot;logDriver&quot;: &quot;awslogs&quot;,<br>                &quot;options&quot;: {<br>                    &quot;awslogs-group&quot;: &quot;ets-logs&quot;,<br>                    &quot;awslogs-region&quot;: &quot;us-west-1&quot;,<br>                    &quot;awslogs-stream-prefix&quot;: &quot;ai&quot;<br>                }<br>            }<br>        }<br>    ],<br>    &quot;taskRoleArn&quot;: &quot;ROLE_TO_RUN_FARGATE_TASK&quot;,<br>    &quot;executionRoleArn&quot;: &quot;ROLE_TO_RUN_FARGATE_TASK&quot;,<br>    &quot;networkMode&quot;: &quot;awsvpc&quot;,<br>    &quot;volumes&quot;: [<br>        {<br>            &quot;name&quot;: &quot;database&quot;,<br>            &quot;efsVolumeConfiguration&quot;: {<br>                &quot;fileSystemId&quot;: &quot;EFS_ID_FROM_PREVIOUS_STEP_EFS_CREATION&quot;,<br>                &quot;rootDirectory&quot;: &quot;/&quot;,<br>                &quot;transitEncryption&quot;: &quot;ENABLED&quot;,<br>                &quot;authorizationConfig&quot;: {<br>                    &quot;accessPointId&quot;: &quot;1ST_ACCESS_POINT_IN_2ND_SCREENSHOT_IN_PREVIOUS_SECTION&quot;,<br>                    &quot;iam&quot;: &quot;ENABLED&quot;<br>                }<br>            }<br>        }<br>    ],<br>    &quot;requiresCompatibilities&quot;: [<br>        &quot;EC2&quot;,<br>        &quot;FARGATE&quot;<br>    ],<br>    &quot;cpu&quot;: &quot;2048&quot;,<br>    &quot;memory&quot;: &quot;4096&quot;,<br>}</pre><ul><li>Click on “<strong>Create</strong>”</li></ul><h3>Creating an AWS Lambda Function</h3><p>Please refer to <a href="https://medium.com/@thakur.ritesh19/deploying-a-containerized-aws-lambda-using-bitbucket-pipelines-9198ca10dbe8">this</a> post to create a container based Lambda function.</p><p>After your Lambda is created, set up your VPC for your Lambda like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RopEx9l8VkLKoWQHidXkkw.png" /></figure><p>Change VPC, Subnets and Security group per your network configuration.</p><p>Post doing VPC configuration, add EFS file system like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXEKd9dzAbQhwhfr62IX-g.png" /></figure><p>“File system ID” would be ID of EFS created in EFS step. “Access point ID” would be ID of second access point in second screenshot in EFS step.</p><p>After following all the aforementioned steps, developer can configure a S3 trigger. Upon receiving an input file in S3 bucket (users can read <a href="https://medium.com/@thakur.ritesh19/uploading-large-payloads-to-s3-using-api-gateway-lambda-102c9102520a">this</a> post for such a setup), Lambda can be used to move the file first to EFS, then submit an ECS task with EFS file path.</p><p>If VPC and File System was correctly configured, when you use following snippet, file would be downloaded to “<strong>/mnt/lambda</strong>” location. A code snippet to download a file onto EFS here:</p><pre>def download_files_to_efs(file_bucket, file_key, file_name, account_id):<br>    s3_client = boto3.client(&#39;s3&#39;,<br>                             endpoint_url=S3_ENDPOINT_URL[account_id],<br>                             region_name=&#39;us-west-1&#39;)<br>    efs_loc = f&quot;/mnt/lambda/{file_name}&quot;<br>    lambda_dir = os.path.join(&quot;/tmp&quot;, file_name)<br>    s3_client.download_file(file_bucket, file_key, lambda_dir)<br>    command = f&#39;cp &quot;/tmp/{file_name}&quot; &quot;{efs_loc}&quot;&#39;<br>    os.system(command)<br>    return &quot;Copied to EFS&quot;</pre><p>In our task definition we mount our EFS to /tmp, hence file’s path on EFS become “<strong>/tmp/lambda</strong>” instead of “<strong>/mnt/lambda</strong>” at this stage. Accordingly, a code snippet to submit Fargate task at this point is provided below:</p><pre>response_ai_task = ecs_client.run_task(<br>    cluster=&#39;YOUR_CLUSTER_NAME_FROM_ECS_STEP_ABOVE&#39;,<br>    count=1,<br>    launchType=&#39;FARGATE&#39;,<br>    networkConfiguration=NETWORK_CONFIGURATION[account_id],<br>    overrides={<br>        &quot;containerOverrides&quot;: [{<br>            &quot;name&quot;: &quot;CUSTOM_NAME&quot;,<br>            &quot;command&quot;: [f&quot;/tmp/lambda/{file_name}&quot;],<br>            &quot;cpu&quot;: 4096,<br>            &quot;memory&quot;: 8192<br>        }],<br>        &quot;cpu&quot;: &quot;4096&quot;,<br>        &quot;memory&quot;: &quot;8192&quot;<br>    },<br>    taskDefinition=&quot;ARN_OF_YOUR_TASK_DEFINITION_CREATED_IN_STEP_ABOVE&quot;)</pre><p>where; file_name is the name of file downloaded from S3.</p><p>Happy Deployment!</p><p>Happy Potatoes because you survived this long post:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*PhX3l4Txnswj7iLJALao1w.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db23565f2cdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading large payloads to S3 using API Gateway + Lambda]]></title>
            <link>https://medium.com/@thakur.ritesh19/uploading-large-payloads-to-s3-using-api-gateway-lambda-102c9102520a?source=rss-6c7ee8750f9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/102c9102520a</guid>
            <category><![CDATA[large-file-upload]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <dc:creator><![CDATA[Ritesh Thakur]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 19:54:11 GMT</pubDate>
            <atom:updated>2023-04-06T18:53:53.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*CBG9nbLwWLkWYn8iBidPsw.png" /></figure><p>Securely uploading a file to S3 using API Gateway has been widely used in tech industry. API gateway however only support files &lt; 10 mb. In order to securely upload files &gt; 10 mb, a more sophisticated solution involving Lambda running in the backend to generate pre-signed URLs, can be used. Pre-signed URL generated by AWS Lambda can then be used to upload large files to S3. This article is my attempt to walk a beginner through a setup involving API Gateway, Lambda and S3 to upload large files to S3 securely and directly. Without any further delay, let us get to the task at hand. I will be breaking down the article into following steps:</p><ol><li><strong>Creating an “AWS Lambda” function.</strong></li><li><strong>Creating a REST API with Lambda proxy integration.</strong></li><li><strong>Writing a Python code to upload a local file to S3 using PUT method.</strong></li></ol><p>Readers can feel free to skip a section if they are already acquainted with any of the aforementioned setups. Do not let length of this article discourage you, most of it is just images for easy reading :)</p><h3><strong>Creating an “AWS Lambda” function</strong></h3><p>To create an “<strong>AWS Lambda”</strong> follow these steps:</p><ul><li>Go to <a href="https://us-west-2.console.aws.amazon.com/lambda/home?region=us-west-2#/functions">this</a> link after logging into your respective AWS account.</li><li>Select a “region” of choice from top right corner of your page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Js1Gz1SBGnD2OseJM0LziA.png" /></figure><ul><li>Click on “<strong>Create function”</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*sXaKrTH_JxrIqcYC6x8Q-g.png" /></figure><ul><li>Fill up the “<strong>Basic information</strong>” section like the following image then click “<strong>Create function</strong>” button on bottom-right side of screen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rp7i5aDs6KX24tWC7uQjxg.png" /></figure><p>Once role is created, your AWS Lambda will be ready. Post Lambda is created, open your function and select “<strong>Code</strong>”. Paste the following code. Following code generates a pre-Signed expiring URL which will then be used by user later in this article.</p><pre>import boto3<br><br><br>def lambda_handler(event, context):<br>    # Get the service client.<br>    s3 = boto3.client(&#39;s3&#39;)<br><br>    # Generate the presigned URL for put requests<br>    presigned_url = s3.generate_presigned_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20ClientMethod=&#39;put_object&#39;,%3Cbr%3E%20%20%20%20%20%20%20%20Params={%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20&#39;Bucket&#39;:%20&#39;YOUR_BUCKET&#39;,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20#%20In%20order%20to%20retain%20the%20file%20name,%20I%20am%20reading%20key%20from%20API%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20#%20request.%20Caller%20needs%20to%20provide%20file%20name%20as%20&quot;queryStringParameter&quot;.%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20#%20We%20will%20get%20to%20this%20part%20in%20next%20segment.%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20&#39;Key&#39;:%20event[&#39;queryStringParameters&#39;][&#39;file_name&#39;]%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20#%20Eg.%20on%20how%20to%20push%20file%20to%20S3%20folde3r%20will%20be%20given%20under%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20#%20&quot;Writing%20a%20Python%20code%20to%20upload%20a%20local%20file%20to%20S3%20using%20%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20#%20PUT%20method&quot;%20segment.%3Cbr%3E%20%20%20%20%20%20%20%20}%3Cbr%3E)<br><br>    # Return the presigned URL<br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: presigned_url<br>    }</pre><h3>Creating <strong>a REST API with Lambda proxy integration</strong></h3><p>To create an “<strong>AWS API Gateway”</strong> follow these steps:</p><ul><li>Go to <a href="https://us-east-1.console.aws.amazon.com/apigateway/main/apis?region=us-east-1">this</a> link after logging into your respective AWS account.</li><li>Select a “region” of choice from top right corner of your page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Js1Gz1SBGnD2OseJM0LziA.png" /></figure><ul><li>Click on “<strong>Create API”</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*TXt0PEs2B023PGhqOdco8g.png" /></figure><ul><li>Select “<strong>Rest API</strong>” and click on “<strong>Build</strong>”. You can select “Private” variant but for the sake of this article we will be creating a “Public” API.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QpywH5TWKNZgtMwBJmIWA.png" /></figure><ul><li>Fill the next page as following and click on “Create API”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsRrTV_DyYS5yuMPab-8rA.png" /></figure><ul><li>To create a resource, select “<strong>/</strong>” -&gt; “<strong>Actions</strong>” -&gt; “<strong>Create Resource</strong>” and then fill as follows.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0Fm3wMlpefVlR-XknBtyA.png" /></figure><ul><li>To create a method, select “<strong>/</strong>” -&gt; “<strong>Actions</strong>” like previous step, then choose “<strong>Create Method</strong>”. Select “POST” as your method, then click on check mark next to it.</li><li>Once your method is created, you have to setup a Lambda integration. Refer to following image. Once done, click on “<strong>Save</strong>” on bottom right-side of screen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmAfenvSq2ViNXigmgNdtQ.png" /></figure><ul><li>Once done, deploy your API like following.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*iIRH21rgtk1ln-leo10WEQ.png" /></figure><ul><li>Give a stage name liek following.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*hhhJuayohjkT9ymGwMxxnA.png" /></figure><ul><li>Got to “<strong>Stages</strong>” and then “<strong>POST</strong>” to get the “<strong>Invoke URL</strong>” like following.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*os2dBYgOz1KHVUO8AfOKBg.png" /></figure><ul><li>You can then go to “<strong>Resources</strong>” -&gt; “<strong>POST</strong>” -&gt; “<strong>Test</strong>”, paste the URL copied from previous step in “<strong>Request Body</strong>” then click on “<strong>Test</strong>”.</li></ul><h3><strong>Writing a Python code to upload a local file to S3 using PUT method</strong></h3><p>The following code can be used to send a file to S3 using the setup above.</p><pre>import requests<br>from aws_requests_auth.aws_auth import AWSRequestsAuth<br><br>auth = AWSRequestsAuth(aws_access_key=&#39;YOUR_KEY&#39;,<br>                       aws_secret_access_key=&#39;YOUR_SECRET&#39;,<br>                       aws_host=&#39;YOUR_API_ID.execute-api.YOUR_API_REGION.amazonaws.com&#39;,<br>                       aws_region=&#39;YOUR_REGION&#39;,<br>                       aws_service=&#39;execute-api&#39;)<br><br>response = requests.post(&#39;https://YOUR_API_ID.execute-api.YOUR_API_REGION.amazonaws.com/Test/import&#39;,<br>                         auth=auth)<br>with open(&quot;YOUR_LOCAL_FILE_TO_TRANSFER&quot;) as fh:<br>    response = requests.put(response.content.decode(&quot;utf-8&quot;), data=fh.read())</pre><p>In case user needs to pass file name or folder name that they want in S3, URL Query String Parameters can be used. In order to set it up, refer to image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkGsZfuLKKYVkgabkbR-dQ.png" /></figure><p>User can then refer to code above but fire POST request as following instead.</p><pre>response = requests.post(&#39;https://YOUR_API_ID.execute-api.YOUR_API_REGION.amazonaws.com/Test/import?file_name=abc&#39;,<br>                         auth=auth)</pre><p>This will create a file named “abc” in your bucket. However, if user wants a bucket “def” created and then want to copy file “abc”, refer to following code.</p><pre>response = requests.post(&#39;https://YOUR_API_ID.execute-api.YOUR_API_REGION.amazonaws.com/Test/import?file_name=def%2Fabc&#39;,<br>                         auth=auth)</pre><p>Happy Deployment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=102c9102520a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a “Container” based AWS Lambda using bitbucket-pipelines]]></title>
            <link>https://medium.com/@thakur.ritesh19/deploying-a-containerized-aws-lambda-using-bitbucket-pipelines-9198ca10dbe8?source=rss-6c7ee8750f9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9198ca10dbe8</guid>
            <category><![CDATA[aws-ecr]]></category>
            <category><![CDATA[aws-container]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[bitbucket-pipelines]]></category>
            <category><![CDATA[bitbucket]]></category>
            <dc:creator><![CDATA[Ritesh Thakur]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 00:11:25 GMT</pubDate>
            <atom:updated>2023-04-06T00:07:25.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*8hK70nrduGjqgeoZ68zobw.png" /></figure><p>AWS Lambda has always suffered with an upper cap on Lambda size that can be deployed. To elevate this, engineers zip their Lambda code, deploy it to AWS S3 and from thereon deploy their Lambda. If you are a reader who in interested in deploying Lambda using S3, follow this <a href="https://aws.amazon.com/blogs/compute/new-deployment-options-for-aws-lambda/">link.</a> However, in December 2020, AWS finally started supporting deployment of Lambda using Containers (Docker Images). When I was working on setting up end-to-end CI/CD (Continuous Integration/Continuous Deployment) for “Container” based AWS Lambda using bitbucket-pipelines, I realized that no one stop guide exists for such a setup, so I decided to create one. Without delaying much let us get into the task. I have split this article into following segments:</p><ol><li><strong>How to create a “Container” based AWS Lambda?</strong></li><li><strong>How to create an AWS ECR Repository?</strong></li><li><strong>How to create a Bitbucket repository?</strong></li><li><strong>bitbucket-pipelines.yml code for Continuous Deployment (CD) of AWS Lambda using Docker Images.</strong></li></ol><p>Readers can feel free to skip a section if they are already acquainted with any of the aforementioned setups. Do not let length of this article discourage you, most of it is just images for easy reading :)</p><h3><strong>How to create a “Containerized” AWS Lambda</strong></h3><p>To create an “<strong>AWS Lambda”</strong> follow these steps:</p><ul><li>Go to <a href="https://us-west-2.console.aws.amazon.com/lambda/home?region=us-west-2#/functions">this</a> link after logging into your respective AWS account.</li><li>Select a “region” of choice from top right corner of your page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Js1Gz1SBGnD2OseJM0LziA.png" /></figure><ul><li>Click on “<strong>Create function”</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*sXaKrTH_JxrIqcYC6x8Q-g.png" /></figure><ul><li>Select “<strong>Container image”</strong> option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*pIIoiD33s1HaTFc5hUo9BQ.png" /></figure><ul><li>Fill up the “<strong>Basic information</strong>” section like the following image. “<strong>Container Image URI</strong>” at this point can be set to any Image’s URI from ECR. We will auto-update this “Container Image URI” using bitbucket-pipelines anyway.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7RuprhBVGGOoK14sull6w.png" /></figure><ul><li>Post a role is created for your lambda, click on “<strong>Create function”</strong> on bottom right side of screen. Give required permission to your lambda role. We DO NOT need to give “ECR Permissions” to this role. However, if “ECR Permissions” is needed for your Lambda’s execution in some other way, feel free to add it.</li></ul><h3><strong>How to create an AWS ECR Repository</strong></h3><p>To create an “<strong>AWS ECR” </strong>repository follow these steps:</p><ul><li>Go to <a href="https://us-west-2.console.aws.amazon.com/ecr/repositories?region=us-west-2">this</a> link after logging into your respective AWS account.</li><li>Select a “region” of choice from top right corner of your page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Js1Gz1SBGnD2OseJM0LziA.png" /></figure><ul><li>Click on “<strong>Create repository”</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*665LmHgbw9G32MIQUONS4Q.png" /></figure><ul><li>Fill up the “<strong>General settings</strong>” and “<strong>Image scan settings”</strong> section like the following image.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*DzblYXVl6bwFwtBf1o0MJg.png" /></figure><ul><li>For scope of this article, we will leave “<strong>Encryption settings”</strong> as Disabled.</li><li>Click on “<strong>Create repository”</strong> on bottom right side of screen.</li></ul><h3><strong>How to create a Bitbucket repository</strong></h3><p>To create a repository in Bitbucket with “master” and “dev” branches, please follow steps listed below:</p><ul><li>Go to this <a href="https://bitbucket.org/dashboard/repositories">link</a>.</li><li>Click on “<strong>Create Repository</strong>” on the top-right side of your screen. Refer to image below and proceed accordingly. “<strong>Language</strong>” and “<strong>Project</strong>” should be selected per project’s needs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*Ao5CKwIsccN548Un3txiJw.png" /></figure><ul><li>To create a “dev” branch, go to “<strong>Branches</strong>” on left side menu (refer to attached image below)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*XcvVNg3Z6oAMnYJZh2x1aw.png" /></figure><ul><li>Click on “<strong>Create branch</strong>” on the top-right side of your screen and create your “dev” branch like this.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Rs8ftGsTp3IjDKjT8KqbVQ.png" /></figure><ul><li>Next, go to “<strong>Repository Settings</strong>” -&gt; “<strong>Branching Model</strong>” using left side menu.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*WjEBquim0BYZjrJVgPtjHA.png" /></figure><ul><li>Post opening “<strong>Branching Model</strong>”, configure your branches like screenshot below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*4xeXQi_FM3AwOmwbCc508g.png" /></figure><ul><li>Go to “<strong>Branches</strong>” page from your left side page menu (see step 3 for image), your branches should look like following.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*NSDI0FkoviyVJV7ZDbXOTg.png" /></figure><h3><strong>bitbucket-pipelines.yml setup for Continuous Deployment of AWS Lambda</strong></h3><p>In order to automate deployment of your code via a docker image using “<strong>bitbucket-pipelines.yml</strong>” use the following code snippet. Please keep in mind that “<strong>AWS Access Key ID</strong>” and “<strong>AWS Secret Access Key</strong>” should be generated from either “a user” or “a role”, that has access to AWS ECR and AWS Lambda. Readers can also take a look at <a href="https://support.atlassian.com/bitbucket-cloud/docs/deploy-on-aws-using-bitbucket-pipelines-openid-connect/">this</a> article which walks through on how to setup “<strong>OIDC</strong>”, which can also be used to connect to AWS.</p><pre>image: python:3.8<br><br>pipelines:<br>  branches:<br>    # Whatever branch you want to set CD for<br>    dev:<br>      - step:<br>            oidc: true<br>            name: &quot;Deploy Python code as an image to be used by AWS Lambda&quot;<br>            image: amazon/aws-cli<br>            deployment: Test<br>            services:<br>              - docker<br>            caches:<br>              - pip<br>            script:<br>              - cd .<br>              - export IMAGE_NAME=&quot;YOUR_IMAGE_NAME&quot;<br>              - export IMAGE_NAME_EXTENSION=&quot;latest&quot;<br>              - VERSION=$(&lt;version.txt)<br>                # Your Dockerfile is expected to be at root directory, but obv you can customize path.<br>              - docker build -t $IMAGE_NAME .<br>                # Following piece of code pushes image to ECR<br>              - pipe: atlassian/aws-ecr-push-image:1.6.2<br>                variables:<br>                  AWS_DEFAULT_REGION: &#39;us-west-2&#39;<br>                  AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID<br>                  AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY<br>                  IMAGE_NAME: &#39;$IMAGE_NAME:$IMAGE_NAME_EXTENSION&#39;<br>                  TAGS: ${BITBUCKET_BRANCH}_$VERSION<br>                # Following piece of code updates Lambda&#39;s image<br>                # Without this step, lambda keeps using the last manually set image even if image name or URI stays the same.<br>              - pipe: atlassian/aws-lambda-deploy:1.7.0<br>                variables:<br>                  AWS_DEFAULT_REGION: &#39;us-west-2&#39;<br>                  AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID<br>                  AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY<br>                  FUNCTION_NAME: &#39;YOUR_LAMBDA_FUNCTION_NAME&#39;<br>                  COMMAND: &#39;update&#39;<br>                  # This will auto update the &quot;Container Image URI&quot; we set while creating our Lambda<br>                  IMAGE_URI: &#39;YOUR_AWS_ACCOUNT_NUMBER.dkr.ecr.us-west-2.amazonaws.com/$IMAGE_NAME:${BITBUCKET_BRANCH}_$VERSION&#39;</pre><p>Post completing all the aforementioned steps, a user can start committing code to repository’s branch for which bitbucket-pipelines is setup. An automatic deployment will be triggered in Bitbucket Pipelines. Post deployment is completed successfully, user’s newly committed code will be readily available whenever Lambda is triggered.</p><p>Happy Deployment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9198ca10dbe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>