<?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 Majdi Dhissi on Medium]]></title>
        <description><![CDATA[Stories by Majdi Dhissi on Medium]]></description>
        <link>https://medium.com/@majdid?source=rss-23349e332d44------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GZesD1NjbGXnrizQ.</url>
            <title>Stories by Majdi Dhissi on Medium</title>
            <link>https://medium.com/@majdid?source=rss-23349e332d44------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:23:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@majdid/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[F1 Telemetry with AWS (and a PS5)]]></title>
            <link>https://towardsaws.com/f1-telemetry-with-aws-and-a-ps5-ea5a774fce9d?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea5a774fce9d</guid>
            <category><![CDATA[formula-1]]></category>
            <category><![CDATA[influxdb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[telemetry]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 16:54:23 GMT</pubDate>
            <atom:updated>2024-10-27T18:22:37.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nch5I5LfHgzhpGlc_OyUdw.jpeg" /><figcaption>F1 Simulator in the AWS Summit 2024 Dubai</figcaption></figure><p>Every project often starts small, this one began with a 20-line script running on my laptop, before evolving into something more substantial.</p><p>The subject? Telemetry data from the thrilling world of F1 racing!</p><p>Real F1 cars are packed with cutting-edge sensors that record mountains of telemetry data, these machines are equipped with over 300 sensors that collectively generate an astounding 1.1 million telemetry data points every second, amounting to around 3 terabytes on a single session. This data encompasses a range of real-time metrics such as speed, tire pressure, engine performance, fuel consumption, aerodynamics, and driver inputs.</p><p>But what exactly is telemetry? It refers to the collection of measurements or data at remote points, which is then automatically transmitted to receiving equipment for monitoring. The term itself originates from the Greek words <em>tele</em> meaning ‘remote’ and <em>metron</em> meaning ‘measure.’</p><p>You may have seen telemetry systems featured in an AWS meetup, often accompanied by a stunning replica of an F1 car. A<a href="https://aws.amazon.com/sports/f1/">WS has collaborated with Formula 1</a> to deliver remarkable real-time data analysis solutions, showcased in events like the AWS F1 Sports Innovation. Failing to have a spare 20 million dollars to spend on an F1 car, i will be falling back to my good old PlayStation 5, which offers a more accessible alternative — broadcasting telemetry data from games like <a href="https://www.ea.com/en-au/games/f1/f1-24">F1® 2024</a>. The idea is to write a UDP listener, parse and filter data, send it to a data streaming engine, and visualize the results in a nice colorful dashboard, hopefully in real-time</p><p>So, without further due, let’s get to it</p><h3>F1 24 Telemetry Data Structure</h3><p>The first step was to do some research to understand what type of data i will be dealing with, and i came across the <a href="https://www.ea.com/en-au/games/f1/f1-24">F1® 2024</a> telemetry specifications, which i will leave a link down below. The document provides an overview of the data output supported by the <a href="https://www.ea.com/en-au/games/f1/f1-24">F1® 2024</a> game via UDP connections. This data can be used by external applications or hardware (such as motion platforms, force feedback steering wheels), and outlines the types of packets transmitted and details the <strong>structure </strong>and <strong>content </strong>of each packet type.</p><p>We will use it later to build a service that listens for UDP packets and processes them. For now, lets get to our high level architecture</p><h3>High Level Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*e67uycp5YKli11xK_VNGeQ.png" /></figure><p>We have a few options here:</p><ul><li>UDP listener acting as reading packets and transferring them to a WebSocket Server. Grafana will bind to the WebSocket server via <a href="https://grafana.com/grafana/plugins/golioth-websocket-datasource/">Grafana WebSocket </a>data source to ingest data and display it in real-time</li><li>UPD listener service will read packets and transfer them to a timeseries database that can be used as a data source for Grafana, in this case InfluxDB</li><li>A similar architecture such as the second one, while using Apache Kafka for real-time data processing and Prometheus for storage instead of InfluxDB</li></ul><p>The last one seems like an overkill, since Kafka itself is not a time-series database, and will be mainly used as a message broker to transport telemetry data in real time. We also do not require any specific processing, as the UDP listener will manage the filtering of the packets we want to visualize and handle the serialization to produce the data output according to our custom schema.</p><p>The first option is not particularly exciting, it took a few minutes to get a simple client-server up and running but that is not really what i wanted to focus on here, as persisting the data might come in handy in case we want to analyze it offline</p><p><em>So, lets go with option two! Here is what it looks like</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QL9XVS8s_nZ5gKQgf3cWQ.png" /><figcaption>High Level Design</figcaption></figure><h3>Key Components</h3><ul><li><strong>Network Load Balancer (NLB)</strong>: Entry point for UDP packets (port 20777) and TCP listeners allowing me to use the InfluxDB and Grafana GUI</li><li><strong>ECR Repository: </strong>This is where my UDP service image will be hosted and pulled from by ECS</li><li><strong>Elastic Container Service Cluster (ECS)</strong>: Deployed in the me-central-1 region which includes task definition and a service running three containers on Fargate instance on private subnets</li><li><strong>UDP Listener Service</strong>: A .Net worker service that receives telemetry data and processes the UDP packets based on the telemetry specification, and filters out any unecessary packets. Serialization is also performed to match a simplified data structure suitable for Grafana consumption.</li><li><strong>InfluxDB instance: </strong>This is our time-series database that will be used to persist telemetry data and serve as a data source for Grafana</li><li><strong>Grafana</strong>: Configured with a InfluxDB as a data source and a dashboard displaying various data points, which have been set to provision automatically during the container deployment. More information on provisioning at <a href="https://grafana.com/docs/grafana/latest/administration/provisioning/">https://grafana.com/docs/grafana/latest/administration/provisioning/</a></li></ul><p>Let’s not forget our PS5 which is our primary data source (although i used a mock UDP packet sending script to mimic sending data, i didn’t think leaving it on for debugging purposes would be a good idea, that thing gets HOT!)</p><blockquote><strong>InfluxDB </strong>is an open-source time series database (TSDB) created by InfluxData. It is designed for storing and retrieving time series data, commonly used in areas like operations monitoring, application metrics, IoT sensor data, and real-time analytics.</blockquote><p><strong>AWS </strong>offers a managed service called <strong>Timestream for InfluxDB</strong>, which allows you to run open-source InfluxDB databases on AWS. It supports time-series applications with millisecond-level response times and guarantees up to 99.9% availability. In a production environment, I would opt for AWS Timestream as it provides high availability while eliminating the need to manage the underlying infrastructure, configuration, and optimization tasks.</p><p>The interoperability advantages are also a big plus, Timestream integrates seamlessly with both SageMaker and QuickSight allowing you to easily leverage machine learning models for predictive analytics with SageMaker, especially when it comes to predictive maintenance, anomaly detection, demand forecasting and performance optimization, or if you are in a rush you can create interactive dashboards with QuickSight in no time!</p><h3>Now, let’s write some code!</h3><h4>UDP Listener Service</h4><p>I used the data structures to create the following data model for various packet types. There is much more data available, but the following telemetry and motion data is only what i am interested in</p><pre>using System.Runtime.InteropServices;<br><br>namespace FluxDBExporter.Data<br>{<br>    // Packet Header<br>    [StructLayout(LayoutKind.Sequential, Pack = 1)]<br>    public struct PacketHeader<br>    {<br>        public ushort PacketFormat;<br>        public byte GameYear;<br>        public byte GameMajorVersion;<br>        public byte GameMinorVersion;<br>        public byte PacketVersion;<br>        public byte PacketId;<br>        public ulong SessionUID;<br>        public float SessionTime;<br>        public uint FrameIdentifier;<br>        public uint OverallFrameIdentifier;<br>        public byte PlayerCarIndex;<br>        public byte SecondaryPlayerCarIndex;<br>    }<br><br>    // Car Motion Data<br>    [StructLayout(LayoutKind.Sequential, Pack = 1)]<br>    public struct CarMotionData<br>    {<br>        public float WorldPositionX;<br>        public float WorldPositionY;<br>        public float WorldPositionZ;<br>        public float WorldVelocityX;<br>        public float WorldVelocityY;<br>        public float WorldVelocityZ;<br>        public short WorldForwardDirX;<br>        public short WorldForwardDirY;<br>        public short WorldForwardDirZ;<br>        public short WorldRightDirX;<br>        public short WorldRightDirY;<br>        public short WorldRightDirZ;<br>        public float GForceLateral;<br>        public float GForceLongitudinal;<br>        public float GForceVertical;<br>        public float Yaw;<br>        public float Pitch;<br>        public float Roll;<br>    }<br><br>    // Car Telemetry Data<br>    [StructLayout(LayoutKind.Sequential, Pack = 1)]<br>    public struct CarTelemetryData<br>    {<br>        public ushort Speed;                       // Speed of car in kilometres per hour<br>        public float Throttle;                     // Amount of throttle applied (0.0 to 1.0)<br>        public float Steer;                        // Steering (-1.0 (full lock left) to 1.0 (full lock right))<br>        public float Brake;                        // Amount of brake applied (0.0 to 1.0)<br>        public byte Clutch;                        // Amount of clutch applied (0 to 100)<br>        public sbyte Gear;                         // Gear selected (1-8, N=0, R=-1)<br>        public ushort EngineRPM;                   // Engine RPM<br>        public byte DRS;                           // 0 = off, 1 = on<br>        public byte RevLightsPercent;              // Rev lights indicator (percentage)<br>        public ushort RevLightsBitValue;           // Rev lights (bit 0 = leftmost LED, bit 14 = rightmost LED)<br>        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]<br>        public ushort[] BrakesTemperature;         // Brakes temperature (celsius)<br>        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]<br>        public byte[] TyresSurfaceTemperature;     // Tyres surface temperature (celsius)<br>        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]<br>        public byte[] TyresInnerTemperature;       // Tyres inner temperature (celsius)<br>        public ushort EngineTemperature;            // Engine temperature (celsius)<br>        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]<br>        public float[] TyresPressure;              // Tyres pressure (PSI)<br>        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]<br>        public byte[] SurfaceType;                 // Driving surface<br>    }<br><br>    // Packet Car Telemetry Data<br>    [StructLayout(LayoutKind.Sequential, Pack = 1)]<br>    public struct PacketCarTelemetryData<br>    {<br>        public PacketHeader Header;<br>        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 22)] // Assuming 22 cars maximum<br>        public CarTelemetryData[] CarTelemetryData;<br><br>        public byte MfdPanelIndex;                  // Index of MFD panel open - 255 = MFD closed<br>        public byte MfdPanelIndexSecondaryPlayer;   // See above<br>        public sbyte SuggestedGear;                 // Suggested gear for the player (1-8)<br>    }<br><br>    // Packet Motion Data<br>    [StructLayout(LayoutKind.Sequential, Pack = 1)]<br>    public struct PacketMotionData<br>    {<br>        public PacketHeader Header;<br>        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 22)] // We will assume 22 cars maximum<br>        public CarMotionData[] CarMotionData;<br><br>        public PacketMotionData(int numCars)<br>        {<br>            Header = new PacketHeader();<br>            CarMotionData = new CarMotionData[numCars];<br>        }<br>    }<br>}</pre><p>The rest of the code is responsible for setting up a service that listens for incoming UDP packets, processes telemetry data, and then sends that data to a InfluxDB endpoint for further handling or visualization. Here’s a breakdown:</p><ol><li><strong>UDP Listener</strong>: The program listens for incoming UDP packets on a specified port (default F1 telemetry port 20777). It continuously listens for data and, upon receiving a packet, processes it based on the packet’s size</li><li><strong>Packet Processing</strong>: Based on the size of the received packet, the data is either identified as motion data or telemetry data, then deserialized from it’s binary format to a structure type</li><li><strong>Health Check HTTP Listener</strong>: The program starts an HTTP server on port 8080, which listens for incoming health check requests. This is useful during deployment as we want to monitor the service health from the load balancer</li></ol><ul><li><strong>Sending Motion and Telemetry Data</strong>: When motion data or car telemetry is available, it is retrieved for the player’s car, creates a data point containing key attributes and sends it to the InfluxDB endpoint using InfluxDBClient</li><li><strong>Error Handling</strong>: The code checks for invalid or missing data and handles cases where the player’s car index is out of bounds, logging appropriate messages</li></ul><h4>Infrastructure</h4><p>As much as I love the way the AWS Console is laid out, I always forget to remove resources and end up with $$$ at the end of the month! To avoid these surprises, i will provision infrastructure using Terraform Infrastructure as Code (IaC), allowing for a “one-click” setup and teardown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4xE4vdAzf40a7JpWvaujg.png" /></figure><pre>TERRAFORM-F1-TELEMETRY-INFRA/<br>├── .gitignore<br>├── backend.tf<br>├── data.tf<br>├── ecs-cluster.tf<br>├── ecs-service.tf<br>├── ecs-task-definition.tf<br>├── iam.tf<br>├── locals.tf<br>├── main.tf<br>├── network.tf<br>├── nlb.tf<br>├── outputs.tf<br>├── provider.tf<br>├── route53.tf<br>├── terraform.tfvars<br>├── variables.tf<br>└── vpc.tf</pre><ul><li><strong>backend.tf</strong>: Defines the Terraform backend, where the state file is stored (e.g., S3, local, etc.).</li><li><strong>data.tf</strong>: Contains data sources used in the project to grant read-only information from existing resources.</li><li><strong>ecs-cluster.tf</strong>: Manages the configuration of the ECS cluster where our Fargate instances will run</li><li><strong>ecs-service.tf</strong>: Defines ECS services that run on the cluster based on the task definition</li><li><strong>ecs-task-definition.tf</strong>: Defines the ECS task definitions, which contain information about container configurations, and resource limits, compute and memory allocation, health checks…</li><li><strong>iam.tf</strong>: Configures AWS IAM resources such as roles, policies, or permissions required for the ECS tasks or other services.</li><li><strong>locals.tf</strong>: Declares local variables used to store reusable values.</li><li><strong>main.tf</strong>: Left empty</li><li><strong>network.tf</strong>: Configures the network components, such as subnets, route tables, and security groups.</li><li><strong>nlb.tf</strong>: Configures a Network Load Balancer (NLB), which distributes incoming traffic across multiple targets.</li><li><strong>outputs.tf</strong>: Defines output values, which are often used to display essential information or pass data between modules or external systems.</li><li><strong>provider.tf</strong>: Specifies the provider (in this case, likely AWS) and its configuration, such as region or authentication details.</li><li><strong>route53.tf</strong>: Configures Route 53 DNS records for mapping <a href="http://app.f1telemetry.online/">app.f1telemetry.online</a> to the load balancer via an A alias record</li><li><strong>terraform.tfvars</strong>: Contains variable values</li><li><strong>variables.tf</strong>: Declares input variables used throughout the project for parameterizing configurations.</li><li><strong>vpc.tf</strong>: Configures the VPC (Virtual Private Cloud) and its associated networking components including IGW, NAT, subnets, route tables and security groups</li></ul><h3>Deployment</h3><p>Applying our IaC scripts, we can see that the NAT and NLB are what takes the most, which is the reason why the service has a dependency on these two resources. Only once they are online that we start deploying our Fargate instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRDoi-bognl9gHPEKdISoQ.jpeg" /><figcaption>Order and duration of resource provisioning</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMNCWLmxdgBaeZFIyfxeMg.png" /><figcaption>VPC Resource Map</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crlB_97pSv_S1VtLspyKBA.png" /><figcaption>NLB Resource Map</figcaption></figure><h3>Demo</h3><p>After deploying the infrastructure, I captured a brief gameplay session. Here is the recorded race synchronized with the Grafana dashboard displaying live telemetry data including metrics such as speed, engine RPM and temperature, gear and steering, brakes and tires inner/outer temperature, as well as G-force and car position</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNqChBsXhM9A&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNqChBsXhM9A&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b76dd36170144e4c8a32479b9b7ce6fa/href">https://medium.com/media/b76dd36170144e4c8a32479b9b7ce6fa/href</a></iframe><h3>Considerations</h3><ul><li>It takes a while to spin up InfluxDB and be fully ready to accept connections, which is why it is important to implement health checks and define container startup order via <a href="https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ContainerDependency.html">Container Dependency</a>. Setting the condition as “HEALTHY” rather than “START/COMPLETE/SUCCESS” for the UDP listener service and Grafana to wait for InfluxDB is what i found the most reliable</li><li>The UPD listener service implements an HTTP health check, but since i am using <a href="https://github.com/dotnet/dotnet-docker/blob/main/documentation/ubuntu-chiseled.md">Ubuntu Chiseled + .NET</a> which is a rootless image with unnecessary dependencies stripped down, i configured the health check at the load balancer level instead of the ECS task definition</li><li>ECS requires certain conditions to be able to pull image from either ECR or public registries. If you are receiving a ResourceInitializationError, make sure that tasks are launched into a public subnet, with a public IP address, so that they can communicate to ECR and other backing services using an internet gateway, OR launch tasks in a private subnet that has a VPC routing table configured to route outbound traffic via a NAT gateway in a public subnet, OR launch tasks in a private subnet and make sure you have AWS PrivateLink endpoints configured in your VPC, for the services you need (ECR for image pull authentication, S3 for image layers, and AWS Secrets Manager for secrets).</li><li>Latency is important especially when it comes to sub 1 second refresh on Grafana, which is why i am deploying the infrastructure on the me-central-1 region</li></ul><h3>Links</h3><ul><li>Terraform git repo: <a href="https://github.com/majdi-d/terraform-f1-telemetry-infra">https://github.com/majdi-d/terraform-f1-telemetry-infra</a></li><li>UPD specifications for EA F1 24: <a href="https://answers.ea.com/t5/General-Discussion/F1-24-UDP-Specification/m-p/13745520?attachment-id=822217">https://answers.ea.com/t5/General-Discussion/F1-24-UDP-Specification/m-p/13745520?attachment-id=822217</a></li><li>Grafana container pre-provisioning: <a href="https://grafana.com/docs/grafana/latest/administration/provisioning/">https://grafana.com/docs/grafana/latest/administration/provisioning/</a></li><li>Getting started with InfluxDB and Grafana: <a href="https://grafana.com/docs/grafana/latest/getting-started/get-started-grafana-influxdb/">https://grafana.com/docs/grafana/latest/getting-started/get-started-grafana-influxdb/</a></li><li>AWS Sports and F1: <a href="https://aws.amazon.com/sports/f1/">https://aws.amazon.com/sports/f1/</a></li></ul><p>Thank you for reading and if you find this article insightful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Disclaimer</h3><ul><li>F1® 2024 Game is an official product of the FIA FORMULA ONE WORLD CHAMPIONSHIP. © 2024 Electronic Arts Inc. EA, EA SPORTS, the EA SPORTS logo are trademarks of Electronic Arts Inc</li><li>PlayStation, PS5 and PS5 Logo are registered trademarks or trademarks of Sony Interactive Entertainment Inc.</li><li>SONY is a registered trademark or a trademark of Sony Group Corporation.</li><li>Other product names, service names, logos and/or company names used in this website are trademarked and copyrighted properties of their respective owners and/or licensors.</li><li>This content is not endorsed or affiliated with EA or SONY</li></ul><p>All pictures, illustrations and diagrams featured in this work are credited to the author, in alignment with their creative efforts and contributions to this content. Any resemblance to other works is purely coincidental. The author holds the rights to these visual elements, ensuring the authenticity and originality of their work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea5a774fce9d" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/f1-telemetry-with-aws-and-a-ps5-ea5a774fce9d">F1 Telemetry with AWS (and a PS5)</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Vulnerability Reporting with Amazon EventBridge, Lambda, Glue and DynamoDB]]></title>
            <link>https://towardsaws.com/automate-vulnerability-reporting-with-amazon-eventbridge-lambda-glue-and-dynamodb-d162dfa6696b?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/d162dfa6696b</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 15:39:53 GMT</pubDate>
            <atom:updated>2024-10-17T07:42:35.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbcfvrXKOnLvoIyyQGeXKQ.png" /><figcaption>Image generated with QuickSight</figcaption></figure><p>Over a decade ago, I asked a colleague who was a graphic designer to whip up something like the image you see above for one of our product’s websites. I distinctly remember it was going to take him <em>quite some time </em>to draft that masterpiece in Photoshop. Fast forward to today — this was generated in a couple of minutes using ChatGPT and AWS QuickSight! But hey, this isn’t a post about GenAI images (though if that piques your interest, you can check out my previous article <a href="https://medium.com/towards-aws/generative-ai-with-amazon-bedrock-rabbitmq-and-net-8-ba8e3913f959"><em>Generative AI with Amazon Bedrock, RabbitMQ, and .NET 8</em></a>). Now, let’s dive into the real topic!</p><p>This article delves into the design and implementation of a serverless solution that automates the reporting of vulnerabilities in container images. We will be mainly utilizing Amazon Inspector to scan ECR images, where we can identify <strong>Common Vulnerabilities and Exposures (CVEs)</strong>.</p><p>These findings are then transferred to DynamoDB through the event-driven capabilities of AWS such as EventBridge and Lambda. Finally, we will explore how Amazon QuickSight can be employed to analyze and visualize this data.</p><h3>Solution Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTV2UiXFI180waWbI2i1gw.png" /></figure><p>We will be creating a pipeline that automatically scans Docker images pushed to an ECR repository for vulnerabilities. The architecture leverages several AWS services, including:</p><ul><li><strong>Amazon ECR (Elastic Container Registry)</strong>: This is the starting point where container images are stored. ECR is scanned for vulnerabilities by Amazon Inspector 2, which integrates with ECR to continuously scan images as they are pushed.</li><li><strong>AWS Inspector 2</strong>: Inspector 2 performs vulnerability scans of the container images stored in ECR. It scans each image to identify potential Common Vulnerabilities and Exposures (CVEs) or security flaws. Inspector 2 findings are published as events.</li><li><strong>EventBridge</strong>: used to route events (in this case, Inspector 2 findings) to different AWS services. It captures the <strong>Inspector 2 findings</strong> and based on pre-configured rules, triggers various downstream workflows such as invoking Lambda functions.</li><li><strong>AWS Lambda</strong>: triggered by EventBridge in response to findings generated by Inspector 2. Lambda functions are responsible for processing the findings, transforming them into a format suitable for storage or further analysis, and storing them in a <strong>DynamoDB</strong> table or S3.</li><li><strong>Amazon DynamoDB</strong>: stores vulnerability scan results in a structured format for quick retrieval, enabling faster queries and processing. This could serve as a central repository for managing and tracking the scan history.</li><li><strong>Amazon S3 (Simple Storage Service)</strong>: The raw data, including Inspector findings and vulnerability scans, is exported and stored in S3 for long-term archival. Transformed versions of the raw findings are stored here after they are processed by AWS Glue.</li><li><strong>Glue DataBrew</strong>: used to clean, normalize, and prepare data for visualization or analysis. It can transform raw vulnerability scan results to make them more consumable by BI tools or external systems.</li><li><strong>Amazon QuickSight</strong>: used to visualize the data we previously transformed and stored back into S3.</li></ul><p>We will be automating the provisioning process using Terraform</p><h3>Pre-requisites</h3><ul><li>AWS Account</li><li>AWS CLI</li><li>Terraform</li><li>Visual Studio Code (or your favorite Editor)</li><li>GitHub account (optional)</li></ul><h3>Step-by-Step Implementation</h3><h4>Project Structure</h4><p>I chose to structure the terraform project as follows:</p><pre>/project-directory<br>│<br>├── py/<br>│   └── lambda_code.py # Python script for the AWS Lambda function<br>│<br>├── backend.tf # Defines the Terraform backend for storing state<br>├── data.tf # Manages data-related resources in the project<br>├── eventbridge.tf # AWS EventBridge configuration<br>├── iam.tf # IAM roles, policies, and permissions<br>├── lambda.tf # AWS Lambda function configuration and deployment<br>├── main.tf # Core Terraform configuration file <br>├── planfile.tfplan # Generated Terraform plan (output from `terraform plan`)<br>├── provider.tf # AWS provider configuration (credentials, region, etc.)<br>├── serverless.tf # Manages serverless resources<br>├── terraform.tfvars # Input variable values for the Terraform configuration<br>└── variables.tf # Declaring variables used throughout the project</pre><p>Here’s how to set up the entire infrastructure using Terraform:</p><h4>Step 1: Define Terraform Configuration</h4><p>First, we create a provider.tf file where we define the required providers, the AWS region, and the AWS account ID as variables.</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source = &quot;hashicorp/aws&quot;<br>      version = &quot;5.70.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = var.region<br>}<br><br>variable &quot;region&quot; {<br>  description = &quot;The AWS region where the resources will be created.&quot;<br>  type        = string<br>  default     = &quot;us-east-1&quot;<br>}<br><br>variable &quot;account_id&quot; {<br>  description = &quot;The AWS account ID where the resources will be created.&quot;<br>  type        = string<br>}</pre><h4>Step 2: Create ECR Repository and Scanning Configuration</h4><p>Next, we configure the ECR repository and set up the scanning rules. We will chose to run enhanced scans to make sure the data we are interested in is included in the finding events</p><pre>resource &quot;aws_ecr_registry_scanning_configuration&quot; &quot;configuration&quot; {<br>  scan_type = &quot;ENHANCED&quot;<br><br>  rule {<br>    scan_frequency = &quot;SCAN_ON_PUSH&quot;<br>    repository_filter {<br>      filter      = &quot;my-api-repo&quot;<br>      filter_type = &quot;WILDCARD&quot;<br>    }<br>  }<br>}<br><br>resource &quot;aws_ecr_repository&quot; &quot;my-api-repo&quot; {<br>  name                 = &quot;my-api-repo&quot;<br>  image_tag_mutability = &quot;MUTABLE&quot;<br>  force_delete         = true<br><br>  image_scanning_configuration {<br>    scan_on_push = true<br>  }<br><br>  encryption_configuration {<br>    encryption_type = &quot;AES256&quot;<br>  }<br>}<br><br>output &quot;ecr_repo_url&quot; {<br>  value = aws_ecr_repository.my-api-repo.repository_url<br>}</pre><h4>Step 3: Create DynamoDB Table</h4><p>We then create a DynamoDB table to store vulnerability findings. Every finding is defined by it’s ARN, which will be the table’s partition key</p><pre>resource &quot;aws_dynamodb_table&quot; &quot;ecr_vulnerabilities_table&quot; {<br>  name         = &quot;ECRVulnerabilities&quot;<br>  billing_mode = &quot;PAY_PER_REQUEST&quot;<br><br>  attribute {<br>    name = &quot;findingArn&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  hash_key = &quot;findingArn&quot;<br>}<br><br>output &quot;dynamodb_table_name&quot; {<br>  value = aws_dynamodb_table.ecr_vulnerabilities_table.name<br>}</pre><h4>Step 4: Set Up Lambda Function and EventBridge</h4><p>The next step is to set up the Lambda function that will process the events from EventBridge.</p><pre>resource &quot;aws_lambda_function&quot; &quot;process_ecr_scan&quot; {<br>  function_name = &quot;ProcessECRScan&quot;<br>  handler       = &quot;lambda_code.handler&quot;<br>  runtime       = &quot;python3.8&quot;<br><br>  environment {<br>    variables = {<br>      DYNAMODB_TABLE = aws_dynamodb_table.ecr_vulnerabilities_table.name<br>    }<br>  }<br><br>  role = aws_iam_role.lambda_exec.arn<br>}<br><br>resource &quot;aws_cloudwatch_event_rule&quot; &quot;inspector_rule&quot; {<br>  name        = &quot;inspector_rule&quot;<br>  description = &quot;EventBridge Rule for Inspector findings&quot;<br>  event_pattern = jsonencode({<br>    source      = [&quot;aws.inspector2&quot;],<br>    &quot;detail-type&quot; = [&quot;Inspector2 Finding&quot;]<br>  })<br>}<br><br>resource &quot;aws_cloudwatch_event_target&quot; &quot;inspector_lambda_target&quot; {<br>  rule      = aws_cloudwatch_event_rule.inspector_rule.name<br>  target_id = &quot;LambdaTarget&quot;<br>  arn       = aws_lambda_function.process_ecr_scan.arn<br>}<br><br>resource &quot;aws_lambda_permission&quot; &quot;allow_eventbridge&quot; {<br>  statement_id  = &quot;AllowExecutionFromEventBridge&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.process_ecr_scan.function_name<br>  principal     = &quot;events.amazonaws.com&quot;<br>}</pre><h4>Step 5: IAM</h4><p>Some IAM permissions are definitely required to have all the services communicate properly:</p><ul><li><strong>IAM Role for Lambda Execution:</strong> defines an IAM role named lambda_exec_role that grants AWS Lambda permission to assume this role. The AssumeRole action allows the Lambda service (lambda.amazonaws.com) to take on the permissions assigned to the role</li><li><strong>Attach AWS-Managed Policy for Lambda Execution</strong>: This attaches an AWS-managed policy (AWSLambdaBasicExecutionRole) to the Lambda execution role. This policy grants Lambda permissions to write logs to CloudWatch, which is essential for Lambda&#39;s basic execution and logging.</li><li><strong>Custom Policy for DynamoDB Access</strong>: This creates a custom policy that grants the Lambda function permission to perform specific actions (PutItem, GetItem, and Scan) on a DynamoDB table called ECRVulnerabilities. The Allow effect ensures the Lambda function can interact with this table.</li><li><strong>Attach Custom Policy to Lambda Role</strong>: This attaches the custom policy to the Lambda execution role. This step links the policy, which allows access to the DynamoDB table, to the role that Lambda assumes during execution.</li></ul><pre>resource &quot;aws_iam_role&quot; &quot;lambda_exec&quot; {<br>  name = &quot;lambda_exec_role&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Action    = &quot;sts:AssumeRole&quot;<br>      Effect    = &quot;Allow&quot;<br>      Principal = {<br>        Service = &quot;lambda.amazonaws.com&quot;<br>      }<br>    }]<br>  })<br>}<br><br># Attach AWS-managed policy to allow Lambda basic execution and logging<br>resource &quot;aws_iam_policy_attachment&quot; &quot;lambda_basic_execution&quot; {<br>  name       = &quot;lambda-basic-execution-attach&quot;<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole&quot;<br>  roles      = [aws_iam_role.lambda_exec.name]<br>}<br><br># Create a custom policy to allow specific DynamoDB actions<br>resource &quot;aws_iam_policy&quot; &quot;lambda_dynamodb_custom_policy&quot; {<br>  name        = &quot;LambdaDynamoDBCustomPolicy&quot;<br>  description = &quot;Custom policy for Lambda to access specific DynamoDB table&quot;<br><br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Effect = &quot;Allow&quot;<br>      Action = [<br>        &quot;dynamodb:PutItem&quot;,<br>        &quot;dynamodb:GetItem&quot;,<br>        &quot;dynamodb:Scan&quot;<br>      ]<br>      Resource = &quot;arn:aws:dynamodb:${var.region}:${var.account_id}:table/ECRVulnerabilities&quot;<br>    }]<br>  })<br>}<br><br># Attach the custom policy to the Lambda role<br>resource &quot;aws_iam_policy_attachment&quot; &quot;lambda_dynamodb_custom&quot; {<br>  name       = &quot;lambda-dynamodb-custom-attach&quot;<br>  roles      = [aws_iam_role.lambda_exec.name]<br>  policy_arn = aws_iam_policy.lambda_dynamodb_custom_policy.arn<br>}</pre><h4>Step 6: Lambda Code</h4><p>The Lambda function is designed to process <strong>AWS Inspector findings</strong> and store them in a DynamoDB table. The function extracts key information from an event, including account details, region, finding details, severity, vulnerable packages, and resource information</p><pre>import json<br>import boto3<br>import os<br>from decimal import Decimal, ROUND_DOWN  # Import Decimal and ROUND_DOWN<br><br># Initialize a DynamoDB resource<br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>table_name = os.environ[&#39;DYNAMODB_TABLE&#39;]  # Get the DynamoDB table name from the environment variable<br>table = dynamodb.Table(table_name)<br><br>def convert_to_decimal(value):<br>    &quot;&quot;&quot;Convert a value to Decimal with controlled precision.&quot;&quot;&quot;<br>    try:<br>        # Convert to Decimal and round it down to 2 decimal places<br>        return Decimal(value).quantize(Decimal(&#39;0.00&#39;), rounding=ROUND_DOWN)<br>    except (ValueError, InvalidOperation) as e:<br>        print(f&quot;Error converting to Decimal: {e}&quot;)<br>        return Decimal(0)  # Return 0 or handle the error as needed<br><br>def handler(event, context):<br>    # Log the incoming event for debugging purposes<br>    print(&quot;Received event:&quot;, json.dumps(event, indent=2))<br><br>    # Extract general event information<br>    aws_account_id = event.get(&#39;account&#39;, &#39;Unknown&#39;)<br>    region = event.get(&#39;region&#39;, &#39;Unknown&#39;)<br>    event_time = event.get(&#39;time&#39;, &#39;Unknown&#39;)<br>    <br>    # Extract the detail section of the event, which contains the Inspector finding<br>    detail = event.get(&#39;detail&#39;, {})<br>    <br>    # Extract essential details from the Inspector finding<br>    finding_arn = detail.get(&#39;findingArn&#39;, &#39;Unknown&#39;)<br>    finding_title = detail.get(&#39;title&#39;, &#39;No title provided&#39;)<br>    severity = detail.get(&#39;severity&#39;, &#39;Unknown&#39;)<br>    description = detail.get(&#39;description&#39;, &#39;No description available&#39;)<br>    status = detail.get(&#39;status&#39;, &#39;Unknown&#39;)<br>    type_of_finding = detail.get(&#39;type&#39;, &#39;Unknown&#39;)<br>    <br>    # Extract additional details (e.g., exploit, remediation, package vulnerability details)<br>    exploit_available = detail.get(&#39;exploitAvailable&#39;, &#39;Unknown&#39;)<br>    fix_available = detail.get(&#39;fixAvailable&#39;, &#39;Unknown&#39;)<br>    <br>    # Convert inspector_score using the new function<br>    inspector_score = convert_to_decimal(detail.get(&#39;inspectorScore&#39;, 0))<br><br>    # Extract vulnerable packages<br>    vulnerable_packages = []<br>    if &#39;packageVulnerabilityDetails&#39; in detail and &#39;vulnerablePackages&#39; in detail[&#39;packageVulnerabilityDetails&#39;]:<br>        for package in detail[&#39;packageVulnerabilityDetails&#39;][&#39;vulnerablePackages&#39;]:<br>            vulnerable_packages.append({<br>                &#39;name&#39;: package.get(&#39;name&#39;, &#39;Unknown&#39;),<br>                &#39;version&#39;: package.get(&#39;version&#39;, &#39;Unknown&#39;),<br>                &#39;packageManager&#39;: package.get(&#39;packageManager&#39;, &#39;Unknown&#39;),<br>                &#39;fixedInVersion&#39;: package.get(&#39;fixedInVersion&#39;, &#39;Unknown&#39;),<br>                &#39;sourceLayerHash&#39;: package.get(&#39;sourceLayerHash&#39;, &#39;Unknown&#39;),<br>                &#39;remediation&#39;: package.get(&#39;remediation&#39;, &#39;Unknown&#39;)<br>            })<br><br>    # Extract resource details (ECR information)<br>    resources = []<br>    if &#39;resources&#39; in detail:<br>        for resource in detail[&#39;resources&#39;]:<br>            resources.append({<br>                &#39;id&#39;: resource.get(&#39;id&#39;, &#39;Unknown&#39;),<br>                &#39;type&#39;: resource.get(&#39;type&#39;, &#39;Unknown&#39;),<br>                &#39;region&#39;: resource.get(&#39;region&#39;, &#39;Unknown&#39;),<br>                &#39;details&#39;: resource.get(&#39;details&#39;, {})<br>            })<br><br>    # Prepare the item to be stored in DynamoDB<br>    item = {<br>        &#39;findingArn&#39;: finding_arn,<br>        &#39;findingTitle&#39;: finding_title,<br>        &#39;severity&#39;: severity,<br>        &#39;description&#39;: description,<br>        &#39;status&#39;: status,<br>        &#39;type&#39;: type_of_finding,<br>        &#39;exploitAvailable&#39;: exploit_available,<br>        &#39;fixAvailable&#39;: fix_available,<br>        &#39;inspectorScore&#39;: inspector_score,<br>        &#39;vulnerablePackages&#39;: vulnerable_packages,<br>        &#39;resources&#39;: resources,<br>        &#39;awsAccountId&#39;: aws_account_id,<br>        &#39;region&#39;: region,<br>        &#39;eventTime&#39;: event_time<br>    }<br><br>    # Try to save the item to DynamoDB<br>    try:<br>        table.put_item(Item=item)<br>        print(f&quot;Successfully added item to DynamoDB: {item}&quot;)<br>    except Exception as e:<br>        print(f&quot;Error saving item to DynamoDB: {e}&quot;)<br><br>    # Return a success response<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(&#39;Inspector findings processed and saved successfully.&#39;)<br>    }</pre><h4>Step 7: Terraform Output</h4><pre>output &quot;ecr_repo_url&quot; {<br>  value = aws_ecr_repository.my-api-repo.repository_url<br>  description = &quot;The URL of the newly created ECR repository.&quot;<br>}<br><br># Output the DynamoDB table name<br>output &quot;dynamodb_table_name&quot; {<br>  value = aws_dynamodb_table.ecr_vulnerabilities_table.name<br>  description = &quot;The name of the DynamoDB table used for storing ECR vulnerabilities.&quot;<br>}<br><br># Output the Docker push commands<br>output &quot;docker_push_commands&quot; {<br>  value = [<br>    &quot;aws ecr get-login-password --region ${var.region} | docker login --username AWS --password-stdin ${aws_ecr_repository.my-api-repo.repository_url}&quot;,<br>    &quot;docker tag &lt;local-image-name&gt;:&lt;tag&gt; ${aws_ecr_repository.my-api-repo.repository_url}:&lt;tag&gt;&quot;,<br>    &quot;docker push ${aws_ecr_repository.my-api-repo.repository_url}:&lt;tag&gt;&quot;<br>  ]<br>  description = &quot;Commands to authenticate and push Docker images to the ECR repository.&quot;<br>}</pre><h3>Deploy Infrastructure</h3><p><strong>Install Terraform</strong>:</p><ul><li>Download and install Terraform from the <a href="https://developer.hashicorp.com/terraform/install">official website</a>.</li><li>Verify the installation by running terraform -version in your terminal.</li></ul><p><strong>Install AWS CLI</strong>:</p><ul><li>Install the AWS Command Line Interface (CLI) from the <a href="https://aws.amazon.com/cli/">AWS CLI installation guide</a>.</li><li>Verify the installation by running aws --version.</li></ul><p><strong>Configure AWS Credentials</strong>:</p><ul><li>Run aws configure to set up your AWS access key, secret key, region, and output format. This will create the necessary credentials file in ~/.aws/credentials.</li></ul><p><strong>Run Terraform Init</strong>:</p><ul><li>Execute the command terraform init in your project directory. This initializes the directory and downloads the required provider plugins.</li></ul><p>Finally, execute terraform plan to create an execution plan and terraform apply to apply the changes required to reach the desired state</p><h3>Testing with Docker Images</h3><p>We will now push some standard docker images to ECR, i chose deliberately older versions to generate more insights during scans</p><p>It’s important to highlight that basic scans generate a different set of results compared to enhanced scans. If you only wish to generate a summary, you can switch to basic scanning in the Terraform code but make sure you are aware of the events payload structure. More information available at <a href="https://docs.aws.amazon.com/inspector/latest/user/eventbridge-integration.html">https://docs.aws.amazon.com/inspector/latest/user/eventbridge-integration.html</a></p><p>Let’s authenticate the Docker client to Amazon Elastic Container Registry (ECR) repository by running the command aws ecr get-login-password --region &lt;your-region&gt; | docker login --username AWS--password-stdin &lt;account-id&gt;.dkr.ecr.&lt;your-region&gt;.amazonaws.com</p><p>Here are some image examples known to have several vulnerabilities you can use:</p><ul><li><strong>Image Name:</strong> ubuntu:22.04</li><li><strong>Docker Pull Command:</strong> docker pull ubuntu:22.04</li><li><strong>Docker Tag Command:</strong> docker tag ubuntu:22.04 1234567890.dkr.ecr.&lt;region&gt;.amazonaws.com/&lt;repository&gt;:ubuntu-22.04</li><li><strong>Docker Push Command:</strong> docker push 1234567890.dkr.ecr.&lt;region&gt;.amazonaws.com/&lt;repository&gt;:ubuntu-22.04</li><li>golang:1.20</li><li>postgres:15.2</li><li>nginx:1.23.5</li><li>busybox:1.35.0</li><li>rabbitmq:3.11.18-management</li><li>elasticsearch:8.10.0</li><li>mongo:6.0.5</li><li>traefik:v2.10</li><li>mcr.microsoft.com/dotnet/sdk:6.0.104</li></ul><p>After pushing an image, a scan will run automatically, and we will be able to view activity on both EventBridge and Lambda, as illustrated in this dashboard. The metrics displayed cover key Lambda performance indicators, including Invocations, which show the number of times the Lambda function was triggered, and Duration, representing the execution time for each invocation. Additionally, Error count and success rate (%) tracks the success rate and any errors encountered. Metrics such as Throttles and Total concurrent executions help monitor system limitations, while Async event age, Async events received, and Async events dropped provide insight into the handling of asynchronous events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQCeoB51v5NrgFOwRFS7Eg.png" /><figcaption>EventBridge Monitoring</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPN5FMwrZUe3S37gPUHQKw.png" /><figcaption>Lambda Executions</figcaption></figure><p>And in case there are any errors, we can check the logs on CloudWatch to identify potential issues, which also provides insights on performance monitoring for both EventBridge and Lambda executions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izKopGuMYfs3sju7_70yOg.png" /><figcaption>CloudWatch performance monitoring</figcaption></figure><p>Once complete, we will see data persisted in DynamoDB, as shown in this table. It displays a detailed list of vulnerability findings from AWS Inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZwMEvjHzj-L1PrJ_gVv3w.png" /><figcaption>DynamoDB Table</figcaption></figure><p>Each item includes attributes such as the findingArn (Amazon Resource Name), a description of the vulnerability, the eventTime when the finding was detected, and its corresponding findingTitle, which references specific CVEs (Common Vulnerabilities and Exposures) in addition to columns such as exploitAvailable, fixAvailable, and inspectorScore that help categorize the risk level, with associated severity ratings ranging from &quot;UNTRIAGED&quot; to &quot;HIGH.&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ISTcgp-OXhf8dAAZqecgKA.png" /></figure><h3>Data Transform</h3><p>The process for transforming and visualizing data, particularly when working with Amazon DynamoDB and QuickSight, requires consideration due to <em>certain limitations</em>.</p><p>QuickSight does not directly support DynamoDB as a data source, nor does it handle nested JSON structures efficiently. As a result, after exporting DynamoDB table data to S3 in JSON format, the first step is to set up a DataBrew project. This project uses the raw extracted JSON as its data source and includes a recipe tailored to discard unnecessary columns and un-nest fields.</p><p>After exporting the raw data into S3, we will build a <strong>DataBrew recipe </strong>first with several actions to perform on sample data, and then run a <strong>job </strong>against raw data as an input and send the output to a separate S3 bucket.</p><blockquote>DynamoDB export to S3 is straightforward and you can read more about it here <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/S3DataExport_Requesting.html">Requesting a table export in DynamoDB</a></blockquote><h4>DataBrew Recipe</h4><p>This recipe is designed to <strong>cleanse and prepare the dataset</strong> for further analysis by:</p><ul><li><strong>Unnesting complex nested data</strong> (e.g., lists, structs) from vulnerability reports or findings</li><li><strong>Removing unnecessary fields</strong> to focus on critical information</li></ul><p>This workflow will produce a <strong>flattened, cleaned dataset</strong> that is ready for further transformations, storage, or visualization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wuIevPs88LHpv35eID6nw.png" /><figcaption>DataBrew Project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wi8SWVLs9xPS33JbRu1W4w.png" /><figcaption>DataBrew Recipe Actions</figcaption></figure><h4>DataBrew Job</h4><ol><li><strong>S3 Input</strong>: The source of the data is an Amazon S3 bucket, containing the raw data</li><li><strong>Dataset</strong>: The file from S3 is then converted into a DataBrew dataset named brand-new-project-dataset. This dataset serves as the input for further analysis.</li><li><strong>Recipe</strong>: The recipe associated with the project, contains 22 steps that define how the data should be cleaned, enriched, or transformed. Recipes in DataBrew allow us to specify transformations without modifying the source data.</li><li><strong>Job</strong>: A job is triggered, which executes the recipe and processes the data according to the transformations. Jobs are used to apply recipes at scale and output the results to specified destinations.</li><li><strong>S3 Output</strong>: After the job runs, the transformed data is saved back into S3 in CSV and JSON formats.</li></ol><blockquote>In Amazon QuickSight, the <strong>manifest.json</strong> file is required when importing data from Amazon S3 to provide instructions and metadata about the data files. It acts as a blueprint that QuickSight uses to understand how to interpret and load data. It will usually describe the data location (S3 paths), file format defition (CSV, JSON, Parquet) and schema configuration</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aWbc6wIXdAVEjEOEGXfVQ.png" /><figcaption>AWS Glue DataBrew Job</figcaption></figure><p>Once the recipe is applied, a DataBrew job is created to process the data according to the specified recipe. This job exports the flattened data back into S3, which can then be properly ingested into QuickSight for analysis and visualization.</p><h3>Data Visualization</h3><p>Here you go, now you are ready for that meeting where you can brag about how secure our systems are!</p><p>This dashboard is like the final boss of a video game after hours of battling serverless monsters like Lambda and EventBridge! It now proudly displays the vulnerable underbelly of our systems, with <strong>Linux</strong> being the star of the show.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIz6R7UpAb_XPRm7fiEMRQ.png" /></figure><h3>Conclusion</h3><p>By leveraging Amazon ECR, EventBridge, Lambda, and DynamoDB, we can create a robust solution for automating vulnerability reporting for Docker images. This setup enhances the security of our containerized applications and provides an efficient way to track and manage vulnerabilities.</p><p>This solution is just one way to automate and improve your DevOps security posture. With the flexibility of AWS services and Terraform, you can expand and adapt this architecture to fit your specific needs and ensure that your applications are not only functional but also secure and in compliance with standards.</p><h3>Additional Resources</h3><ul><li><a href="https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html">AWS ECR Documentation</a></li><li><a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/what-is-amazon-eventbridge.html">Amazon EventBridge Documentation</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/welcome.html">AWS Lambda Documentation</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">Terraform AWS Provider Documentation</a></li></ul><p>Thank you for reading and if you find this article insightful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Disclaimer</h3><p>All pictures, illustrations and diagrams featured in this work are credited to the author, in alignment with their creative efforts and contributions to this content. Any resemblance to other works is purely coincidental. The author holds the rights to these visual elements, ensuring the authenticity and originality of their work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d162dfa6696b" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/automate-vulnerability-reporting-with-amazon-eventbridge-lambda-glue-and-dynamodb-d162dfa6696b">Automate Vulnerability Reporting with Amazon EventBridge, Lambda, Glue and DynamoDB</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI with Amazon Bedrock, RabbitMQ and .NET 8]]></title>
            <link>https://towardsaws.com/generative-ai-with-amazon-bedrock-rabbitmq-and-net-8-ba8e3913f959?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba8e3913f959</guid>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 12:14:44 GMT</pubDate>
            <atom:updated>2024-04-24T04:28:05.567Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generative AI with Amazon Bedrock, RabbitMQ and .NET 8</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*W7v0X7Cp9I7XnyRK.jpg" /><figcaption>AI Image depicting a futuristic city generated by Amazon Titan G1 model</figcaption></figure><p>Are you interested in accessing a boundless collection of “Cat in spacesuit” images? Are you passionate about crafting production-ready applications capable of scaling far beyond mere requests per second? Does high availability, resilience, or microservices resonate with your professional ethos? If so, this article is tailor-made for you!</p><p>On a more serious note, this article explores the creation of a web-based solution designed to generate and display AI-generated images, leveraging AWS shiny brand new service, Bedrock.</p><p>However, I must caution you: this article contains a substantial amount of code. So, without further ado, let’s dive in!</p><h3>Introduction to AWS Bedrock</h3><p>Amazon Bedrock is a comprehensive managed service offering an array of high-performing foundation models (FMs) sourced from some of the leading AI entities.</p><p>As it is the case with most AWS services, it is available via CLI, SDK and API, which is what we will be using in this project to interact with the foundation model</p><p>As of the time of writing this article, there are 24 models available and specializing in text, embedding, image and vision from providers such as <em>AI21 Labs, Stability AI, Anthropic, Cohere, Meta, Mistral AI and Amazon</em></p><h3>Overview of the project</h3><p>Our microservices architecture comprises several distinct components, each serving a specific role in the system’s functionality. Communication is performed via a load balanced message broker based on a RabbitMQ cluster with three nodes for high availability</p><p>The reason why i wanted to use message based communication via a broker in this project is to compartmentalize each service based on a different domain and responsibility, and to have a good level of scalability when it comes to having a responsive REST endpoint that will return a response to the caller immediately</p><p>The REST service will publish a message in the queue, and leave the heavy lifting to be done by the consumer. If one of the nodes in the message broker goes down, another one will take over, and if the consumer system goes offline, it will still pick up the pending messages from the queue and process them at a later stage</p><p>Therefore, microservices communication is at it’s most basic and there will be no SAGA, Event Sourcing or other popular patterns used for transaction management</p><p>The generated images are eventually stored in an S3 bucket and will be available in the CloudFront CDN to be loaded from a web front-end built in ASP.NET Razor</p><h3>System Components</h3><h4>REST API Service</h4><ul><li>Serves as the primary interface for user interaction, providing REST endpoints for accessing system functionalities</li><li>Publishes messages to a message queue for asynchronous processing by other services</li></ul><h4>HAProxy Service</h4><ul><li>Acts as a load balancer for the RabbitMQ cluster, ensuring even distribution of incoming requests</li><li>Provides a unified endpoint for clients to interact with the RabbitMQ cluster, abstracting the complexity of accessing multiple nodes. We certainly don’t want to “rewrite the wheel” here and manage message broker connectivity via server code!</li></ul><h4>RabbitMQ Cluster</h4><ul><li>Consists of three RabbitMQ nodes operating as a cluster to ensure high availability, fault tolerance, and scalability for message queuing operations</li></ul><h4>Queue Listener Service</h4><ul><li>Responsible for consuming messages from the RabbitMQ queue, processing them, and executing various tasks such as calling external APIs for image generation, persisting to database or pushing results to S3</li></ul><h4>MongoDB Service</h4><ul><li>Stores metadata related to successful requests made to external APIs, providing data persistence for the system</li></ul><h4>Web Frontend Service</h4><ul><li>Built using ASP.Net Razor Pages, serves as the user interface for viewing generated images, loading from CloudFront CDN (i don&#39;t like to open up S3 buckets for public access)</li></ul><h4><strong>Application Performance Monitoring</strong></h4><p>Any microservices deployment is incomplete without proper visibility on resource and metrics monitoring. The combination of Prometheus and Grafana provides the necessary framework libraries and components to ingest runtime metrics and display them on dashboards and we will be using those for this project</p><h4>Docker Containers and Orchestration</h4><p>Each service operates within its individual Docker container, ensuring encapsulation, portability, and scalability. Dockerization facilitates deployment and management of services across different environments. The system is orchestrated using Docker Compose, defining service dependencies and configurations in a single YAML file</p><h3>Getting Started</h3><h4>Environment Setup</h4><p>For this project, we will need the following:</p><ul><li>An AWS account, you can signup for a free tier at <a href="https://aws.amazon.com/free/">https://aws.amazon.com/free/</a></li><li>Visual Studio (using 2022 for this particular project)</li><li>Docker Desktop (If you are using Windows as a dev machine)</li></ul><h4>Model Access</h4><p>Head to your AWS console and select Bedrock from the list of services, then you will be able to request access to individual models at <a href="https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess">https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess</a> (change to your favorite region)</p><p>Once your access has been granted, you will be able to perform requests to the model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIoNGA9ROU32-wnJifREsw.png" /><figcaption>Bedrock Model Access</figcaption></figure><h4>IAM Credentials</h4><p>In order to be able to perform calls to Bedrock using the .NET SDK, we will need to create the necessary identity and access. There are two AWS Managed policies that can be attached to the user account (this project uses <em>AmazonBedrockFullAccess</em>)</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;BedrockAll&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;bedrock:*&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;DescribeKey&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;kms:DescribeKey&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:*:kms:*:::*&quot;<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;APIsWithAllResourceAccess&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;iam:ListRoles&quot;,<br>                &quot;ec2:DescribeVpcs&quot;,<br>                &quot;ec2:DescribeSubnets&quot;,<br>                &quot;ec2:DescribeSecurityGroups&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;PassRoleToBedrock&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;iam:PassRole&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:iam::*:role/*AmazonBedrock*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;iam:PassedToService&quot;: [<br>                        &quot;bedrock.amazonaws.com&quot;<br>                    ]<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>After that, go to “Create access key” under the newly created user account to generate an Key/Secret pair that will be used to authenticate requests against the Bedrock API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDfknf978a7E2TUv0diE4A.png" /><figcaption>Generate key/secret pair</figcaption></figure><h4>Additional AWS Resources</h4><p>We need to create some additional resources. Let’s start by setting up an S3 bucket that will be used to store generated images, after having done that, head to CloudFront and create a new CDN distribution with the following parameters:</p><ul><li><em>Origin </em>will use the S3 bucket created earlier, with an <em>Origin access control settings with signing requests enabled</em></li><li><em>Behavior </em>with default parameters (HTTP/HTTPS viewer protocol, Allow GET,HEAD, disabled Restricted Viewer Access, Default Cache policies)</li></ul><p>Take note of the CloudFront distribution domain name (which looks like <em>randomstring.cloudfront.net</em>), we will use it later to persist generated assets URLs in a database to be loaded on a web based client</p><h4>Multi-Project Solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*F8DcK3Me1-s7KDPuuvPqTQ.png" /><figcaption>Multi-project VS Solution</figcaption></figure><p>The solution has a total of four project which i will describe below:</p><ul><li><strong>BedrockService</strong>: WebAPI project that exposes a single endpoint “InvokeModel” and is responsible for constructing a Bedrock Titan payload and pushing it into our message broker</li><li><strong>RMQSubService</strong>: Worker Service project that exposes no endpoints. It is responsible for consuming RabbitMQ messages and performing calls to Bedrock API. The service connects to the message broker and starts reading and acknowledging messages, then it will perform outbound HTTP requests to the Bedrock API, save the received data stream into an S3 bucket and finally insert the generated image and it’s Cloudfront URL into a MongoDB collection</li><li><strong>WebClient</strong>: ASP.Net Razor pages connecting to the same MongoDB collection and loading images into a web page</li><li><strong>docker-compose: </strong>This project is automatically generated when you add docker orchestration support to each one of the above projects (<a href="https://learn.microsoft.com/en-us/visualstudio/containers/tutorial-multicontainer?view=vs-2022">https://learn.microsoft.com/en-us/visualstudio/containers/tutorial-multicontainer?view=vs-2022</a>)</li></ul><p>In addition to the main <em>docker-compose.yml</em> file, there are additional files necessary to run the other containers:</p><p><strong>Load balancer configuration (<em>haproxy.cfg</em>)</strong></p><pre>global<br>    log stdout format raw local0<br><br>defaults<br>    log global<br>    mode http<br>    timeout connect 5000ms<br>    timeout client 50000ms<br>    timeout server 50000ms<br><br>listen haproxy-stats<br>        bind  *:9092<br>        mode  http<br>        stats enable<br>        stats show-legends<br>        stats show-node<br>        stats refresh 5s<br>        stats uri     /haproxy?stats<br>        stats realm   Haproxy\ Statistics<br>        stats auth    haproxy:haproxy<br> <br>listen rabbitmq-cluster<br>        bind *:9090<br>        mode            tcp<br>        balance         leastconn<br>        timeout client  50000ms<br>        timeout server  50000ms<br>        option          clitcpka<br>        server          rabbitmq1 rabbitmq1:5672  check inter 5s rise 2 fall 3<br>        server          rabbitmq2 rabbitmq2:5672  check inter 5s rise 2 fall 3<br>        server          rabbitmq3 rabbitmq3:5672  check inter 5s rise 2 fall 3<br><br>listen rmq-management<br>        bind *:9091<br>        mode            tcp<br>        balance         leastconn<br>        timeout client  50000ms<br>        timeout server  50000ms<br>        option          clitcpka<br>        server          rabbitmq1 rabbitmq1:15672  check inter 5s rise 2 fall 3<br>        server          rabbitmq2 rabbitmq2:15672  check inter 5s rise 2 fall 3<br>        server          rabbitmq3 rabbitmq3:15672  check inter 5s rise 2 fall 3</pre><ul><li><strong>log stdout format raw local0:</strong> Configures logging to send log messages to the standard output (stdout) in raw format, tagged with the local0 facility.</li><li><strong>log global:</strong> Directs log messages to be sent to the global log destination defined in the global section.</li><li><strong>mode http:</strong> Sets the mode to HTTP, indicating that HAProxy will operate as an HTTP proxy.</li><li><strong>timeout connect 5000ms:</strong> Specifies a timeout of 5000 milliseconds for establishing connections with backend servers.</li><li><strong>timeout client 50000ms:</strong> Sets a client timeout of 50000 milliseconds for client connections.</li><li><strong>timeout server 50000ms:</strong> Defines a server timeout of 50000 milliseconds for connections to backend servers.</li><li><strong>*<em>bind :9092</em></strong>: Binds the HAProxy instance to listen on all interfaces (*) on port 9092.</li><li><strong>stats enable:</strong> Enables statistics reporting.</li><li><strong>stats show-legends: </strong>Displays legends in statistics reports.</li><li><strong>stats show-node:</strong> Shows node information in statistics reports.</li><li><strong>stats refresh 5s:</strong> Sets the refresh interval for statistics reports to 5 seconds.</li><li><strong>stats uri /haproxy?stats:</strong> Specifies the URI path for accessing the statistics page.</li><li><strong>stats realm Haproxy\ Statistics:</strong> Defines the authentication realm for accessing statistics.</li><li><strong>stats auth haproxy:haproxy:</strong> Sets the username and password for accessing statistics.</li><li><strong>*<em>bind :9090</em>:</strong> Binds HAProxy to listen on all interfaces on port 9090 for TCP connections.</li><li><strong>balance leastconn:</strong> Employs the least connections load balancing algorithm.</li><li><strong>option clitcpka:</strong> Enables the “client-side” TCP keep-alive option.</li><li><strong>server rabbitmq1 rabbitmq1:5672 check inter 5s rise 2 fall 3:</strong> Defines backend server configurations for the <em>RabbitMQ cluster node 1</em>, including server name2, address, port, and health checks. We will do the same for the two remaining nodes for the queue service and the management page</li><li><strong>*<em>bind :9091</em>:</strong> Binds HAProxy to listen on all interfaces on port 9091 for TCP connections.</li><li><strong>balance leastconn:</strong> Utilizes the least connections load balancing algorithm.</li><li><strong>option clitcpka:</strong> Enables the “client-side” TCP keep-alive option.</li></ul><p><strong>RabbitMQ Cluster Initial Configuration (<em>rabbitmq.config</em>)</strong></p><p>While certain parameters in RabbitMQ can be adjusted through environment variables, the majority are set within a primary configuration file known as <em>rabbitmq.conf</em></p><p>This file includes settings for both the core server and its associated plugins. Additionally, an auxiliary configuration file may be utilized to adjust parameters that cannot be specified within the primary file’s format</p><p>For the purpose of this project, we will only require a basic cluster configuration following the Classic (Erlang terms) format. It defines a list of nodes called respectively rabbit1@rabbit1, rabbit2@rabbit2 and rabbit3@rabbit3</p><p>The remaining parameters related to the actual image will be set as part of docker-compose</p><p>For more information on clustering and configuration please have a look at <a href="https://www.rabbitmq.com/docs/clustering">RabbitMQ Clustering</a> and <a href="https://www.rabbitmq.com/docs/configure">Configuration Guide</a></p><pre>[ <br>  { rabbit, [ <br>    { loopback_users, [ ] }, <br>    { cluster_nodes, {[&#39;rabbit1@rabbit1&#39;,&#39;rabbit2@rabbit2&#39;,&#39;rabbit3@rabbit3&#39;], disc }} <br>  ]} <br>].</pre><h3>Container Orchestration</h3><p>Docker Compose is a tool used for defining and managing multi-container Docker applications. Typically in a microservices project, Docker Compose is used to simplify the process of orchestrating and coordinating multiple microservices by allowing developers to define the services, their configurations, and the relationships between them in a single YAML file.</p><p>If you are not yet familiar with docker-compose and it’s related Visual Studio integration, please have a look at this excellent <a href="https://learn.microsoft.com/en-us/visualstudio/containers/tutorial-multicontainer?view=vs-2022">Microsoft tutorial</a> for creating a multi-container app with Docker Compose</p><pre>version: &#39;3.4&#39;<br><br>services:<br>  bedrockservice:<br>    image: ${DOCKER_REGISTRY-}bedrockservice<br>    build:<br>      context: .<br>      dockerfile: BedrockService/Dockerfile<br>    ports:<br>     - 80:8080<br>     - 443:8081<br><br>  rabbitmq1:<br>    image: rabbitmq:3.13.1-management-alpine<br>    hostname: rabbit1<br>    volumes:<br>      - &quot;./rabbitmq.config:/etc/rabbitmq/rabbitmq.config&quot;<br>    environment:<br>      RABBITMQ_ERLANG_COOKIE: &quot;uniqueerlangcookie&quot;<br>      RABBITMQ_NODENAME: rabbit1<br>    networks:<br>      - rabbitmq_network<br><br>  rabbitmq2:<br>    image: rabbitmq:3.13.1-management-alpine<br>    hostname: rabbit2<br>    volumes:<br>      - &quot;./rabbitmq.config:/etc/rabbitmq/rabbitmq.config&quot;<br>    environment:<br>      RABBITMQ_ERLANG_COOKIE: &quot;uniqueerlangcookie&quot;<br>      RABBITMQ_NODENAME: rabbit2<br>    networks:<br>      - rabbitmq_network<br>    depends_on:<br>      - rabbitmq1<br>  <br>  rabbitmq3:<br>    image: rabbitmq:3.13.1-management-alpine<br>    hostname: rabbit3<br>    volumes:<br>      - &quot;./rabbitmq.config:/etc/rabbitmq/rabbitmq.config&quot;<br>    environment:<br>      RABBITMQ_ERLANG_COOKIE: &quot;uniqueerlangcookie&quot;<br>      RABBITMQ_NODENAME: rabbit3<br>    networks:<br>      - rabbitmq_network<br>    depends_on:<br>      - rabbitmq1<br><br>  haproxy:<br>    image: haproxy:latest<br>    hostname: haproxy<br>    ports:<br>      - 9091:9091<br>      - 9090:9090<br>      - 9092:9092<br>    volumes:<br>      - ./haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg<br>    networks:<br>      - rabbitmq_network<br>    depends_on:<br>      - rabbitmq1<br>      - rabbitmq2<br>      - rabbitmq3<br><br>  rmqsubservice:<br>    image: ${DOCKER_REGISTRY-}rmqsubservice<br>    build:<br>      context: .<br>      dockerfile: RMQSubService/Dockerfile<br>    env_file:<br>      - .env<br>    depends_on:<br>      - rabbitmq1<br>      - rabbitmq2<br>      - rabbitmq3<br>      - haproxy<br>  mongodb:<br>    image: mongo<br>    ports:<br>      - &quot;27017:27017&quot;<br>    volumes:<br>      - mongodb_data:/data/db<br>    networks:<br>      - rabbitmq_network<br><br>  webclient:<br>    image: ${DOCKER_REGISTRY-}webclient<br>    build:<br>      context: .<br>      dockerfile: WebClient/Dockerfile<br>    ports:<br>     - 81:8080<br>     - 444:8081<br>    env_file:<br>      - .env<br>volumes:<br>  mongodb_data:<br><br>networks:<br>  rabbitmq_network:<br>    driver: bridge</pre><p>We will use this docker-compose file to define a multi-service application environment for deploying and orchestrating various components:</p><p><strong>Bedrock Service: </strong>An image built from the local Dockerfile exposing ports 80 and 443 for HTTP and HTTPS traffic.</p><p><strong>RabbitMQ Cluster: </strong>Consists of three RabbitMQ instances for defining a cluster using the RabbitMQ 3.13.1 Management Alpine image<br><br><strong>HAProxy: </strong>Uses the latest HAProxy image and acts as a load balancer for the RabbitMQ cluster nodes. We expose ports 9091, 9090, and 9092 for HAProxy statistics and routing, and mounts a local <em>haproxy.cfg</em> file for configuration (see configuration file below)</p><p><strong>RMQSubService: </strong>An image built from the local Docker file and loads environment variables from a <em>.env file</em></p><p><strong>MongoDB: </strong>Uses the latest MongoDB image and exposes port 27017 for MongoDB connections. Storage is persistent via the <em>mongodb_data</em> volume mounted during creation<br><br><strong>Web Client: </strong>An image built from the local Dockerfile exposing ports 81 and 444 for HTTP and HTTPS traffic and will loads environment variables from a <em>.env file</em></p><p><strong>Prometheus: </strong>Open-source monitoring and alerting toolkit designed specifically to collects metrics from configured targets at regular intervals, storing them efficiently, and allowing querying and visualization of the data. We will be using it in this project to scrape metrics endpoints from various components including the the message broker, the publisher, the subscriber, and the load balancer</p><p><strong>Grafana: </strong>Open-source platform for data visualization and monitoring used in this project to extend the observability capabilities for some services. HAProxy for example comes with a basic dashboard for monitoring front and back end which is not suitable for a production setup, so we will be extending those capabilities by providing a more advanced dashboard for it and for other services</p><blockquote><strong>Note on custom metrics: </strong>Although the main aim of this article is not monitoring and observability, a small example is provided at the end describing how custom metrics can be collected from our application and used for visualization in Grafana</blockquote><p>API Keys and secrets are stored on this docker-compose project inside an <em>.env file</em> and consumed inside the corresponding projects using the following syntax. There is no need for any dependency injection mechanisms here, since the static <strong>Environment class</strong> can access variables associated with the current process, and we can chose which services have access to what variables by including the directive <em>env_file</em> for each image respectively</p><pre>string? accessKey = Environment.GetEnvironmentVariable(&quot;AWS_ACCESS_KEY&quot;);<br>string? secretKey = Environment.GetEnvironmentVariable(&quot;AWS_SECRET&quot;);</pre><p>Once you run the project, the environment variables will be read from the <em>.env file</em> and passed on to the containers, which you can see on docker desktop or by running the following commands:</p><pre>$ docker exec -it &lt;container_name_or_id&gt; /bin/bash<br>$ env<br>or<br>$ printenv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xHZFO_hYVI2IIONsrFk0w.png" /><figcaption>Environment variables on PowerShell/bash</figcaption></figure><h3>Microservices</h3><h4>REST Service — bedrockservice</h4><p>The <strong>BedrockService</strong> is designed to accept client requests via an HTTP Get endpoint, then generate and process image prompts through a series of asynchronous tasks. It utilizes several classes and components to achieve its functionality:</p><ol><li>InvokeModelController: This controller exposes an API endpoint for invoking the image generation process. It randomly selects a prompt from a predefined list and publishes it to a message queue using an instance of IRabbitMqPublisher.</li><li>Payload, ImageGenerationConfig, TextToImageParams: These classes encapsulate the payload structure sent to the message queue, containing information about the task type, text-to-image parameters, and image generation configuration like the number of images to generate, quality settings, and dimensions.</li><li>RabbitMqPublisher: A helper class responsible for publishing messages to a RabbitMQ message broker. It establishes a connection, declares necessary exchanges and queues, and publishes messages with the provided payload.</li><li>Program: The entry point of the application, where the web server is configured using ASP.NET Core. It sets up dependencies, such as adding controllers, configuring Swagger/OpenAPI for documentation, and registering services like IRabbitMqPublisher for dependency injection.</li></ol><p>We will bootstrap an ASP.NET Core Web API project in Visual Studio 2022 using .Net 8.0, HTTPS support using Controllers and an explicit Program class</p><p>This would take care of the initial structure of our solution, and we will be adding three more projects to it later on (Subscriber service, Web client and Docker-Compose orchestrator)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*QH27xchZb8-u1DKESNd10w.png" /></figure><p>We will then add the necessary dependencies:</p><ul><li>AWSSDK.Bedrock 3.7.301.56</li><li>AWSSDK.BedrockRuntime 3.7.301.56</li><li>RabbitMQ Client 6.8.1</li></ul><p>Next is creating the necessary classes for our REST service described earlier</p><p><strong>InvokeModelController Class </strong>is an HTTP endpoint with a prompt randomizer, but you can change it to a POST endpoint and provide your own prompts instead</p><pre>using Amazon.Runtime.Internal;<br>using BedrockService.Helpers;<br>using Microsoft.AspNetCore.Mvc;<br>using System.Threading;<br><br>namespace BedrockService.Controllers<br>{<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class InvokeModelController : ControllerBase<br>    {<br>        private readonly List&lt;string&gt; Prompts = new List&lt;string&gt;<br>        {<br>            &quot;Prompt 1&quot;,<br>            &quot;Prompt 2&quot;,<br>            &quot;Prompt 3&quot;,<br>            &quot;Prompt 4&quot;<br>        };<br><br>        private readonly IRabbitMqPublisher _rabbitMqPublisher;<br>        public InvokeModelController(IRabbitMqPublisher rabbitMqPublisher)<br>        {<br>            _rabbitMqPublisher = rabbitMqPublisher;<br>        }<br>        // GET: api/&lt;InvokeModel&gt;<br>        [HttpGet]<br>        public async Task&lt;ActionResult&lt;IEnumerable&lt;string&gt;&gt;&gt; Get()<br>        {<br>            // Randomly select a prompt from the Prompts list<br>            string randomPrompt = Prompts[new Random().Next(Prompts.Count)];<br><br>            // Publish the randomly selected prompt to the queue<br>            _rabbitMqPublisher.PublishMessage(randomPrompt, new Random().Next());<br>            return Ok($&quot;Message ID {Guid.NewGuid().ToString()} has been published to the queue, awaiting processing by the consumer service&quot;);<br>        }<br><br>    }<br>}</pre><p><strong>Data Access Objects</strong></p><p>Contains a set of data transfer objects (DTOs) used within the <strong>BedrockService </strong>application for handling image generation parameters and payloads</p><pre>using System.ComponentModel.DataAnnotations;<br>using System.Text.Json.Nodes;<br>namespace BedrockService.Dtos<br>{<br>    public class TextToImageParams<br>    {<br>        public string text { get; set; }<br>    }<br><br>    public class ImageGenerationConfig<br>    {<br>        public int numberOfImages { get; set; };<br>        public string quality { get; set; };<br>        public float cfgScale { get; set; };<br>        public int height { get; set; };<br>        public int width { get; set; };<br>        public int seed { get; set; };<br>    }<br><br>    public class Payload<br>    {<br>        public string taskType { get; set; };<br>        public TextToImageParams textToImageParams { get; set; }<br>        public ImageGenerationConfig imageGenerationConfig { get; set; }<br>    }<br>}</pre><p><strong>RabbitMQPublisher Class</strong></p><p>The RabbitMqPublisher class is responsible for publishing messages to a RabbitMQ message broker within the BedrockService application. Here&#39;s an overview of its functionality:</p><ol><li>The Constructor initializes a new instance of the RabbitMqPublisher class, configures a ConnectionFactory with the provided RabbitMQ server details. Note that the connection is initialized in the constructor to avoid creating a new one each time a message is published. We are also setting some arguments to make sure that the queue is highly available across the available nodes, and we will use the modern <a href="https://www.rabbitmq.com/docs/quorum-queues">quorum queues</a> that now replace the original, replicated <a href="https://www.rabbitmq.com/docs/ha">mirrored classic queue</a>. They are designed to be safer and provide simpler, well defined failure handling semantics</li><li>PublishMessage Method: Accepts a prompt string and a seed integer as parameters -&gt; creates message properties with the message ID as a header (RabbitMQ de-dup best practice) -&gt; constructs a payload object containing the task type, image generation configuration, and text-to-image parameters -&gt; serializes the payload object to JSON and converts it to a byte array suitable for being used in the queue. The message is then published to the RabbitMQ exchange with the specified routing key.</li></ol><pre>using RabbitMQ.Client;<br>using System.Text.Json.Nodes;<br>using System.Text;<br>using System.Threading.Channels;<br>using BedrockService.Dtos;<br>using System.Net;<br>using Newtonsoft.Json;<br><br>namespace BedrockService.Helpers<br>{<br>    public class RabbitMqPublisher : IDisposable, IRabbitMqPublisher<br>    {<br>        private string exchangeName = Environment.GetEnvironmentVariable(&quot;exchangeName&quot;);<br>        private string routingKey = Environment.GetEnvironmentVariable(&quot;routingKey&quot;);<br>        private string queueName = Environment.GetEnvironmentVariable(&quot;queueName&quot;);<br>        private readonly IModel channel;<br>        private const string hostName = Environment.GetEnvironmentVariable(&quot;hostName&quot;);<br>        private const string rmqUsername = Environment.GetEnvironmentVariable(&quot;rmqUsername&quot;);<br>        private const string rmqPassword = Environment.GetEnvironmentVariable(&quot;rmqPassword&quot;);<br>        private readonly IConnection conn;<br><br>        public RabbitMqPublisher()<br>        {<br>            var factory = new ConnectionFactory<br>            {<br>                ClientProvidedName = &quot;RabbitMqPublisher&quot;,<br>                HostName = hostName,<br>                Port = 9090,<br>                UserName = rmqUsername,<br>                Password = rmqPassword<br>            };<br>            conn = factory.CreateConnection();<br>            channel = conn.CreateModel();<br>            // Declare a highly available exchange<br>            channel.ExchangeDeclare(exchange: exchangeName,<br>                                    type: ExchangeType.Direct,<br>                                    durable: true,<br>                                    autoDelete: false,<br>                                    arguments: new Dictionary&lt;string, object&gt; { { &quot;x-ha-policy&quot;, &quot;all&quot; } });<br>            channel.QueueDeclare(queue: queueName,<br>                                 durable: true,<br>                                 exclusive: false,<br>                                 autoDelete: false,<br>                                 arguments: new Dictionary&lt;string, object&gt; { { &quot;x-ha-policy&quot;, &quot;all&quot; }, { &quot;x-queue-type&quot;, &quot;quorum&quot; } });<br>            channel.QueueBind(queueName, exchangeName, routingKey, null);<br>            channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);<br><br>        }<br>        public bool PublishMessage(string prompt, int seed)<br>        {<br>            string messageId = Guid.NewGuid().ToString();<br><br>            // Create message properties<br>            var properties = channel.CreateBasicProperties();<br>            properties.Headers = new Dictionary&lt;string, object&gt;  {{ &quot;MessageId&quot;, messageId }};<br><br>            Payload payload = new Payload() {taskType = &quot;TEXT_IMAGE&quot;, imageGenerationConfig = new ImageGenerationConfig() {numberOfImages = 1, quality = &quot;standard&quot;, cfgScale = 8.0f, height = 512, width = 512, seed = seed}, <br>                                                 textToImageParams = new TextToImageParams() { text = prompt }<br>            };<br><br>            byte[] messageBodyBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload));<br><br>            channel.BasicPublish(exchange: exchangeName,<br>                                 routingKey: routingKey,<br>                                 basicProperties: properties,<br>                                 messageBodyBytes);<br>            Console.WriteLine($&quot;Message ID {messageId} sent to {exchangeName} with routing key {routingKey} and queue {queueName} at {DateTime.Now.ToLongTimeString()}&quot;);<br>            return true;<br>        }<br><br>        public void Dispose() {<br>            channel.Close();<br>            conn.Close();<br>            channel.Dispose();<br>            conn.Dispose();<br>        }<br>    }<br>}</pre><p>During testing, you may notice that the AWS Bedrock API would start returning errors if the allowed number of requests per minute is exceeded</p><p>Since we are using the Amazon Titan Image Generator G1, the default requests processed per minute is 60 for runtime operations such as <a href="https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html">InvokeModel</a> and <a href="https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html">InvokeModelWithResponseStream</a> requests. At the moment, none of the available models has an adjustable service quota, however that limit can be lifted for production deployments by requesting <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/prov-throughput.html">Provisioned Throughput for Amazon Bedrock</a></p><h4>Subscriber service — rmqsubservice</h4><p>Worker services are cross-platform background services that usually doesn’t involve a user interface (UI) and are mostly suitable for processing CPU-intensive data, queuing work items in the background and performing a time-based operation on a schedule</p><p>This is the type of project we will use for the sub in this solution</p><pre>using RMQSubService.Service;<br><br>namespace RMQSubService<br>{<br>    public class Worker : BackgroundService<br>    {<br>        private readonly ILogger&lt;Worker&gt; _logger;<br>        private readonly IMessageReader _messageReader;<br>        public Worker(ILogger&lt;Worker&gt; logger, IMessageReader messageReader)<br>        {<br>            _logger = logger;<br>            _messageReader = messageReader;<br>            <br>        }<br>        protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>        {<br>            while (!stoppingToken.IsCancellationRequested)<br>            {<br>                await Task.Run(() =&gt; _messageReader.StartReading());<br>                if (_logger.IsEnabled(LogLevel.Information))<br>                {<br>                    _logger.LogInformation(&quot;Worker running at: {time}&quot;, DateTimeOffset.Now);<br>                }<br>                await Task.Delay(1000, stoppingToken);<br>            }<br>        }<br>        public override async Task StopAsync(CancellationToken stoppingToken)<br>        {<br>            _logger.LogInformation(&quot;Stopping worker service...&quot;);<br>            await base.StopAsync(stoppingToken);<br>            _messageReader.StopReading();<br>        }<br>    }<br>}</pre><p><strong>Message Reader</strong></p><p>Standard RabbitMQ code for reading messages, which is the main tasks we will be calling from the worker service code</p><pre>namespace RMQSubService.Service<br>{<br>    public interface IMessageReader<br>    {<br>        void StartReading();<br>        void StopReading();<br>    }<br>}</pre><pre>using Newtonsoft.Json;<br>using RabbitMQ.Client;<br>using RabbitMQ.Client.Events;<br>using RMQSubService.Dtos;<br>using System;<br>using System.Collections.Generic;<br>using System.Diagnostics.CodeAnalysis;<br>using System.Linq;<br>using System.Text;<br>using System.Threading.Channels;<br>using System.Threading.Tasks;<br>using MongoDB.Driver;<br>using MongoDB.Bson.Serialization;<br>using MongoDB.Bson;<br>using RMQSubService.Helpers;<br><br>namespace RMQSubService.Service<br>{<br>    public class MessageReader : IMessageReader<br>    {<br>        private readonly ILogger&lt;MessageReader&gt; _logger;<br>        private readonly IConnection _connection;<br>        private readonly IModel _channel;<br>        private readonly SemaphoreSlim _queueCreationSemaphore = new SemaphoreSlim(0);<br>        private string _exchangeName = &quot;titan-exchange&quot;;<br>        private string _routingKey = &quot;titan-routing-key&quot;;<br>        private readonly string _queueName = &quot;titan-queue&quot;;<br>        private const string _hostName = &quot;localhost&quot;;<br>        public MessageReader(ILogger&lt;MessageReader&gt; logger, IConfiguration configuration)<br>        {<br>            _logger = logger;<br>            var factory = new ConnectionFactory<br>            {<br>                ClientProvidedName = &quot;RabbitMqSubscriber&quot;,<br>                HostName = _hostName,<br>                Port = 9090,<br>                UserName = &quot;guest&quot;,<br>                Password = &quot;guest&quot;, <br>                ConsumerDispatchConcurrency = 10<br>            };<br>            // Trying to connecto to the queue<br>            while (true)<br>            {<br>                try<br>                {<br>                    _connection = factory.CreateConnection();<br>                    _logger.LogInformation($&quot;Connection to RabbitMQ successful, starting listening for messages&quot;);<br>                    break; // Exit the loop if connection succeeds<br>                }<br>                catch (Exception ex)<br>                {<br>                    _logger.LogWarning($&quot;Error establishing connection to RabbitMQ {ex.Message}. Retrying in 5 seconds...&quot;);<br>                    Task.Delay(TimeSpan.FromSeconds(5)).Wait(); // Wait for 5 seconds before retrying<br>                }<br>            }<br>            _channel = _connection.CreateModel();<br>            _channel.ExchangeDeclare(exchange: _exchangeName,<br>                                    type: ExchangeType.Direct,<br>                                    durable: true,<br>                                    autoDelete: false,<br>                                    arguments: new Dictionary&lt;string, object&gt; { { &quot;x-ha-policy&quot;, &quot;all&quot; } });<br>            _channel.QueueDeclare(queue: _queueName,<br>                                 durable: true,<br>                                 exclusive: false,<br>                                 autoDelete: false,<br>                                 arguments: new Dictionary&lt;string, object&gt; { { &quot;x-ha-policy&quot;, &quot;all&quot; }, { &quot;x-queue-type&quot;, &quot;quorum&quot; } });<br>            _channel.QueueBind(_queueName, _exchangeName, _routingKey, null);<br>            _channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);<br>        }<br>        public void StartReading()<br>        {<br>            var eventConsumer = new EventingBasicConsumer(_channel);<br>            eventConsumer.Received += async (model, ea) =&gt;<br>            {<br>                var body = ea.Body.ToArray();<br>                var message = Encoding.UTF8.GetString(body);<br>                // Access message properties<br>                var properties = ea.BasicProperties;<br>                // Access custom header (MessageId)<br>                string messageId = GetMessageId(properties);<br>                _logger.LogInformation($&quot;Received message: { message}&quot;);<br>                _logger.LogInformation($&quot;Started processing message {messageId} at {DateTime.Now.ToLongTimeString()}&quot;);<br><br>                var payload = JsonConvert.DeserializeObject&lt;Payload&gt;(message);<br><br>                var resultTask = await TitanHelper.InvokeTitanImageGeneratorG1Async(message);<br>                // Convert the string stream to a byte array<br>                byte[] imageBytes = Convert.FromBase64String(resultTask);<br>                S3Helper.UploadImage(&quot;bedrock-images-1&quot;, imageBytes, $&quot;{messageId}.jpg&quot;);<br>                await PersistRecord(messageId);<br>                _logger.LogInformation($&quot;Finished processing message {messageId} at {DateTime.Now.ToLongTimeString()}&quot;);<br>                // Acknowledge the message<br>                _channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);<br>            };<br>            _channel.BasicConsume(queue: _queueName,<br>                                  autoAck: false,<br>                                  consumer: eventConsumer);<br>        }<br>        public void StopReading()<br>        {<br>            _channel.Close();<br>            _connection.Close();<br>        }<br>        private string GetMessageId(IBasicProperties properties)<br>        {<br>            object messageId;<br>            if (properties.Headers != null &amp;&amp; properties.Headers.TryGetValue(&quot;MessageId&quot;, out var value))<br>            {<br>                messageId = Encoding.UTF8.GetString((byte[])value);<br>            }<br>            else<br>            {<br>                messageId = &quot;N/A&quot;;<br>            }<br>            return messageId.ToString();<br>        }<br>    }<br>}</pre><p><strong>Titan Helper Class</strong></p><pre>using Amazon;<br>using Amazon.BedrockRuntime;<br>using Amazon.BedrockRuntime.Model;<br>using Amazon.Runtime;<br>using Amazon.Util;<br>using System.Text.Json.Nodes;<br><br>namespace RMQSubService.Helpers<br>{<br>    public static class TitanHelper<br>    {<br>        public static async Task&lt;string?&gt; InvokeTitanImageGeneratorG1Async(string message)<br>        {<br>            string titanImageGeneratorG1ModelId = &quot;amazon.titan-image-generator-v1&quot;;<br>            string? accessKey = Environment.GetEnvironmentVariable(&quot;AWS_ACCESS_KEY&quot;);<br>            string? secretKey = Environment.GetEnvironmentVariable(&quot;AWS_SECRET&quot;);<br>            AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);<br>            AmazonBedrockRuntimeClient client = new(credentials, RegionEndpoint.USEast1);<br><br>            try<br>            {<br>                InvokeModelResponse response = await client.InvokeModelAsync(new InvokeModelRequest()<br>                {<br>                    ModelId = titanImageGeneratorG1ModelId,<br>                    Body = AWSSDKUtils.GenerateMemoryStreamFromString(message),<br>                    ContentType = &quot;application/json&quot;,<br>                    Accept = &quot;application/json&quot;<br>                });<br><br>                if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)<br>                {<br>                    var results = JsonNode.ParseAsync(response.Body).Result?[&quot;images&quot;]?.AsArray(); ;<br><br>                    return results?[0]?.GetValue&lt;string&gt;();<br>                }<br>                else<br>                {<br>                    _logger.LogError(&quot;InvokeModel failed with status code &quot; + response.HttpStatusCode);<br>                }<br>            }<br>            catch (AmazonBedrockRuntimeException e)<br>            {<br>                _logger.LogError(e.Message);<br>            }<br>            return null;<br>        }<br><br>    }<br>}</pre><p><strong>S3 Helper Class</strong></p><p>This class, named S3Helper, is a static helper class within the RMQSubService.Helpers namespace. It‘s sole purpose is uploading of images to Amazon S3 storage</p><p>The UploadImage method within the class accepts three parameters: bucketName, imageBytes, and keyName. It takes the byte array representing the image data, along with the S3 bucket name and the key name under which the image will be stored in the bucket.</p><p>Inside the method, it retrieves AWS access and secret keys from environment variables (AWS_ACCESS_KEY and AWS_SECRET, respectively). Then, it creates an instance of Amazon.S3Client using these credentials and the desired AWS region (USEast1 in this case) and a TransferUtility</p><p>Next, we convert the byte array into a MemoryStream and uploads it to the specified S3 bucket using the Upload method of the TransferUtility class.</p><p>At this point, the S3 object will be available via our CloudFront CDN as well</p><pre>using Amazon.S3;<br>using Amazon.S3.Transfer;<br><br>namespace RMQSubService.Helpers<br>{<br>    public static class S3Helper<br>    {<br>        public static void UploadImage(string bucketName, byte[] imageBytes, string keyName)<br>        {<br>            string? accessKey = Environment.GetEnvironmentVariable(&quot;AWS_ACCESS_KEY&quot;);<br>            string? secretKey = Environment.GetEnvironmentVariable(&quot;AWS_SECRET&quot;);<br><br>            try<br>            {<br>                var credentials = new Amazon.Runtime.BasicAWSCredentials(accessKey, secretKey);<br>                var s3Client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.USEast1);<br>                var fileTransferUtility = new TransferUtility(s3Client);<br>                // Create a memory stream from the byte array<br>                using (MemoryStream stream = new MemoryStream(imageBytes))<br>                {<br>                    // Upload the stream to S3<br>                    fileTransferUtility.Upload(stream, bucketName, keyName);<br>                }<br>                _logger.LogInformation(&quot;Upload completed&quot;);<br>            }<br>            catch (AmazonS3Exception e)<br>            {<br>                _logger.LogError($&quot;Error uploading to S3: {e.Message}, used {accessKey} and {secretKey}&quot;);<br>            }<br>        }<br>    }<br>}</pre><p><strong>Persisting Records in a Database</strong></p><p>The following method named PersistRecord is a private asynchronous task responsible for persisting a record into a MongoDB database and is called from the MessageReader class described earlier . It accepts a messageId parameter, which presumably identifies the image associated with the record being persisted.</p><p>Within the method, a BsonDocument object is constructed to represent the data to be stored in MongoDB. This document includes two fields: &quot;imageId&quot;, which holds the provided messageId, and &quot;url&quot;, which is a formatted string representing the URL of the image.</p><p>The payload, represented by the bsonObject, is inserted into the MongoDB collection asynchronously using the InsertOneAsync method, which will return insertedId of type ObjectId</p><pre>private async Task&lt;ObjectId&gt; PersistRecord(string messageId)<br>{<br>    BsonDocument bsonObject = new BsonDocument<br>    {<br>        { &quot;imageId&quot;, messageId },<br>        { &quot;url&quot;, $&quot;https://my-cf-distribution.cloudfront.net/{messageId}.jpg&quot; }<br>    };<br>    var client = new MongoClient(&quot;mongodb://localhost:27017&quot;);<br><br>    // Get or create the database<br>    var databaseName = &quot;messageDB&quot;;<br>    var database = client.GetDatabase(databaseName);<br><br>    // Get or create the collection<br>    var collectionName = &quot;GeneratedImages&quot;;<br>    var collection = database.GetCollection&lt;BsonDocument&gt;(collectionName);<br><br>    // Insert the payload into MongoDB<br>    await collection.InsertOneAsync(bsonObject);<br>    // Retrieving the ID of the inserted document<br>    ObjectId insertedId = bsonObject[&quot;_id&quot;].AsObjectId;<br>    _logger.LogInformation($&quot;Payload with id {insertedId} inserted in database&quot;);<br>    return insertedId;<br>}</pre><p>Any successfully saved image will have it’s metadata persisted in a database as well, and we are able to view these records by using a MongoDB client such as <a href="https://www.mongodb.com/products/tools/compass">Compass</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oy5vo7YmZN53a_k2n81UVg.png" /></figure><h4>Front-end Service — webclient</h4><p>The front end couldn’t be simpler. This ASP.NET Razor Pages project is designed to interact with the MongoDB database and collection created while running the project to retrieve and display images on a web page. Here’s a copy of the server code, i will leave out the obscure CSS and markup to you</p><pre>namespace WebClient.Pages<br>{<br>    public class IndexModel : PageModel<br>    {<br>        private readonly ILogger&lt;IndexModel&gt; _logger;<br>        private readonly IMongoClient _mongoClient;<br>        public List&lt;(string imageId, string url)&gt;? ImageData { get; private set; }<br>        public IndexModel(ILogger&lt;IndexModel&gt; logger, IMongoClient mongoClient)<br>        {<br>            _logger = logger;<br>            _mongoClient = mongoClient;<br>        }<br><br>        public async Task OnGetAsync()<br>        {<br>            var database = _mongoClient.GetDatabase(&quot;messageDB&quot;);<br>            var collection = database.GetCollection&lt;BsonDocument&gt;(&quot;GeneratedImages&quot;);<br><br>            var filter = Builders&lt;BsonDocument&gt;.Filter.Empty;<br>            var cursor = await collection.FindAsync(filter);<br>            var imageData = await cursor.ToListAsync();<br><br>            ImageData = imageData.Select(doc =&gt; (doc.GetValue(&quot;imageId&quot;).AsString, doc.GetValue(&quot;url&quot;).AsString)).ToList();<br>        }<br>    }<br>}</pre><p>You can see the end result in the upcoming section titled “Running the project”</p><h4>Monitoring — prometheus and grafana</h4><p>We will be leveraging the OpenTelemetry capabilities of the .NET framework</p><p>As of the time of writing this article, the libraries are still in release candidate or beta status</p><p>More information at <a href="https://opentelemetry.io/docs/languages/net/">https://opentelemetry.io/docs/languages/net/</a></p><p>Dependencies include:</p><ul><li>OpenTelemetry.Exporter.Prometheus.AspNetCore 1.7.0-rc.1</li><li>OpenTelemetry.Extensions.Hosting 1.8.0</li><li>OpenTelemetry.Instrumentation.Process 0.5.0-beta.5</li><li>OpenTelemetry.Instrumentation.Runtime 1.8.0</li></ul><p><strong>BedrockMetrics Class</strong></p><pre><br>using System.Diagnostics.Metrics;<br><br>namespace Bedrock.monitoring<br>{<br>    public class BedrockMetrics<br>    {<br>        private readonly Counter&lt;int&gt; _total_requests;<br>        private readonly Counter&lt;int&gt; _rate_limited_requests;<br>        private readonly Counter&lt;int&gt; _successful_image_generation_requests;<br>        private readonly Counter&lt;int&gt; _failed_image_generation_requests;<br>        private readonly Histogram&lt;int&gt; _average_image_generation_time;<br>        private readonly Histogram&lt;int&gt; _cache_hit_rate;<br>        private readonly Histogram&lt;int&gt; _database_query_execution_time;<br>        private readonly Histogram&lt;int&gt; _concurrency_level;<br><br>        public BedrockMetrics(IMeterFactory meterFactory)<br>        {<br>            var meter = meterFactory.Create(&quot;bedrock.metrics&quot;);<br>            _total_requests = meter.CreateCounter&lt;int&gt;(&quot;bedrock.metrics.total_requests&quot;);<br>            _rate_limited_requests = meter.CreateCounter&lt;int&gt;(&quot;bedrock.metrics.rate_limited_requests&quot;);<br>            _successful_image_generation_requests = meter.CreateCounter&lt;int&gt;(&quot;bedrock.metrics.successful_image_generation_requests&quot;);<br>            _failed_image_generation_requests = meter.CreateCounter&lt;int&gt;(&quot;bedrock.metrics.failed_image_generation_requests&quot;);<br>            _average_image_generation_time = meter.CreateHistogram&lt;int&gt;(&quot;bedrock.metrics.average_image_generation_time&quot;);<br>            _cache_hit_rate = meter.CreateHistogram&lt;int&gt;(&quot;bedrock.metrics.cache_hit_rate&quot;);<br>            _database_query_execution_time = meter.CreateHistogram&lt;int&gt;(&quot;bedrock.metrics.database_query_execution_time&quot;);<br>            _concurrency_level = meter.CreateHistogram&lt;int&gt;(&quot;bedrock.metrics.concurrency_level&quot;);<br>        }<br>        public void AddTotalRequest(int value)<br>        {<br>            _total_requests.Add(value);<br>        }<br><br>        public void AddRateLimitedRequest(int value)<br>        {<br>            _rate_limited_requests.Add(value);<br>        }<br><br>        public void AddSuccessfulImageGenerationRequest(int value)<br>        {<br>            _successful_image_generation_requests.Add(value);<br>        }<br><br>        public void AddFailedImageGenerationRequest(int value)<br>        {<br>            _failed_image_generation_requests.Add(value);<br>        }<br><br>        public void SetAverageImageGenerationTime(int timeInMilliseconds)<br>        {<br>            _average_image_generation_time.Record(timeInMilliseconds);<br>        }<br><br>        public void SetCacheHitRate(int cacheHitRate)<br>        {<br>            _cache_hit_rate.Record(cacheHitRate);<br>        }<br><br>        public void SetDatabaseQueryExecutionTime(int queryExecutionTime)<br>        {<br>            _database_query_execution_time.Record(queryExecutionTime);<br>        }<br><br>        public void SetConcurrencyLevel(int concurrencyLevel)<br>        {<br>            _concurrency_level.Record(concurrencyLevel);<br>        }<br>    }<br>}</pre><p><strong>Program Class</strong></p><pre>builder.Services.AddOpenTelemetry()<br>    .WithMetrics(metrics =&gt;<br>    {<br>        //metrics.AddMeter();<br>        metrics.AddMeter(&quot;Microsoft.AspNetCore.Hosting&quot;);<br>        metrics.AddMeter(&quot;Microsoft.AspNetCore.Server.Kestrel&quot;);<br>        metrics.AddMeter(&quot;System.Net.Http&quot;);<br>        metrics.AddMeter(&quot;Microsoft.AspNetCore.Hosting&quot;);<br>        metrics.AddMeter(&quot;Microsoft.AspNetCore.Http.Connections&quot;);<br>        metrics.AddMeter(&quot;Microsoft.AspNetCore.Routing&quot;);<br>        metrics.AddMeter(&quot;Microsoft.AspNetCore.Diagnostics&quot;);<br>        metrics.AddMeter(&quot;Microsoft.AspNetCore.RateLimiting&quot;);<br>        metrics.AddMeter(&quot;bedrock.metrics&quot;); // customer meters<br>        metrics.AddRuntimeInstrumentation();<br>        metrics.AddProcessInstrumentation();<br>        metrics.AddPrometheusExporter();<br>    });<br><br>app.MapPrometheusScrapingEndpoint();</pre><p><strong>Prometheus Configuration (prometheus.yml)</strong></p><pre>global:<br>  scrape_interval: 15s<br>  scrape_timeout: 5s<br>  evaluation_interval: 15s<br> <br>rule_files:<br><br>scrape_configs:<br>  - job_name: &quot;bedrock-service-scrape&quot;<br>    static_configs:<br>      - targets: [&quot;bedrockservice:8080&quot;]<br>  - job_name: &quot;prometheus-scrape&quot;<br>    static_configs:<br>      - targets: [&quot;prometheus:9090&quot;]<br>  - job_name: &#39;rabbitmq-scrape&#39;<br>    static_configs:<br>      - targets: [&quot;rabbitmq1:15692&quot;]<br>  - job_name: &#39;haproxy-exporter-scrape&#39;<br>    static_configs:<br>      - targets: [&quot;haproxy:8405&quot;]</pre><p><strong>Docker Compose additions</strong></p><pre>version: &#39;3.4&#39;<br><br>services:<br>  prometheus:<br>    image: prom/prometheus<br>    ports:<br>      - &quot;9090:9090&quot;<br>    volumes:<br>      - ./prometheus.yml:/etc/prometheus/prometheus.yml<br>    depends_on:<br>      - bedrockservice<br>  grafana:<br>    image: grafana/grafana<br>    container_name: grafana<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      - GF_SECURITY_ADMIN_USER=root<br>      - GF_SECURITY_ADMIN_PASSWORD=root<br>    volumes:<br>      - grafana_data:/var/lib/grafana<br>    depends_on:<br>      - prometheus<br><br>volumes:<br>  grafana_data:</pre><h3>Running the project</h3><p>You can either run the project directly through Visual Studio by selecting the Docker Compose profile, or cd to the solution folder and run a docker-compose up (-d to run in the background and starts the services defined in docker-compose.yml file in detached mode)</p><p>You should be able to see the network, containers and volumes being created and the logs from all services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WB7MfVDDDNlHY3OrRq8Pg.png" /></figure><p>After a while, the <em>bedrockservice </em>will start trying to connect to HAProxy a few times and will notify once the connection to the message broker is successful, signaling that we can start performing HTTP requests to the GET endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W45rXVibXRoet228gLT-1w.png" /><figcaption>HAProxy load balancer statistics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*52oeseJWxiFWUkbQ1A5j1A.png" /><figcaption>RabbitMQ Statistics</figcaption></figure><p>We use Postman to generate requests and perform a little bit of stress testing. On a development machine, a sustained 10 minutes with 100 virtual users averaged 49 requests/s, 51ms response time and a 0% error rate, and each request is basically performing a message reception/ack, construct Bedrock payload, a database insert and an S3 push</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEYCGAReoALckSBFKlN4Fg.png" /><figcaption>Performance Tests (Postman client)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rr43hdn0f0bD4-zk5FoE1w.gif" /><figcaption>RabbitMQ subscriber service working hard!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0pck6B9o6E1jlSQWgRF2Q.png" /><figcaption>The Result!</figcaption></figure><h3>Service Quotas</h3><p>It is important to note that Bedrock is has a rate limiting . Therefore, the async code required to generate images and store them in S3 has been disabled for stress testing purposes and a production setup should include a proper mechanism for controlling the number of outbound http requests using a token bucket algorithm (handles bursts) or leaky bucket algorithm (sustained output rates)</p><h3>APM</h3><p>Application Performance Monitoring refers to the practices, tools, and processes used to monitor and manage the performance and availability of software applications. APM solutions typically provide insights into various aspects of an application’s performance, including response times, error rates, resource utilization, and end-user experience.</p><p>Some of my favorite APM features are distributed trancing and the ability to correlate information parsed from logs with metrics generated from applications to observe system behavior under load and predict infrastructure components potentially becoming problematic or software tiers causing bottlenecks</p><h3>Visualizations</h3><p>There are ready-made dashboards that can be used to visualize OpenTelemetry metrics related to the ASP.NET runtime including Requests status (4xx, 5xx, 2xx…), Requests/Response durations, HTTPS termination statistics, CPU and memory usage, Heap and ThreadPool, GC Collections, Endpoints metrics</p><p>Here are some interesting dashboards used in this project:</p><p><a href="https://grafana.com/grafana/dashboards/19924-asp-net-core/">ASP.NET Core metrics from OpenTelemetry</a> is a dashboard to show ASP.NET (.NET Core/5/6/7) metrics produced by opentelemetry-dotnet tools for Prometheus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96e_DOwTTVbwhDkxYOGslQ.png" /><figcaption>ASP.NET OpenTelemetry (OTEL Collectors)</figcaption></figure><p><a href="https://grafana.com/grafana/dashboards/12693-haproxy-2-full/">HAProxy with Prometheus data</a> is a great dashboard with Prometheus support encompassing all kind of metrics to monitor front and backends</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TuXopHXEOmaFHsaVWiE7Q.png" /><figcaption>HAProxy load balancer metrics</figcaption></figure><p><a href="https://grafana.com/grafana/dashboards/10991-rabbitmq-overview/">RabbitMQ-Overview</a> provides insights into the status of any RabbitMQ cluster instantly. This dashboard provides a comprehensive overview of all metrics showcased on the RabbitMQ Management Overview page.</p><p>All metrics are specific to each node, simplifying the identification of cluster imbalances, also known as cluster hotspots.</p><p>Metrics on display include:</p><ul><li>Node identification, using RabbitMQ and Erlang/OTP version details</li><li>Node memory and disk availability before publishers become blocked</li><li>Node file descriptors and TCP sockets availability</li><li>Ready and pending message counts</li><li>Incoming message rates: published, routed to queues, confirmed, unconfirmed, returned, and dropped</li><li>Outgoing message rates: delivered with auto or manual acknowledgments, acknowledged, and redelivered</li><li>Polling operations with auto or manual acknowledgments, as well as empty operations</li><li>Queue metrics, including declaration and deletion rates</li><li>Channel metrics, including open and close rates</li><li>Connection metrics, including open and close rates</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbSgb7ZvKz0ATVuYdwIDeQ.png" /><figcaption>RabbitMQ Node metrics</figcaption></figure><p><a href="https://grafana.com/grafana/dashboards/19896-asp-net-otel-metrics-from-otel-collector/">ASP.NET OTEL Metrics from OTEL Collector</a> demonstrates the metrics of .NET and ASP.NET (.NET Core/5/6/7) generated by OTLP instruments and integrated into an application. These metrics are transmitted to the OpenTelemetry Collector, which subsequently exposes them for retrieval by Prometheus. Finally, the Grafana dashboard retrieves the metrics from Prometheus for visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMttvjcBrRLum0z8pgVyTw.png" /><figcaption>ASP.NET Core metrics</figcaption></figure><p>The custom metrics we defined earlier as part of bedrock.metrics meter are available in Grafana via Prometeus scraping endpoint and can be used to create relevant dashboards</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tw7LVp6PTg2y5QSdSSlpw.png" /><figcaption>Custom Bedrock service metrics</figcaption></figure><h3>AWS Bedrock use-cases</h3><p>We live in exciting times! Today, we have at our disposal some amazing generative AI tools capable of perceiving, listening, speaking, reading, writing, and creating. These generative AIs are increasingly evolving to perform multiple functions simultaneously, such as generating both text and images concurrently.</p><p>These tools will continue to shape the next revolutions in technology and will surely enhance existing jobs, increase efficiency and productivity, and will offload repetitive tasks to machines, while humans will focus more on problem-solving and creativity</p><p>Some of the use cases include:</p><h4>Text generation</h4><p>Generate fresh content across various platforms, including blogs, social media, and webpage content.</p><h4>Virtual assistants</h4><p>Develop virtual assistants capable of comprehending user queries, breaking down tasks, engaging in dialogue to gather details, and executing actions to meet user needs.</p><h4>Text and image search</h4><p>Utilize text and image search capabilities to locate and compile pertinent information, providing answers and recommendations from extensive text and image datasets.</p><h4>Text summarization</h4><p>Condense lengthy documents such as articles, reports, research papers, and technical documentation into summaries for rapid and efficient extraction of key information.</p><h4><strong>Prompts examples</strong></h4><p>These are some of prompts used in this project, feel free to experiment!</p><pre>private readonly List&lt;string&gt; Prompts = new List&lt;string&gt;<br>{<br>    &quot;A majestic phoenix rising from vibrant flames against a twilight sky.&quot;,<br>    &quot;A bustling cityscape at sunset, with skyscrapers reflecting the warm hues of the evening sun.&quot;,<br>    &quot;An enchanted forest illuminated by the soft glow of bioluminescent plants and creatures.&quot;,<br>    &quot;A cosmic voyage through swirling galaxies and nebulae in an endless universe.&quot;,<br>    &quot;A surreal underwater world teeming with exotic marine life and coral reefs in vivid shades.&quot;,<br>    &quot;A magical garden filled with blooming flowers of every color, amidst fluttering butterflies and hummingbirds.&quot;,<br>    &quot;A futuristic metropolis with neon-lit streets and flying cars zipping past towering holographic advertisements.&quot;,<br>    &quot;A peaceful countryside scene with rolling hills, golden fields, and a rainbow stretching across the sky after a refreshing rain shower.&quot;,<br>    &quot;A fantastical realm of dragons and castles, where mystical creatures roam under a sky painted with swirling auroras.&quot;,<br>    &quot;An abstract composition of geometric shapes and patterns in a kaleidoscope of bold and contrasting colors.&quot;<br>};</pre><h3>Future considerations and enhancements</h3><p>Some of the optimizations we could introduce in order to improve performance would include:</p><ul><li>Access control and authentication mechanisms</li><li>Rate limiting mechanisms</li><li>The use of an API gateway for distributing requests amongst services</li><li>Securing endpoints</li><li>Implementing encryption</li></ul><h3>Conclusion</h3><p>This article has provided a comprehensive overview of developing a web-based solution for generating and visualizing AI-generated images with AWS Bedrock. However, this is just the beginning.</p><p><strong>Part-2</strong> of this series will delve into the deployment phase, utilizing Terraform to create essential resources including IAM, S3, CloudFront, ECR, and ECS to run and orchestrate containers. Additionally, it will cover CI/CD pipelines employing GitHub, CircleCI, Synk for image security scans, and the Bridgecrew terraform orb for infrastructure-as-code error scans within the CircleCI workflows.</p><p>Stay tuned for the next installment, where we’ll continue our journey towards building resilient and performant systems with cutting-edge technologies.</p><h3>Additional Reading Material</h3><ul><li><a href="https://aws.amazon.com/bedrock/">Intro to Amazon Bedrock</a></li><li><a href="https://catalog.us-east-1.prod.workshops.aws/workshops/a4bdb007-5600-4368-81c5-ff5b4154f518/en-US">Amazon Bedrock Workshop</a></li><li><a href="https://explore.skillbuilder.aws/learn/course/external/view/elearning/17904/building-generative-ai-applications-using-amazon-bedrock">Building Generative AI Applications Using Amazon Bedrock</a></li><li><a href="https://microservices.io/">https://microservices.io/</a></li><li><a href="https://learn.microsoft.com/en-us/aspnet/core/log-mon/metrics/metrics?view=aspnetcore-8.0">ASP.NET Core metrics</a></li><li><a href="https://github.com/rabbitmq/rabbitmq-server">rabbitmq-server</a></li></ul><h3>Source Code</h3><p>If you would like a copy of the entire project, hit me up on one of the following channels and i will share the GitHub repository with you</p><p>Thank you for reading and if you find this article insightful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Disclaimer</h3><p>All pictures, illustrations and diagrams featured in this work are credited to the author, in alignment with their creative efforts and contributions to this content. Any resemblance to other works is purely coincidental. The author holds the rights to these visual elements, ensuring the authenticity and originality of their work.</p><h4><a href="http://cloudhandbook.substack.com/"><strong>The CloudHandbook on Substack — Join 1500+ incredible readers</strong></a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONlIruiYUSQrXVLTRiM8sQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba8e3913f959" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/generative-ai-with-amazon-bedrock-rabbitmq-and-net-8-ba8e3913f959">Generative AI with Amazon Bedrock, RabbitMQ and .NET 8</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Infrastructure Orchestration with Terraform and CircleCI]]></title>
            <link>https://towardsaws.com/aws-infrastructure-orchestration-with-terraform-and-circleci-58915cab8bec?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/58915cab8bec</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[circleci]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 04:00:08 GMT</pubDate>
            <atom:updated>2023-08-18T06:20:09.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P576h0pfKK4tOSIB983tLA.jpeg" /><figcaption>Beautiful Dubai Sunset!</figcaption></figure><p>In the midst of Dubai’s summer heat, something cool is on going on (and I am not talking about the cranked-up AC at home).</p><p>Picture this: AWS infrastructure getting a makeover, all thanks to Terraform and CircleCI!</p><p>In this article, I will deep-dive into a practical use case of deploying an AWS Transfer Family workload using my Infrastructure as Code (IaC) tool of choice, Terraform. We will then automate the GitOps process using CircleCI pipelines</p><h3>What you need to get started?</h3><ul><li>Visual Studio Code</li><li>An account in Github</li><li>An account in CircleCI</li><li>An AWS Account and CLI installed</li><li>Download and install Terraform</li><li>Download and install CircleCI CLI</li></ul><h3>Solution Architecture</h3><p>The AWS Transfer Family is a set of fully managed file transfer services designed to simplify and enhance the process of moving files to and from Amazon Web Services (AWS). It offers secure, scalable, and efficient solutions for transferring files between your on-premises infrastructure, Amazon S3 (Simple Storage Service), and Amazon EFS (Elastic File System)</p><p>The main purpose of this application is to deploy an SFTP system powered by AWS Transfer Family Managed Service, along with the required user accounts and their respective authentication certificates, the logging mechanisms around that, as well as a pub-sub notification system, while making sure that all communication is encrypted at transit and at rest</p><p>We are therefore leveraging comprehensive infrastructure composed of several essential components. These components include various foundational elements such as IAM Policies and Roles, KMS Key Policies, and IAM Role configurations tailored to specific service requirements, and services such as Route53 and CloudWatch that enables further customization and logging respectively</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCbGkVo9wwoZAkkWdiDeFA.png" /><figcaption>Solution Architecture Diagram</figcaption></figure><p><strong>IAM Policies and Roles</strong></p><ul><li>KMS Key Policy to enable access for SNS Service Principal encrypted topic to the CMK (Customer Managed Key)</li><li>IAM Policy document to enable the Amazon S3 service (identified by its principal) to publish messages to an SNS topic, under certain conditions related to the AWS account and the source ARN</li><li>IAM Role required by AWS Transfer Family to interact with S3 Object Storage</li><li>IAM Role to enable AWS Transfer service to assume this role and take on the permissions and policies associated with this role for specific tasks related to secure file transfers</li><li>IAM Policy allowing specific Logs actions for a CloudWatch Log Group. The policy is intended to grant permissions for logging data related to AWS Transfer Family server activity into CloudWatch Logs. We will need it for enabling monitoring and analysis of server activity through CloudWatch logs</li></ul><p><strong>KMS Keys</strong></p><ul><li>CMK used to encrypt SNS communication</li><li>CMK used to encrypt CloudWatch Log Groups</li><li>Key Aliases</li></ul><p><strong>SNS Topic</strong> will be used to send out notification by email whenever a new file is uploaded into the SFTP. This functionality can be definitely improved either by using a custom Lambda function, or by leveraging the Transfer Family Workflows functionality</p><p>The SNS topic is encrypted for security purposes using KMS, and is triggered by “s3:ObjectCreated” events</p><p><strong>Service managed AWS Transfer Family</strong> instance with a public endpoint and SSH File Transfer Protocol</p><p><strong>SSH Keys</strong> for each of the Transfer Family user accounts</p><p><strong>CloudWatch Log Group</strong> used to record all activity on the SFTP</p><p><strong>Route53</strong> Hosted Zone and CNAME record to use as an endpoint</p><h3>The Approach</h3><p>The entire application configuration, including infrastructure as code (IaC), application code (if any), configuration files, and deployment specifications, will be stored in a Git repository (GitHub). Changes to the desired state will be made by submitting pull requests or direct commits to the repository, which enables us to review them, and maintain an auditable history of modifications.</p><p>The core principles we will be adhering to in this project are:</p><ul><li><strong>Declarative Configuration</strong>: The desired state of the application and infrastructure is defined in configuration files stored in the Git repository.</li><li><strong>Version Control</strong>: All changes to the application and infrastructure are versioned in Git.</li><li><strong>Continuous Deployment</strong>: The Git repository serves as the source of truth for the application’s configuration. Automated pipelines monitor the repository for changes and automatically deploy updates to the target environment based on the repository’s state.</li><li><strong>Audit and Compliance</strong>: With all changes tracked in Git, it’s easier to maintain compliance and auditing requirements, as well as troubleshoot issues by reviewing historical changes.</li></ul><p>A “<strong>Security-First</strong>” approach that emphasizes prioritizing security considerations throughout the GitOps workflow will be one of our guiding principle. We will make sure throughout the project that we:</p><ul><li>Apply the principle of <em>least privilege</em> by configuring appropriate IAM roles and permissions for infrastructure resources</li><li>Implement infrastructure as <em>code best practices</em>, such as using parameterization and secrets management to prevent sensitive information from being exposed in our code</li><li>Conduct security <em>scans and assessments</em> of our Terraform code and configurations to ensure compliance with industry best practices and security standards.</li></ul><p>We could also add a Reconciliation part by constantly comparing the desired state in the Git repository with the actual state of the deployed resources. If there are any discrepancies, corrective actions will be taken automatically to bring the environment back to the desired state. That’s perhaps something for another article</p><h3>Code Storage and Version Control</h3><p>Let’s get you started from the very beginning!</p><p>Create a new project in GitHub by going to github.com and logging in to your account. Once logged in, click on the “+” sign in the upper right corner and select “New repository”. Fill in the repository name, description, and choose the appropriate visibility (public or private) and click “Create repository” to create the project.</p><p>Now let’s clone our repository in Visual Studio Code. You can either do that by selecting the Clone option on Github, or via the Visual Studio in the Welcome screen called “Clone Git Repository”, If you are logged in to your Github account, you will see the new repository there. Just provide a directory and you are all set</p><p>Make sure you also install CircleCI VS Code plugin <a href="https://circleci.com/product/vscode-extension/">https://circleci.com/product/vscode-extension/</a></p><p>Our project structure should look like this for now, we will add more to it later</p><pre>Project Root<br>├── main.tf<br>├── backend.tf<br>├── outputs.tf<br>├── policies.tf<br>├── provider.tf<br>├── variables.tf<br>├── terraform.tfvars<br>└── .gitignore</pre><ul><li>main.tf is the core configuration file where you define your infrastructure resources and their configurations. This file contains the primary declarations of resources, data sources, and modules you intend to create or manage.</li><li>backend.tf defines the backend configuration for storing Terraform&#39;s state file remotely. It includes settings for remote state storage, such as backend type (e.g., S3, Azure Blob Storage), access credentials, and configuration details.</li><li>outputs.tf is used to define output values that can be displayed after Terraform applies your configuration. Outputs can provide useful information like IP addresses, endpoint URLs, or other relevant data generated by our infrastructure, and these outputs are displayed in the terminal after applying the configuration.</li><li>policies.tf will be used to define IAM policies and roles required for our resources.</li><li>provider.tf contains provider configurations that define the cloud or service providers we’re using. In this file, we will specify details like authentication, region, and other provider-specific settings. Terraform uses these configurations to interact with the respective providers’ APIs.</li><li>variables.tf defines input variables that allow us to parameterize our Terraform configuration.</li><li>terraform.tfvars is a file where we actually assign values to the variables declared in variables.tf. It is important to note this file is excluded from version control to avoid sharing sensitive information. The values will be ported as secrets and environment variables on the CI/CD part</li></ul><h3>Terraform Setup</h3><p>The tool being used here is Terraform and it requires a few simple steps to initialize</p><p>The first thing to do if you don’t have Terraform installed yet is to go to <a href="https://developer.hashicorp.com/terraform/downloads">https://developer.hashicorp.com/terraform/downloads</a> and download the latest version. You can verify the installation by running “<em>terraform — version</em>”</p><pre>PS C:\projects\my-project&gt; terraform --version<br>Terraform v1.5.5<br>on windows_386<br>+ provider registry.terraform.io/hashicorp/aws v5.11.0</pre><p>Assuming you have already created a new folder and cd into it, replicate the same file structure described earlier and let’s start adding our HCL code to the project</p><p>We will first define a backend in our code, which is where Terraform stores its state files</p><p>Several options are available for configuring the backend including:</p><ul><li><strong>Local Backend</strong>: The local backend stores the state file on the local filesystem of the machine where Terraform commands are run. This is the default backend and is suitable for single-person projects or experimentation. It’s not recommended for team collaboration or production environments.</li><li><strong>S3 Backend</strong>: The S3 backend stores the state file in an Amazon S3 bucket. This is a popular choice for many Terraform users as it provides centralized storage, durability, and access control. The S3 backend also supports versioning and locking to prevent concurrent state modifications. This is the option we will be using for this project</li><li><strong>Azure Storage Backend</strong>: Similar to the S3 backend, the Azure Storage backend stores the state file in an Azure Storage Account in Microsoft Azure. It offers similar benefits like centralized storage, versioning, and access control.</li><li><strong>Google Cloud Storage Backend</strong>: The Google Cloud Storage backend stores the state file in a Google Cloud Storage bucket on Google Cloud Platform. This is the equivalent of S3 and Azure Storage backends but for GCP.</li><li><strong>HTTP Backend</strong>: The HTTP backend allows you to store the state file on a remote HTTP server. This can be useful if you have a custom backend system in place, but it lacks some of the features and robustness of other backends like S3 or Azure Storage.</li><li><strong>Consul Backend</strong>: The Consul backend stores the state file in HashiCorp Consul, a distributed service mesh and key-value store. This option is suitable for users who are already using Consul and want to keep their Terraform state integrated with their Consul setup.</li><li><strong>Terraform Cloud/Enterprise Backend</strong>: Terraform Cloud (for open-source users) and Terraform Enterprise (for enterprise users) provide cloud-based backends that offer collaboration features, remote state management, and integration with version control systems. These options are suitable for team collaboration and more complex environments.</li></ul><p>For that, we will be using an AWS S3 backend that relies on an S3 bucket and a DynamoDB table.</p><p>Make sure you enable <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/manage-versioning-examples.html">Bucket Versioning</a> on the S3 bucket used for storage to allow for state recovery in the case of accidental deletions</p><p>Here is an example you can use for backend.tfonce you have created your S3 bucket:</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;your-terraform-state-bucket&quot;<br>    key            = &quot;your-state-file.tfstate&quot;<br>    region         = &quot;us-east-1&quot;  # Specify the desired AWS region<br>    encrypt        = true         # Enable encryption of state file<br>    dynamodb_table = &quot;your-lock-table&quot;  # Optional: Enable state locking with DynamoDB<br>  }<br>}</pre><p>As for state locking, create a DynamoDB table where the partition key is named LockID with type of String. If not configured, state locking will be disabled</p><p>Next is our provider.tfthat defines the cloud provider we target:</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.11.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><p>After having taken care of the basics, it’s time to add some code to our main.tf</p><p>Let’s start testing our project by adding a simple statement to retrieve information about the caller’s identity</p><pre>data &quot;aws_caller_identity&quot; &quot;current&quot; {}</pre><p>Running a “<em>terraform validate</em>” command on the terminal should return a message saying “<em>Success! The configuration is valid.</em>”</p><blockquote>Note: The caller identity should already be in place as part of configuring AWS CLI, if not please setup a <a href="https://docs.aws.amazon.com/sdkref/latest/guide/file-location.html">shared credentials file</a> with the necessary IAM permissions to enable Terraform to interact with AWS API, but make sure no credentials are being stored in terraform files as it is not recommended!</blockquote><p>After making sure there are no syntax errors, you can initialize the Terraform backend and download the necessary provider plugins. This is done using the init command: “<em>terraform init</em>”</p><p>We can now configure our infrastructure components.</p><h3>Terraform Code</h3><p>We will use HCL in this project primarily for writing configuration files that describe the desired state of infrastructure components, such as servers, networks, storage, and more. These configuration files are then processed by HashiCorp tools to provision and manage the corresponding resources in cloud providers such as AWS.</p><p>If you are not yet familiar with HCL, it stands for <strong>H</strong>ashiCorp <strong>C</strong>onfiguration <strong>L</strong>anguage and is a domain-specific language (DSL) developed by <a href="https://www.hashicorp.com/">HashiCorp</a>, a company known for creating various infrastructure automation tools like Terraform, Vault, and Consul. HCL is designed specifically for defining and configuring infrastructure resources in a clear and human-friendly manner.</p><p>HCL has a simple and declarative syntax that focuses on readability and ease of understanding. It is designed to be less verbose than traditional programming languages, and also supports a wide range of data types, expressions, and built-in functions to help define and manipulate configurations in an effective manner</p><p>Since we have already initialized our Terraform configuration earlier, we can start coding the rest of the infrastructure</p><p>Here is the entire code for our main.tf</p><pre>data &quot;aws_s3_bucket&quot; &quot;bucket&quot; {<br>  bucket = var.s3_bucket_name<br>}<br><br>data &quot;aws_kms_key&quot; &quot;log_key&quot; {<br>  key_id = var.kms_key_id<br>}<br><br>data &quot;aws_caller_identity&quot; &quot;current&quot; {}<br><br>resource &quot;aws_route53_zone&quot; &quot;transfer_family_landing_zone&quot; {<br>  name = &quot;my-domain.com&quot;<br>}<br>resource &quot;aws_route53_record&quot; &quot;sftp_record&quot; {<br>  zone_id = aws_route53_zone.transfer_family_landing_zone.zone_id<br>  name    = &quot;sftp.my-domain.com&quot;<br>  type    = &quot;CNAME&quot;<br>  ttl     = 300<br><br>  records = [aws_transfer_server.sftp_server.endpoint]<br>}<br><br>resource &quot;aws_transfer_tag&quot; &quot;with_custom_domain_route53_zone_id&quot; {<br>  resource_arn = aws_transfer_server.sftp_server.arn<br>    key          = &quot;aws:transfer:customHostname&quot;<br>    value        = &quot;sftp.my-domain.com&quot;<br>}<br><br>resource &quot;aws_kms_key&quot; &quot;service-key&quot; {<br>  description           = &quot;Service key used for SNS encryption&quot;<br>  policy                = data.aws_iam_policy_document.kms_key_policy.json<br>  enable_key_rotation   = true<br>  deletion_window_in_days = 7<br><br>  tags = {<br>    Name = var.service_kms_key_alias<br>    Environment = var.tags_environment<br>  }<br>}<br><br>resource &quot;aws_kms_alias&quot; &quot;service-key-alias&quot; {<br>  name          = &quot;alias/${var.service_kms_key_alias}&quot;<br>  target_key_id = aws_kms_key.service-key.key_id<br>}<br><br>resource &quot;aws_sns_topic&quot; &quot;s3_upload_sns_topic&quot; {<br>  name = &quot;s3_upload_sns_topic&quot;<br>  display_name = &quot;My SNS Topic&quot;<br>  policy = data.aws_iam_policy_document.topic.json<br>  kms_master_key_id = aws_kms_key.service-key.key_id<br>}<br><br>resource &quot;aws_sns_topic_subscription&quot; &quot;s3_upload_sns_topic_subscription&quot; {<br>  topic_arn = aws_sns_topic.s3_upload_sns_topic.arn<br>  protocol  = &quot;email&quot;<br>  endpoint  = var.my_email<br>}<br><br>resource &quot;aws_s3_bucket_notification&quot; &quot;bucket_notification&quot; {<br>  bucket = data.aws_s3_bucket.bucket.id<br><br>  topic {<br>    topic_arn     = aws_sns_topic.s3_upload_sns_topic.arn<br>    events        = [&quot;s3:ObjectCreated:*&quot;]<br>    filter_suffix = &quot;.csv&quot;<br>  }<br>}<br><br>resource &quot;aws_transfer_server&quot; &quot;sftp_server&quot; {<br>  identity_provider_type = &quot;SERVICE_MANAGED&quot;<br>  endpoint_type          = &quot;PUBLIC&quot;<br><br>  protocols    = var.protocols //SFTP (SSH File Transfer Protocol) - file transfer over Secure Shell<br>  logging_role = aws_iam_role.sftp_logging_role.arn<br>  structured_log_destinations = [<br>    &quot;${aws_cloudwatch_log_group.log_group.arn}:*&quot;<br>  ]<br>  <br>  tags = {<br>    Name        = var.tags_name<br>    Environment = var.tags_environment<br>  }<br>}<br><br>resource &quot;aws_cloudwatch_log_group&quot; &quot;log_group&quot; {<br>  name              = &quot;/aws/transfer/sftp_server&quot;<br>  retention_in_days = 3<br>  kms_key_id        = data.aws_kms_key.log_key.arn // Security check will throw an error if log group is not encrypted<br>}<br><br># Attach the IAM policy to the role<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;transfer_role_attachment&quot; {<br>  policy_arn = aws_iam_policy.sftp_role_policy.arn<br>  role       = aws_iam_role.transfer_role.name<br>}<br><br>resource &quot;aws_transfer_user&quot; &quot;sftp_user&quot; {<br>  for_each       = toset(var.sftp_user_names)<br>  server_id      = aws_transfer_server.sftp_server.id<br>  user_name      = each.key<br>  home_directory = &quot;/${data.aws_s3_bucket.bucket.id}/${each.key}&quot;<br>  role           = aws_iam_role.transfer_role.arn<br>}<br><br>resource &quot;aws_transfer_ssh_key&quot; &quot;sftp_user_ssh_key&quot; {<br>  for_each  = var.sftp_user_ssh_keys<br>  server_id = aws_transfer_server.sftp_server.id<br>  user_name = aws_transfer_user.sftp_user[each.key].user_name<br>  body      = each.value<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;sftp_logging_policy_attachment&quot; {<br>  policy_arn = aws_iam_policy.sftp_logging_policy.arn<br>  role       = aws_iam_role.sftp_logging_role.name<br>}</pre><p>The above code takes care of provisioning all the components described in the architecture earlier, with variables being declared in variables.tfand their respective values set in terraform.tfvars</p><p>Please note that terraform.tfvars is excluded from version control via .gitignore for various reasons:</p><ul><li><strong>Sensitive Information</strong>: terraform.tfvars often contains sensitive information such as API keys, access tokens, passwords, and other credentials that are required for infrastructure to interact with external services (e.g., cloud providers, databases, APIs).</li><li><strong>Separation of Concerns</strong>: Keeping configuration separate from sensitive data promotes a clear separation of concerns.</li><li><strong>Environmental Flexibility</strong>: Different environments (development, staging, production) require different values for variables. Consider having dev.tfvars, test.tfvars andprod.tfvars for each environment and keep these files out of version control.</li><li><strong>Automation and CI/CD</strong>: Excluding sensitive data ensures that automated processes do not expose secrets to potential security risks.</li></ul><p>The next stage of our workflow is to plan for the change and then apply them. This is done through two of the most used Terraform command, respectively “<a href="https://developer.hashicorp.com/terraform/cli/commands/plan"><em>terraform plan</em></a>” and “<a href="https://developer.hashicorp.com/terraform/cli/commands/apply"><em>terraform apply</em></a>”</p><pre>terraform plan -out tfapply # Generates an execution plan for your infrastructure changes and saves it to a file</pre><pre>terraform apply -auto-approve tfapply # Apply changes to your infrastructure based on a previously generated execution plan</pre><p>That’s it! We have deployed our infrastructure on AWS. The code included in the outputs.tfwill display the actual values of our deployed infrastructure</p><blockquote>While using-auto-approvemakes things easier, we are only using it in the context of Terraform being called from a terminal window. In a real scenario, this step will require manual approval via an automated pipeline. If you still want to use it, then make sure that no one can change your infrastructure outside of your Terraform workflow. This minimizes the risk of unpredictable changes and configuration drift.</blockquote><h3>Automating Infrastructure Deployment</h3><p>To orchestrate the deployment, I am using CircleCI in this project for a change (GitLab is great too if you prefer to use it)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcR2VpHDz0SoNEvA3kv1uA.png" /></figure><h3>CircleCI Configuration</h3><p>To configure CircleCI to perform builds, we will use the GitHub integration. CircleCI uses YAML for it’s pipeline configuration which we need to create in our project by adding a folder called “<em>.circleci</em>” and a “config.yml” inside of it</p><p>After committing the changes to GitHub, follow these steps to continue with the setup:</p><ol><li>Sign-up on CircleCI using your GitHub credentials, that will automatically load all your repositories</li><li>Click on “Set Up Project” next to the relevant repository and follow the steps.</li><li>CircleCI will automatically detect a .circleci/config.yml on your main branch and under the “Fastest” option. You can also commit a started CI pipeline to a new branch, or select from an existing template. <a href="https://circleci.com/docs/sample-config/">This page</a> provides a great resource for sample pipelines to get you started</li><li>Navigate to the Project Settings/Environment Variables and make sure you add all the variables needed that we defined on the main.tfand the other Terraform files. In addition to those, you will need to include your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY for the credentials created in the beginning to interact with AWS resources. Just make sure you grant the least privileges required corresponding with the type of resources we will mange in this project</li><li>You can optionally configure additional settings including triggers, email notifications and Slack or Jira integration</li></ol><p>The moment has come to enhance our pipeline by implementing the intended workflow. The provided CircleCI pipeline configuration describes the sequence of actions required to coordinate the deployment procedure, verify the infrastructure, and obtain authorization prior to implementing any modifications. Now, let’s dig into the main steps of this configuration:</p><h4>Orbs and Jobs</h4><ul><li>The tfsec orb is used for security scanning of your Terraform code. It ensures that our infrastructure adheres to best practices and security standards. Other security-first scanners are available including JFrog, SonarQube, Terrascan, etc…</li><li>The plan-apply job initializes, formats, and plans our Terraform deployment.</li><li>The tfsec-check job scans Terraform code for security vulnerabilities.</li><li>The apply job applies the changes to our infrastructure.</li><li>The plan-destroy job creates a destroy plan to safely remove the infrastructure.</li><li>The destroy job performs the actual destruction of the infrastructure.</li></ul><h4>Workflows</h4><p>The terraform_plan_apply_destroy_sftp workflow orchestrates the pipeline execution and uses two steps to seek approval, hold-apply job pauses for manual approval after security scanning while hold-destroy job pauses for manual approval before destroying the infrastructure.</p><h3>tfsec Integration</h3><p>Incorporating security checks into CI/CD pipelines is essential to prevent vulnerabilities and ensure the robustness of our infrastructure code. To achieve this, we’ll integrate the tfsec security scanner into your existing CircleCI configuration.</p><p>The tfsec orb is a great addition to our pipeline. It scans your Terraform code for potential security issues, configuration errors, and adherence to best practices. This proactive approach helps identify and address security concerns before deploying your infrastructure.</p><pre>orbs:<br>  tfsec: mycodeself/tfsec@1.1.0</pre><pre>jobs:<br>  tfsec-check:<br>    executor: tfsec/default<br>    steps:<br>      - checkout<br>      - tfsec/scan:<br>          directory: .</pre><p>In the above code snippet, we define the tfsec-check job using the tfsec orb. This job utilizes the executor provided by the orb and performs a scan on your Terraform code within the specified directory.</p><h3>Full Pipeline</h3><pre>version: 2.1<br>orbs:<br>  tfsec: mycodeself/tfsec@1.1.0<br>jobs:<br>  plan-apply:<br>    working_directory: /tmp/project<br>    docker:<br>      - image: docker.mirror.hashicorp.services/hashicorp/terraform:light<br>    steps:<br>      - checkout<br>      - run:<br>          name: Terraform - fmt, Init and Plan<br>          command: |<br>            terraform fmt -recursive .<br>            terraform init -input=false<br>            terraform plan -out tfapply \<br>              -var=&quot;my_variable_1=${TF_VAR_variable_1}&quot; \<br>              -var=&quot;my_variable_2=${TF_VAR_variable_2}&quot;<br>      - persist_to_workspace:<br>          root: .<br>          paths:<br>            - .<br>  tfsec-check:<br>    executor: tfsec/default<br>    steps:<br>      - checkout<br>      - tfsec/scan:<br>          directory: .<br>  apply:<br>    docker:<br>      - image: docker.mirror.hashicorp.services/hashicorp/terraform:light<br>    steps:<br>      - attach_workspace:<br>          at: .<br>      - run:<br>          name: Terraform - Apply<br>          command: |<br>            terraform apply -auto-approve tfapply<br>      - persist_to_workspace:<br>          root: .<br>          paths:<br>            - .<br>  plan-destroy:<br>    docker:<br>      - image: docker.mirror.hashicorp.services/hashicorp/terraform:light<br>    steps:<br>      - attach_workspace:<br>          at: .<br>      - run:<br>          name: Terraform - Creating Destroy Plan<br>          command: |<br>            terraform plan -destroy -out tfdestroy<br>      - persist_to_workspace:<br>          root: .<br>          paths:<br>            - .<br>  destroy:<br>      docker:<br>        - image: docker.mirror.hashicorp.services/hashicorp/terraform:light<br>      steps:<br>        - attach_workspace:<br>            at: .<br>        - run:<br>            name: Terraform - Destroy<br>            command: |<br>              terraform apply -auto-approve tfdestroy<br><br>workflows:<br>  version: 2<br>  terraform_plan_apply_destroy_sftp:<br>    jobs:<br>      - plan-apply<br>      - tfsec-check:<br>          requires:<br>            - plan-apply<br>      - hold-apply:<br>          type: approval<br>          requires:<br>            - tfsec-check<br>      - apply:<br>          requires:<br>            - hold-apply<br>      - plan-destroy:<br>          requires:<br>            - apply<br>      - hold-destroy:<br>          type: approval<br>          requires:<br>            - plan-destroy<br>      - destroy:<br>          requires:<br>            - hold-destroy</pre><p>If everything goes well, once you commit your changes to GitHub, a webhook event will trigger a new build on CircleCI</p><p>You will be able to monitor the progress of the pipeline and approve certain steps within Visual Studio Code (if you installed and configured the VSC Extension)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neJyCaN3oAnarpZz6zbq8w.png" /><figcaption>CicleCI Pipeline Progress</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuuzeL9IxWW4_250jJUnog.png" /><figcaption>Different View of the Pipeline</figcaption></figure><p>There is also a nice Insights section that provides information on <strong>Metrics and Trends </strong>via a graphical representations of key performance and execution indicators related to the CI/CD pipelines such as build duration, success rates, and resource usage. These visualizations enable us to track trends over time and identify areas for improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D40YQ588SRLKmMPnwkBo-w.png" /><figcaption>Pipeline Insights</figcaption></figure><p>That’s it! I hope you enjoyed reading this article as much as i did while writing it. It is an immersive experience to have pieces of text to collate together on one screen in a way that makes sense and is consistent to readers, while having a bunch of tools, scripts and consoles open on another. It is two different activities that writing technical content brings together!</p><p>Thank you for reading and if you find this article insightful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Disclaimer</h3><p>All pictures, illustrations and diagrams featured in this work are credited to the author, in alignment with their creative efforts and contributions to this content. Any resemblance to other works is purely coincidental. The author holds the rights to these visual elements, ensuring the authenticity and originality of their work.</p><h3>Useful Resources</h3><ul><li><a href="https://developer.hashicorp.com/terraform/cli/commands">Terraform CLI Commands</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">Hashicorp AWS Provider</a></li><li><a href="https://docs.aws.amazon.com/transfer/latest/userguide/what-is-aws-transfer-family.html">AWS Transfer Family Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58915cab8bec" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/aws-infrastructure-orchestration-with-terraform-and-circleci-58915cab8bec">AWS Infrastructure Orchestration with Terraform and CircleCI</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Speech-to-Text Transcription System using AWS Lambda and OpenAI Whisper]]></title>
            <link>https://towardsaws.com/building-a-speech-to-text-transcription-system-using-aws-lambda-and-openai-whisper-d670e85fa8fc?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/d670e85fa8fc</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 11:04:57 GMT</pubDate>
            <atom:updated>2023-04-27T14:32:07.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*BiKuW3wwUOw9yemLbkWNeg.png" /><figcaption>AWS Lambda and OpenAI</figcaption></figure><p>Speech-to-text transcription systems have become increasingly popular in recent years, and with good reason. They allow users to quickly and easily convert audio files into text, which can be edited, searched, and analyzed more easily than audio alone. In this article, we’ll walk through the steps required to build a speech-to-text transcription system using an event-driven architecture and automatic speech recognition.</p><h3>Overview</h3><p>Our system will consist of several AWS services that work together to transcribe audio files into text. Here’s a high-level overview of the architecture:</p><ol><li>User uploads audio file to S3 bucket</li><li>SNS topic sends notification to Lambda function written in C#</li><li>Lambda function retrieves audio file from S3 bucket</li><li>Lambda function performs API calls to OpenAI Whisper</li><li>OpenAI Whisper API processes audio file and returns the transcribed text</li><li>Transcription is stored back into S3 bucket</li><li>SQS queue message is submitted on success so that other services can be notified about the availability of the transcription file</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vyg_9UkDBihBfajgsCo5Fw.png" /><figcaption>Architecture diagram</figcaption></figure><p>OpenAI’s API is easy to use, we could actually just call it directly from a client app. So why the extras?</p><p>Aside from the obvious reasons of scalability, reliability and security when working with services designed to handle high levels of traffic and scale up or down as needed, where would be the fun then?!!!</p><p><strong>Scalability</strong>: By using AWS services like S3, SNS, and SQS, we can easily scale our system to handle a large volume of audio files. S3 for example is built using a distributed architecture that allows it to scale horizontally, allowing it to to handle an large number of requests per second and can store trillions of objects, with each object being up to 5 terabytes in size</p><p><strong>Reliability</strong>: AWS services are highly reliable and offer features like automatic failover and backups. By using these services, we can ensure that our transcription system is always available and that data is not lost. SNS for example supports Message Filtering, Delivery Retry and Dead Letter Queue in addition to the ability to implement a fan-out messaging pattern for broadcasting messages to multiple endpoints simultaneously</p><p>With that said, let’s go ahead and start deploying and configuring our components</p><h3>Infrastructure</h3><p>We will create two S3 buckets using the default settings, the first one called “raw-audio-to-process” will be used to store raw audio files (OpenAI Whisper supports formats such as mp3, mp4, mpeg, mpga, m4a, wav, or webm)</p><p>The second bucket will be used to store the processed transcription, we will call it “openai-audio-transcriptions”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*J3SAU764WN2fu6USV09h1A.png" /><figcaption>Creating an S3 bucket</figcaption></figure><p>Now, we move on to SNS where we will be creating a new topic. FIFO topics are <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-compatibility.html">not supported</a> as a target for S3 Events, so we will use a Standard type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*8fuxQy3h1z95QrSXNGatqA.png" /><figcaption>Creating an SNS topic</figcaption></figure><p>We need to allow Amazon S3 event notifications to publish to our topic by modifying the SNS access policy according to the following template:</p><pre>{<br>  &quot;Version&quot;: &quot;2008-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;s3.amazonaws.com&quot;<br>      },<br>      &quot;Action&quot;: &quot;sns:Publish&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:sns:us-east-1:[ACCOUNTID]:s3-upload-sns-topic&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringEquals&quot;: {<br>          &quot;aws:SourceArn&quot;: &quot;arn:aws:s3:::raw-audio-to-process&quot;<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>Now, lets connect the two services by adding our newly created SNS topic to the first S3 bucket, this can be done from the properties tab of the raw-audio-to-process bucket</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*UUMsVGOTFoFnu6LygNdESw.png" /><figcaption>S3 event notification</figcaption></figure><p>We will leverage the event filtering capabilities and only send out events whenever a new S3:ObjectCreated:Put happens and the file extension matches the .mp3 suffix. This way, we avoid triggering the entire workflow when irrelevant events happen (delete, update, multi-part uploads…)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*aEn3OQs0cL1dLddTz5lVNQ.png" /><figcaption>Set SNS as a destination for event notifications</figcaption></figure><p>Finally, we select the SNS topic as a destination. This is where the common errors prevent setting up event publishing to a topic:</p><ul><li><strong>Invalid SNS topic ARN</strong>: If you specify an invalid SNS topic ARN, S3 will not be able to deliver events to the topic. Make sure that the ARN is formatted correctly and that the topic actually exists.</li><li><strong>Insufficient permissions</strong>: In order for S3 to publish events to an SNS topic, it must have permission to do so. Make sure that the IAM role or user associated with the S3 bucket has the necessary permissions to publish messages to the SNS topic.</li><li><strong>Mismatched regions</strong>: If the S3 bucket and SNS topic are in different regions, S3 will not be able to deliver events to the topic. Make sure that the regions match.</li><li><strong>Disabled SNS topic</strong>: If the SNS topic has been disabled, S3 will not be able to publish events to it. Make sure that the topic is enabled and ready to receive messages.</li><li><strong>SNS topic has exceeded limits</strong>: If the SNS topic has exceeded its limits, S3 will not be able to publish events to it. Make sure that the topic has sufficient capacity to handle the number of events being sent to it.</li></ul><p>Once this is set, file uploads will now send out an S3 Event to the SNS topic, to be consumed later on by subscribers (Lambda function in this case)</p><p>Now, time to head to your favorite IDE and build our Lambda function</p><h3>Lambda Function</h3><p>The following libraries are required for this project</p><pre>using Amazon.Lambda.Core;<br>using Amazon.Lambda.S3Events;<br>using Amazon.Lambda.SNSEvents;<br>using Amazon.S3.Model;<br>using Amazon.S3;<br>using Amazon.S3.Util;<br>using static Amazon.Lambda.SNSEvents.SNSEvent;<br>using System.Net.Http.Headers;<br>using Amazon.SecretsManager;<br>using Amazon.SecretsManager.Model;<br>using Amazon;<br>using Newtonsoft.Json.Linq;<br>using Amazon.SQS;<br>using Amazon.SQS.Model;<br>using Newtonsoft.Json;</pre><p>Our entry point is a handler that takes an SNS Event and the current Lambda content. The SNS Event is a collection of records that will be processed by ProcessRecordAsync</p><pre>public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context)<br>    {<br>        foreach(var record in evnt.Records)<br>        {<br>            await ProcessRecordAsync(record, context);<br>        }<br>    }</pre><p>DownloadS3FileAsync is used to download a file from an S3 bucket and return a Stream object</p><pre>public async Task&lt;Stream&gt; DownloadS3FileAsync(string bucketName, string key)<br>    {<br>        using (var client = new AmazonS3Client())<br>        {<br>            var request = new GetObjectRequest<br>            {<br>                BucketName = bucketName,<br>                Key = key<br>            };<br>            var response = await client.GetObjectAsync(request);<br>            return response.ResponseStream;<br>        }<br>    }</pre><p>UploadFileToOpenAIAsync will handle uploading the raw audio file to OpenAI Whisper, and will return a text transcription asynchronously once the API call has completed</p><pre>public async Task&lt;string&gt; UploadFileToOpenAIAsync(Stream fileStream, string fileName, string apiKey, string apiUrl, string modelId)<br>    {<br>        using (var client = new HttpClient())<br>        {<br>            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, apiKey);<br>            var content = new MultipartFormDataContent();<br>            content.Add(new StreamContent(fileStream), &quot;file&quot;, fileName);<br>            content.Add(new StringContent(modelId), &quot;model&quot;);<br>            var response = await client.PostAsync(apiUrl, content);<br>            return await response.Content.ReadAsStringAsync();<br>        }<br>    }</pre><p>The following function will retrieve the encrypted OpenAI API key from AWS Secrets Manager</p><pre>static async Task&lt;string&gt; GetSecretValue()<br>    {<br>        string secretName = &quot;prod-OpenAI-API-Key&quot;;<br>        string region = &quot;us-east-1&quot;;<br>        IAmazonSecretsManager client = new AmazonSecretsManagerClient(RegionEndpoint.GetBySystemName(region));<br>        GetSecretValueRequest request = new GetSecretValueRequest<br>        {<br>            SecretId = secretName,<br>            VersionStage = &quot;AWSCURRENT&quot;,<br>        };<br>        GetSecretValueResponse response;<br>        try<br>        {<br>            response = await client.GetSecretValueAsync(request);<br>        }<br>        catch (Exception e)<br>        {<br>            // Handle exception<br>            throw;<br>        }<br>        var json = JObject.Parse(response.SecretString);<br>        var secretValue = (string)json[&quot;OpenAI-APIKey&quot;]!;<br>        return secretValue;<br>    }</pre><p>SendMessageToSQS will publish a message to a queue to be consumed later by third party services</p><pre>public async Task SendMessageToSQS(string messageBody, string queueUrl)<br>    {<br>        var sqsClient = new AmazonSQSClient();<br><br>        var request = new SendMessageRequest<br>        {<br>            QueueUrl = queueUrl,<br>            MessageBody = messageBody<br>        };<br>        try<br>        {<br>            var response = await sqsClient.SendMessageAsync(request);<br>            //context.Logger.LogLine($&quot;Message sent to SQS queue: {response.MessageId}&quot;);<br>        }<br>        catch (Exception e)<br>        {<br>            //context.Logger.LogLine($&quot;Error sending message to SQS queue: {e.Message}&quot;);<br>        }<br>        await Task.CompletedTask;<br>    }</pre><p>Finally, our main method will be responsible for calling the various functions and process data and results</p><pre> private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)<br>    {<br>        context.Logger.LogInformation($&quot;Processed record {record.Sns.Message}&quot;);<br>        S3EventNotification _s3Event = S3EventNotification.ParseJson(record.Sns.Message);<br>        string? _fileName = _s3Event.Records[0].S3.Object.Key;<br>        string? _bucket = _s3Event.Records[0].S3.Bucket.Name;<br>        long _size = _s3Event.Records[0].S3.Object.Size;<br>        context.Logger.LogLine($&quot;A new file {_fileName} in bucket {_bucket} has been uploaded, the size is {_size}&quot;);<br>        var stream = await DownloadS3FileAsync(_bucket, _fileName);<br>        if (stream == null)<br>        {<br>            context.Logger.LogLine(&quot;The downloaded stream is null&quot;);<br>            return;<br>        }<br>        else<br>        {<br>            context.Logger.LogLine($&quot;The downloaded stream size is {stream.Length}&quot;);<br>        }<br>        var transcription = await UploadFileToOpenAIAsync(stream!, &quot;my-file.mp3&quot;, GetSecretValue().Result, &quot;https://api.openai.com/v1/audio/transcriptions&quot;, &quot;whisper-1&quot;);<br>        context.Logger.LogLine($&quot;The transcription is {transcription}&quot;);<br><br>        // Saving the stream into a text file<br>        var resultStream = new MemoryStream();<br>        var writer = new StreamWriter(resultStream);<br>        writer.Write(transcription);<br>        writer.Flush();<br>        resultStream.Position = 0;<br><br>        // Uploading the text file to a new S3 bucket<br>        var newS3Client = new AmazonS3Client();<br>        var newBucketName = &quot;openai-audio-transcriptions&quot;;<br>        var newObjectName = $&quot;transcription-{_fileName}.txt&quot;;<br>        var request = new PutObjectRequest<br>        {<br>            BucketName = newBucketName,<br>            Key = newObjectName,<br>            InputStream = resultStream<br>        };<br>        var putResult = await newS3Client.PutObjectAsync(request);<br>        if (putResult != null)<br>        {<br>            context.Logger.LogLine($&quot;The transcription upload result is {putResult!.HttpStatusCode}&quot;);<br>        }<br>        string queueUrl = &quot;https://sqs.us-east-1.amazonaws.com/ACCOUNTID/sqs-queue&quot;;<br><br>        var message = new<br>        {<br>            S3Bucket = _bucket,<br>            S3Key = _fileName,<br>            Transcription = newObjectName,<br>            Timestamp = DateTime.UtcNow<br>        };<br>        var messageBody = JsonConvert.SerializeObject(message);<br>        await SendMessageToSQS(messageBody, queueUrl);<br>    }</pre><p>Some of the most common errors encountered when performing calls to OpenAI Whisper are:</p><p><strong>Error: 400 Bad Request — you must provide a model parameter</strong></p><p>Ensure that you have selected the correct body type on your http request, and that the model parameter is written exactly as this: model</p><p><strong>Error: 400 Bad Request — 1 validation error for Request\nbody -&gt; file\n field required (type=value_error.missing)</strong></p><p>Same as above, and the file parameter is written exactly as this: file</p><p><strong>Error: Maximum content size limit (26214400) exceeded (38874347 bytes read)</strong></p><p>The maximum supported file size is 25 MB</p><h3>Testing and Deployment</h3><p>We are now ready to start testing our function. AWS has done a great job by providing the Mock Lambda Test Tool as part of the AWS Toolkit for Visual Studio</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*GlYtMUPkYN7MQ3tl5FJMyg.png" /><figcaption>Publish Lambda - step 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*ZsPdyZjcZX2y_2KMvt2H5A.png" /><figcaption>Publish Lambda - step 2</figcaption></figure><p>We’re almost there! We just need to setup a couple of things and then we’re done:</p><p><strong>Setup the proper access permissions for our Lambda function</strong></p><ul><li>S3 GetObject and PutObject</li><li>SQS SendMessage</li><li>CloudWatch CreateLogGroup, CreateLogStream and PutLogEvents</li><li>Secret Manager Read and Write</li><li>SNS lambda:InvokeFunction</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QE3C4TWSkkfgOb5oJZuhKA.png" /><figcaption>Lambda function overview</figcaption></figure><p><strong>Create an SQS queue that will receive notifications from the Lambda function</strong></p><p>Again, we need to make sure that SQS queue has the proper access controls set to enable Lambda publishing messages to it:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Id&quot;: &quot;__default_policy_ID&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;__owner_statement&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;lambda.amazonaws.com&quot;<br>      },<br>      &quot;Action&quot;: &quot;SQS:*&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:sqs:us-east-1:[ACCOUNTID]:sqs-queue&quot;<br>    }<br>  ]<br>}</pre><h3>The moment of truth!</h3><p>Let’s upload an mp3 file containing speech and see what happens:</p><ol><li>The file is uploaded to the S3 bucket which triggers an S3Event being sent to the SNS topic</li><li>SNS receives the event payload and delivers it to our Lambda function, which is a subscriber</li><li>The magic happens within the Lambda function, downloads the file in question, performs the request to OpenAI, retrieves and text transcription, stores in back on S3 and finally publishes a message to SQS with a custom payload</li></ol><p>Looking at CloudWatch, you will see various events being logged, including the file SNS Event that wraps an S3 Event payload, a copy of the transcript once received and a confirmation that the text has been uploaded to the second S3 bucket (all coming from the Lambda function)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SwT2fciwMkC3RI4G6KaKQ.png" /><figcaption>CloudWatch Lambda log group</figcaption></figure><h3>Overkill?</h3><p>This article focuses on a common event driven architecture that can be leveraged for many use cases such as image and video processing, real-time analytics, image recognition and chatbots. However, depending on specific situations, going with a simpler design would make more sense. There is actually an AWS service called <a href="https://aws.amazon.com/transcribe/">Transcribe</a>, which in many cases would do the job just fine by itself, but when integrated with other AWS services, we would be making sure that our system is going to handle increased volumes of data and requests, respond to events in real-time, and trigger other services and applications based on those events</p><p>In terms of reliability, S3 and SNS are designed to be fault-tolerant, and Lambda functions can be set up to automatically retry in the event of an error or failure.</p><p>Customization is a huge advantage as well, and by using a similar design for our system, we can customize the way that a Transcribe service (Whisper, AWS or other) processes data. For example, we can use Lambda functions to perform pre-processing tasks such as removing noise from audio recordings or segmenting text data into smaller chunks, which can help to improve the accuracy of our transcription results</p><h3>What next?</h3><p>These are just a few ideas on what to do with transcriptions and how AWS services can be leveraged. Depending on your specific use case, there may be other AWS services that can be used to further enhance our transcription workflow</p><ul><li><strong>Store transcripts in </strong><a href="https://aws.amazon.com/dynamodb/"><strong>DynamoDB</strong></a>: We can store the transcription text along with metadata such as the audio file name, transcription status, and timestamp in DynamoDB. This will allow us to easily query and retrieve transcriptions based on specific criteria, use the generated text as meta-data for products such as audio-books, etc</li><li><strong>Analyze transcripts using </strong><a href="https://aws.amazon.com/comprehend/"><strong>Amazon Comprehend</strong></a><strong>:</strong> Amazon Comprehend is a natural language processing (NLP) service that can be used to analyze and extract insights from transcripts. Common use cases include performing sentiment analysis, topic modeling, and entity recognition</li><li><strong>Use </strong><a href="https://aws.amazon.com/translate/"><strong>Amazon Translate</strong></a>: Amazon Translate is a fully managed neural machine translation service. It uses advanced deep learning techniques to provide high-quality, real-time language translation in multiple languages that we can leverage in this case to automatically translate transcriptions into multiple languages, using the same Even Driven Architecture and Asynchronous operations and mechanisms used so far in this solution</li><li><strong>Use </strong><a href="https://aws.amazon.com/opensearch-service/"><strong>Amazon Open Search</strong></a><strong> to index and search transcripts:</strong> Amazon Open Search is a fully managed search and analytics engine (based on Elastic Search) that can be used to index and search through large volumes of text data. We can use it to index text and provide a full-text search experience based on keywords or specific phrases</li></ul><p>I hope you enjoyed reading this article, thank you for reading and if you find this article useful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Disclaimer</h3><p>Credit goes to any cited articles or illustration/diagram owners</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d670e85fa8fc" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/building-a-speech-to-text-transcription-system-using-aws-lambda-and-openai-whisper-d670e85fa8fc">Building a Speech-to-Text Transcription System using AWS Lambda and OpenAI Whisper</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Site-to-Site VPN between OCI and AWS]]></title>
            <link>https://towardsaws.com/site-to-site-vpn-between-oci-and-aws-9d84071eaa8c?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d84071eaa8c</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[oracle-cloud]]></category>
            <category><![CDATA[vpn]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 05:27:32 GMT</pubDate>
            <atom:updated>2023-04-13T09:09:52.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*RYPmep9PrA8jp0saPFDkMg.jpeg" /></figure><p>Welcome to the exciting world of VPN connections! In today’s digital age, interconnecting various networks and infrastructures has become a necessity, and VPN tunnels are the backbone of secure communication over the internet.</p><p>In this Medium article, we’ll dive into the nitty-gritty details of setting up a site-to-site IPSec VPN connection tunnel between Oracle Cloud Infrastructure (OCI) and Amazon Web Services (AWS), and in an upcoming chapter, we’ll be walking you through the process of setting up compute instances on both sides: a client on OCI and a web server on AWS hosting REST API based on .NET Framework</p><p>But why is this important, you ask? Well, imagine your organization’s main infrastructure host is hosted on OCI, and you need to securely communicate with an on-premises data center of a financial institution that provides APIs and file exchange services through a secure channel. This is where a site-to-site VPN connection comes in handy, allowing for secure and reliable communication between the two networks.</p><p>Throughout this article, we’ll cover everything from setting up the IPSec tunnel, configuring the compute instances, and testing the connection to ensure everything is working as it should. So, whether you’re a seasoned network administrator or just starting, we’ve got you covered with this comprehensive guide.</p><p>So, grab a cup of coffee, sit back, and let’s dive into it!</p><h3>Why API’s through VPN?</h3><p>Oh, why would a financial institution want to expose its API’s publicly? I mean, who wouldn’t want to give all those curious developers and hackers out there free rein to poke around in their sensitive financial data? And heaven forbid that they might actually have to verify the identity of the third-party entities that want to connect to their systems. I mean, what could possibly go wrong with allowing anyone and everyone to access their APIs?</p><p>No, no, no. Much better to restrict access to those APIs through a pre-validated process and IPSec VPN. That way, they can make sure that only authorized parties can access their systems and that all connections are secure. Because we all know that verifying identities and using secure connections is just such a hassle. Who wants to go through all that trouble when they could just leave the front door wide open and hope that no one walks in?</p><p>In short, financial institutions should definitely not bother with securing their APIs or restricting access to authorized parties. It’s much more fun to live on the edge and hope that nothing bad happens. After all, what’s the worst that could happen?</p><p>On a more serious note, organizations usually go this route mainly for security and compliance reasons, here are some points they usually consider:</p><ul><li><strong>Protect sensitive financial data</strong>: Financial institutions hold a lot of sensitive customer data, such as bank account numbers, transaction details, and personal identifying information. By restricting API access to authorized third-party entities, they can help ensure that this data is protected from unauthorized access and misuse.</li><li><strong>Limit attack surface</strong>: Opening APIs publicly to anyone can increase the attack surface and make it easier for hackers to find vulnerabilities and exploit them. By restricting access to authorized entities, financial institutions can limit the potential attack surface and reduce the risk of data breaches.</li><li><strong>Verify the identity of third-party entities</strong>: By using a pre-validated process to connect third-party entities, financial institutions can verify the identity of those entities and ensure that they are trustworthy before allowing them to access their systems. This helps reduce the risk of unauthorized access and fraudulent activity.</li><li><strong>Enforce security standards</strong>: By requiring connections to be made via IPSec VPN, financial institutions can enforce security standards for connections to their APIs. IPSec VPN provides secure encryption and authentication, which helps ensure that data is transmitted securely and that only authorized entities can access the API.</li><li><strong>Compliance requirements</strong>: Financial institutions are subject to a variety of regulatory requirements related to data security and privacy. Restricting API access to authorized entities and using secure connections helps ensure compliance with these requirements and avoids them costly fines or legal action.</li></ul><h3>The Architecture</h3><p>This architecture connects Oracle Cloud Infrastructure (OCI) and Amazon Web Services (AWS) using native IPSec VPN appliances.</p><p>It involves creating a Virtual Cloud Network (VCN) with three subnets on OCI’s side, one for the public internet-facing resources, one for the private resources, and one for the VPN appliances.</p><p>On the AWS side, a Virtual Private Cloud (VPC) is created with a similar number of subnets. An Internet Gateway is deployed on each side to provide access to the public internet-facing resources. A DRG is created on OCI’s side to connect to the AWS VPN and a VPG is created on AWS’s side to connect to the OCI VPN.</p><p>Routing tables are then configured on both sides to route traffic between the private subnets through the VPN connection.</p><p>Compute instances are deployed in both private subnets to test connectivity, and security rules are configured to allow traffic between the private subnets and deny traffic from the public subnets.</p><p>To summarize, we will be dealing with the following types of components</p><ul><li>VPC and VCN</li><li>Subnets and Routing tables</li><li>Dynamic Routing Gateway</li><li>Virtual Private Gateway</li><li>Customer-Premises Equipment</li><li>Customer Gateway</li><li>IPSec Connectivity</li></ul><h3>Setup on AWS</h3><p>To begin, it’s important to ensure that the CIDR block of your Oracle Cloud Infrastructure (OCI) Virtual Cloud Network (VCN) does not overlap with the CIDR block of the Amazon Web Services (AWS) Virtual Private Cloud (VPC). Lets go ahead a create a brand new VPC using the CIDR block 172.32.0.0/16</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*S9msXHyjsjFZvvUYbxlGBw.png" /><figcaption>Creating our VPC on AWS</figcaption></figure><p>Next, we will setup three subnets on the new VPC</p><p><strong>Subnet-01: 172.32.0.0/24</strong></p><ul><li>This subnet uses the first 24 bits to represent the subnet, leaving 8 bits for the hosts.</li><li>The valid IP addresses for hosts within this subnet are 172.32.0.1 to 172.32.0.254.</li></ul><p><strong>Subnet-02: 172.32.1.0/24</strong></p><ul><li>This subnet uses the first 24 bits to represent the subnet, leaving 8 bits for the hosts.</li><li>The valid IP addresses for hosts within this subnet are 172.32.1.1 to 172.32.1.254.</li></ul><p><strong>Subnet-03: 172.32.2.0/24</strong></p><ul><li>This subnet uses the first 24 bits to represent the subnet, leaving 8 bits for the hosts.</li><li>The valid IP addresses for hosts within this subnet are 172.32.2.1 to 172.32.2.254.</li></ul><p>Note that the first IP address in each subnet is reserved for the network address, and the last IP address in each subnet is reserved for the broadcast address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqhsBVnnqYBo3BPVDblgyw.png" /><figcaption>Creating our subnets on AWS</figcaption></figure><p>Now, we can continue our AWS simulating the financial organization’s On-Prem DC hosting REST API’s. Let’s create a dummy Customer Gateway that we will replace later on with the actual one, once we have setup the required components on OCI as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*PnQbIFtqKUnddMiQtmp-Lg.png" /><figcaption>Creating a dummy Customer Gateway on AWS</figcaption></figure><p>Then, we will create a VPG which is the equivalent of a Dynamic Routing Gateway on OCI and attach it to our new VPC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*8AGGixlCFa0i4TUVOPd8jg.png" /><figcaption>Creating a VPG on AWS</figcaption></figure><p>Attaching the VPG to our VPC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*tRo2B27P458X_20f4tAlhw.png" /><figcaption>Attaching our VPG to the VPC</figcaption></figure><p>Once attached, we can now go ahead and move forward with the IPSec connection step. Go to “Site-to-Site VPN connections” on the AWS console and select “<strong>Create VPN connection</strong>”</p><p>We will select our VPG and dummy Customer Gateway, keep most of the settings as default. However, we need to make sure that the format of the Pre-Shared Key complies with OCI’s requirements, which only accepts alphanumeric characters and does not allow special characters such as underscores or even dots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*xGx7tZu0hX3Z_xJt77f0jg.png" /><figcaption>Creating the IPSec connection</figcaption></figure><p>Here, we are instructing AWS to use the provided Pre-shared key instead of generating one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*6xb0ZlNU5mtzgJckXL5gCg.png" /><figcaption>Using a custom Pre-shared key on AWS IPSec connection</figcaption></figure><p>We will now wait until the newly created VPN connection is provisioned and in the “Available” state, then we can download the configuration file using the “Generic” vendor options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*qf0JbCabKuK6TYM8QM6A7Q.png" /><figcaption>Downloading the VPN Configuration</figcaption></figure><p>The downloaded file will contain important information we need in order to setup the tunnel on the OCI side</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1JUwd5MI_lnqIhsaCZtew.png" /><figcaption>AWS VPN Configuration</figcaption></figure><h3>Setup on OCI</h3><p>First, we will create a Customer Premises Equipment (CPE) and we will use the public IP 3.220.251.49 for the AWS VPG from the downloaded configuration file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*UH3d-8IMrFk50E9E5rcByQ.png" /><figcaption>Virtual representation of a Customer-Premises Equipment on OCI</figcaption></figure><p>Next, we will create a Dynamic Routing Gateway, or you can use an existing one if you have created a DRG previously</p><p>Finally, we will now create our IPSec VPN connection using our CPE and DRG</p><p>In this article, we will only focus on the Tunnel 1 connection, however it is important to enable the second tunnel in a production environment to make sure the VPN connectivity is redundant</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ClZAYzjB45ko4yGj4uSbQ.png" /><figcaption>Creating the IPSec connection on OCI</figcaption></figure><p>Let’s expand the Tunnel 1 configuration and <strong>re-use the same Pre-Shared Key</strong> we used on the AWS configuration. You will find the PSK on the downloaded configuration file under “<strong>IPSec Tunnel #1</strong>” configuration details</p><p>We also need to fill out the following details that we can take from the same configuration file</p><ul><li><strong>BGP ASN</strong>: Corresponds to “BGP Configuration Options\Virtual Private Gateway ASN”</li><li>I<strong>Pv4 inside tunnel interface — CPE</strong>: Corresponds to “Inside IP Addresses\Virtual Private Gateway”</li><li><strong>IPv4 inside tunnel interface — Oracle</strong>: Corresponds to “Inside IP Addresses\Customer Gateway”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jH7cN_jjpclkLdL4RvBVpg.png" /></figure><p>Once done, the status of both tunnels will show as “DOWN” and we are now almost done with the OCI configuration.</p><p>Let’s copy the following parameters “Tunnel 1 IP” and “Oracle BGP ASN” and use them on the AWS configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwMfGGrz1Gxod9IZmjRBtQ.png" /><figcaption>The Oracle VPN Public IP for the first Tunnel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5xQyrCKM4YL8tzbGu8tlg.png" /><figcaption>Oracle BGP ASN</figcaption></figure><p>Remember our dummy Customer Gateway on AWS with IP 1.1.1.1, now is the time to create the actual one using the above values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*nKAX8iztCchJYpe9MovELQ.png" /><figcaption>Creating the actual Customer Gateway using BGP ASN and IP from OCI VPN</figcaption></figure><p>Once done, we need to modify the AWS VPN Connection to use the newly created Customer Gateway. It usually takes some time to complete the change and once done, it will change from “modifying” to “available” status</p><p>At this point, Tunnel 1 on either OCI or AWS will show as “UP”, and the final steps to complete the configuration is to</p><ul><li>Configure routing on AWS so that our Virtual Private Gateway (VPG) is designated as the target for the Classless Inter-Domain Routing (CIDR) associated with the Oracle Virtual Cloud Network (VCN), which is in this case 10.1.0.0/16</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLImOOKC1b_lmOkj44xwPg.png" /><figcaption>Update the AWS VPC routing table</figcaption></figure><ul><li>Perform the same on OCI VCN route table by adding the route to the AWS VPC, using the DRG as a target type</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mipsR-baylmeRFreN-HTpQ.png" /><figcaption>Update the OCI VCN routing table</figcaption></figure><h3>That’s it, we are done!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPxj_EVAd7YOBcLvrxahvQ.png" /><figcaption>Tunnel 1 Up on OCI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Deo5k0VEz1C8a14MJT1Jtg.png" /><figcaption>Tunne 1 Up on AWS</figcaption></figure><p>Time to test our connection now, let’s launch compute instances on each side of the tunnel and SSH to both</p><blockquote>Obviously, an Internet Gateway has to be deployed and attached to the VPC/VCN, otherwise you won’t be able to SSH using the respective instances public IP’s. Also, make sure that Security Groups (AWS) and Security Lists/Network Security Groups(OCI) are configured properly to allow SSH ingress traffic</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bctLqugETGWSvaYpAEKhrA.png" /></figure><p>On the left is an OCI compute instance showing Pings to the target, and on the right is an EC2 instance showing the incoming sources for all ICMP traffic. Pinging from the compute instance to the EC2 using it’s private IP 172.32.0.213 is working properly</p><p>If it doesn’t work for you, make sure that you update the Security Group of the target EC2 by adding ICMP (TCP 22)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKs7ON_V6tBQIQyYKmgGGg.png" /><figcaption>Security Group changes on AWS</figcaption></figure><p>Don’t forget to delete all the created resources to avoid unnecessary charges!</p><p>In the next chapter, we will be configuring a DevOps CI/CD pipeline in order to ship containerized code into an AWS EC2 using tools such as Microsoft Azure DevOps, and performing calls via HTTPS to the REST API from an OCI compute instance, so stay tuned!</p><p>I hope you enjoyed reading this article, thank you for reading and if you find this article useful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Disclaimer</h3><p>Credit goes to any cited articles or illustration/diagram owners</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d84071eaa8c" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/site-to-site-vpn-between-oci-and-aws-9d84071eaa8c">Site-to-Site VPN between OCI and AWS</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability with Prometheus and Grafana]]></title>
            <link>https://towardsaws.com/observability-with-prometheus-and-grafana-c0d589220c0b?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0d589220c0b</guid>
            <category><![CDATA[visualisation]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 18:20:41 GMT</pubDate>
            <atom:updated>2022-12-12T22:31:05.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7bp6nohVbgOlHJUw6IfS8w.png" /><figcaption>A Grafana dashboard as imagined by AI text2img</figcaption></figure><p>Prometheus and Grafana are two popular open-source tools that are commonly used for monitoring and observability. While Prometheus is a time-series database that collects and stores metrics data, Grafana is a visualization tool that allows users to create dashboards and charts based on that data.</p><p>Prometheus was first developed at <a href="https://soundcloud.com/">SoundCloud</a>, the popular music and audio distribution website in 2012, and it has since become one of the most widely-used <strong>monitoring</strong> tools in the industry. It is a highly scalable and efficient system that is able to collect and store millions of metrics from different sources. Prometheus uses a pull-based model to collect data, which means that it actively queries various targets to gather the metrics it needs. This allows it to be very flexible and adaptable to different environments.</p><p>Grafana, on the other hand, is a <strong>visualization</strong> tool that is commonly used in conjunction with Prometheus. It allows users to create informative dashboards that display real-time metrics data in a variety of formats, including graphs, charts, and tables. Grafana is highly customizable and supports a wide range of different data sources, including Prometheus.</p><p>One of the key benefits of using Prometheus and Grafana together is that they provide a complete end-to-end solution for monitoring and observability. Prometheus is able to collect and store vast amounts of data, while Grafana allows users to easily visualize and analyze that data. This makes it possible to quickly identify trends and anomalies, and to take appropriate action to resolve any issues that may arise.</p><p>In addition to their core capabilities, both Prometheus and Grafana also offer a number of other useful features. For example, Prometheus has built-in support for alerting, which allows users to define rules that trigger notifications when certain conditions are met. Grafana, on the other hand, offers a rich plugin ecosystem that allows users to extend its functionality and integrate it with other tools and services.</p><p>In conclusion, Prometheus and Grafana are powerful and versatile tools that are essential for any modern monitoring and observability stack. They provide a complete end-to-end solution that allows users to collect, store, and visualize metrics data, and to take action based on that data. Whether you are running a small application or a large-scale distributed system, Prometheus and Grafana are the tools you need to ensure that your systems are running smoothly and efficiently.</p><p>In recent years, the use of Prometheus and Grafana has become increasingly widespread in the technology industry. Many organizations are adopting these tools to improve their monitoring and observability capabilities, and to gain a better understanding of their systems and applications.</p><p>One of the key reasons for the popularity of Prometheus and Grafana is their ability to handle large amounts of data. As more and more organizations move to <strong>cloud-based architectures</strong> and <strong>microservices-based applications</strong>, the amount of data generated by these systems can quickly become overwhelming. With the rise in popularity of container based software packaging and orchestration solutions, it has become more important than ever to put in place the right metrics monitoring and alerting mechanisms in place, and the combination of Prometheus and Grafana are designed just to enable that, <em>handling data and making it accessible and actionable</em></p><p>Another important factor in the adoption of Prometheus and Grafana is their open-source nature. Both tools are developed and maintained by large and active communities, which means that they are constantly evolving and improving. This allows users to benefit from the latest features and capabilities, and to contribute back to the community if they have ideas for improvements.</p><p>In addition to their technical capabilities, Prometheus and Grafana are also highly cost-effective solutions. Because they are open-source, there are no licensing fees associated with using them, which means that organizations can save money while still getting access to powerful end-to-end monitoring and observability tools that allows them to collect, store, and visualize metrics data, and to take action based on that data</p><h3>Common use cases</h3><p>Some of the most common use cases for Prometheus and Grafana include:</p><ul><li><strong>Monitoring and alerting</strong>: monitor the performance and health of applications and infrastructure, and to trigger alerts when certain conditions are met. This allows organizations to detect and resolve issues before they impact users.</li><li><strong>Capacity planning</strong>: collect and visualize metrics data, which can then be used to plan for future capacity needs. This allows organizations to ensure that they have the resources they need to support their applications and services.</li><li><strong>Performance optimization</strong>: identify performance bottlenecks and other issues, and to take action to improve the performance of applications and infrastructure.</li><li><strong>Troubleshooting</strong>: diagnose and troubleshoot problems with applications and infrastructure, by providing detailed visibility into the underlying systems.</li><li><strong>DevOps</strong>: used as part of a DevOps workflow, to provide real-time visibility into the performance and health of applications and infrastructure. This allows organizations to quickly identify and resolve issues, and to continuously improve their systems.</li></ul><h3>Other use cases</h3><p>One advanced use case for Prometheus and Grafana is using the former for monitoring and alerting on the performance of a highly dynamic and scalable system, such as a cloud-native application deployed on a Kubernetes cluster. Prometheus can collect metrics from the various components of the system, such as the Kubernetes nodes and the individual microservices, and then use its powerful query language and integration with alerting systems to trigger alerts when certain performance thresholds are breached. Grafana, on the other hand, can be used to visualize the collected metrics and create dashboards that provide an overview of the system’s performance. This can be useful for identifying <em>performance bottlenecks</em> and <em>debugging issues</em> in real-time.</p><p>Another advanced use case for these tools is using them for anomaly detection in time-series data. Prometheus can be configured to collect metrics from various sources, such as system metrics, application logs, and business metrics, and then use machine learning algorithms to detect anomalies in the collected data. Grafana can be used to visualize the detected anomalies, along with the underlying time-series data, in order to help users quickly identify and investigate the root cause of the anomalies.</p><h3>Prometheus Installation</h3><p>Prometheus is an open-source monitoring and alerting system. We will use a sample microservices .NET 6 WebApi project to install it by following these steps:</p><ol><li>First, we will install the Prometheus NuGet package in our project by running the following command in the Package Manager Console: Install-Package Prometheus.Client , and there are several other packages available and we can also <a href="https://github.com/prometheus-net/prometheus-net">Prometheus-net</a> to achieve the same functionality</li><li>Next, we will need to configure Prometheus to scrape metrics from our project. To do this, we will add a scrape_configs section to your Prometheus configuration file. In this section, we can specify the URL of our project as the scrape_target, as well as any other relevant configuration options. An example of the YML file is available below</li><li>Once we have configured Prometheus to scrape metrics we can start the Prometheus server by running the prometheus command in a terminal window. This will begin the metrics collection process</li><li>In webapi project code, we can use the Prometheus client library to expose custom metrics (registered users, e-commerce transactions, failed logins…) and make them available for querying and visualization</li></ol><p>Once the above step have been completed, we can see that Prometheus is running correctly under it’s default port 9090, and that the targets we configured for scraping are healthy (8003/metrics-text and 8005/metrics-text)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGBVscIhl6VoOKNxqnmryQ.png" /></figure><p>And this is what the Prometheus metrics page actually looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*rQRAM6bm7tf33oeGU26NUw.png" /><figcaption>Prometheus metrics endpoint</figcaption></figure><p>YML Scraping jobs configuration</p><pre># my global config<br>global:<br>  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.<br>  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.<br>  # scrape_timeout is set to the global default (10s).<br><br># Alertmanager configuration<br>alerting:<br>  alertmanagers:<br>    - static_configs:<br>        - targets:<br>          # - alertmanager:9093<br><br># Load rules once and periodically evaluate them according to the global &#39;evaluation_interval&#39;.<br>rule_files:<br>  # - &quot;first_rules.yml&quot;<br>  # - &quot;second_rules.yml&quot;<br><br># A scrape configuration containing exactly one endpoint to scrape:<br># Here it&#39;s Prometheus itself.<br>scrape_configs:<br>  # The job name is added as a label `job=&lt;job_name&gt;` to any timeseries scraped from this config.<br>  - job_name: &quot;prometheus&quot;<br><br>    # metrics_path defaults to &#39;/metrics&#39;<br>    # scheme defaults to &#39;http&#39;.<br><br>    static_configs:<br>      - targets: [&quot;localhost:9090&quot;]<br><br>  - job_name: &quot;CustomerMetrics&quot;<br>    static_configs:<br>      - targets: [&quot;localhost:8003&quot;]<br>    metrics_path: /metrics-text<br>    scheme: https<br>  - job_name: &quot;ProductMetrics&quot;<br>    static_configs:<br>      - targets: [&quot;localhost:8005&quot;]<br>    metrics_path: /metrics-text<br>    scheme: https</pre><h3>Collecting custom business domain metrics in Prometheus</h3><p>To use Prometheus to collect metrics such as the number of registered users or successful e-commerce transactions, we will need to instrument our code to expose these metrics in a format that Prometheus can scrape and collect.</p><p>To monitor the number of registered users, for example, we will expose a metric called “users_registered” that is incremented each time a new user registers on our platform (in concrete terms, we will call a function within our controller action. Prometheus can then be configured to scrape this metric at regular intervals, allowing you to monitor the number of registered users over time and track trends and changes in user growth. Similarly, you can expose metrics for successful e-commerce transactions, or any other business metrics you want to collect and monitor.</p><p>Here is an example of instrumenting code to expose metrics that Prometheus can scrape, using C#:</p><pre>using Prometheus;<br><br>public class Customer<br>{<br>    private static Counter usersRegistered = Metrics.CreateCounter(&quot;users_registered&quot;, &quot;The number of users registered on the platform&quot;);<br><br>    public void RegisterCustomer()<br>    {<br>        // code to register a user goes here...<br><br>        usersRegistered.Inc();<br>    }<br>}</pre><p>In this example, we are using the Prometheus C# client library to create a counter metric called “users_registered”. This metric is incremented each time the RegisterUser() method is called, allowing us to track the number of users registered on our platform over time. Eventually, we will move the method call to our customer controller where our profile class Mediating between the domain and the data mapping layers is encapsulating the logic required to access our data source</p><p>Once the code is instrumented to expose this metric, we can then configure Prometheus to scrape it at regular intervals. This can be done by specifying the URL where the metrics are exposed, as well as the frequency at which Prometheus should scrape the metrics. Prometheus will then collect the metrics and store them in its time-series database</p><h3>Consuming Prometheus data</h3><p>There are several different ways in which you can consume Prometheus data, depending on your specific needs and requirements. Some of the main modes of consuming Prometheus data include the following:</p><ul><li><strong>Querying using PromQL</strong>: One of the main ways to consume Prometheus data is by using PromQL, which is Prometheus’ query language. You can use PromQL to write queries that extract specific data from Prometheus’ time-series data, and to perform various operations on that data, such as filtering, aggregation, and arithmetic. PromQL queries can be run directly from the Prometheus server, or from a client that is connected to the server.</li></ul><pre>http_requests_total{method=&quot;GET&quot;}</pre><p>This query would return the total number of HTTP GET requests that have been made to the Prometheus server. The http_requests_total metric is a built-in Prometheus metric that tracks the total number of HTTP requests that have been made to the server, and the query filters the results to include only requests with the method &quot;GET&quot;.</p><p>Here is another example of a PromQL query:</p><pre>100 * (1 - avg by (instance) (irate(node_cpu_seconds_total{mode=&quot;idle&quot;}[5m]))</pre><p>This query would calculate the average CPU utilization across all instances, over the past 5 minutes, as a percentage. The node_cpu_seconds_total metric is a built-in Prometheus metric that tracks the total amount of CPU time that has been used by a node, and the irate function is used to calculate the rate of change over the specified time period. The query filters the results to include only data for the &quot;idle&quot; mode, and then uses the avg function to calculate the average across all instances. The final result is multiplied by 100 to express it as a percentage.</p><ul><li><strong>Visualizing using Grafana</strong>: Another common way to consume Prometheus data is by using Grafana dashboards and visualizing time-series data</li><li><strong>Exporting using the Prometheus HTTP API</strong>: Prometheus provides an HTTP API that we can use to extract data from the Prometheus server. The API allows querying using PromQL, and the results are retrievied in various formats, such as CSV or JSON, which can then be imported into other tools or applications, such as visualization or analysis tools</li><li><strong>Consuming using client libraries</strong>: Prometheus provides client libraries for various programming languages, such as Go, Java, Python, and Ruby. These libraries enable integration Prometheus with other applications code in order to build custom monitoring and alerting solutions that are tailored to specific business needs and requirements</li></ul><h3>Grafana Installation</h3><p>Now that we have configured Prometheus correctly to scrape our project metrics endpoints, we will use Grafana to make sense of all that text based information</p><p>The installation process is simple and consists of downloading the installer grafana-X.X.X.windows-amd64.msi, going through the required steps of the installer and then running it</p><p>Once the Grafana server is running, we can access its web interface by going tohttp://localhost:3000, which will open the Grafana login page. By default, the username is &quot;admin&quot; and the password is &quot;admin&quot;</p><p>Now we are up and running and we can connect Prometheus as a data source, and i would recommend installing the ready-made dashboard <a href="https://grafana.com/grafana/dashboards/3662-prometheus-2-0-overview/">https://grafana.com/grafana/dashboards/3662-prometheus-2-0-overview/</a> and start customizing from there</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuMVY5QdY3OY1NTnL2zU5Q.png" /><figcaption>Grafana Prometheus Dashboard — Figure 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*af7ILJHMEDBhGrhHyFo5vg.png" /><figcaption>Grafana Prometheus Dashboard — Figure 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhdvZZ2QnbTnRkKUMN_00g.png" /><figcaption>Grafana Prometheus Dashboard — Figure 3</figcaption></figure><h3>Dashboard examples</h3><p>When using Prometheus as a data source, a Grafana dashboard can display a wide variety of information and metrics, including the status and health of different systems and applications, as well as detailed performance metrics and other data.</p><p>Some examples of Grafana dashboards using Prometheus as a data source might include:</p><ul><li>A dashboard showing the overall health and status of different systems and services in our infrastructure. This could include information such as the <strong>number of requests</strong> being handled by each service, the <strong>error rate</strong>, and the overall <strong>system load</strong>.</li><li>A dashboard focused on the performance of a specific application or service. This could include detailed metrics such as <strong>request latencies</strong>, <strong>memory usage</strong>, and other performance indicators.</li><li>A dashboard showing the status and health of individual servers or containers in your infrastructure. This could include information such as <strong>CPU and memory usage</strong>, <strong>disk space</strong>, and <strong>network traffic</strong>.</li><li>A dashboard focused on monitoring the <strong>performance and availability</strong> of critical services, such as databases or caching systems. This could include metrics such as <strong>query latencies</strong>, <strong>cache hit rates</strong>, and other indicators of system performance and reliability.</li></ul><h3>Advanced scenarios</h3><p>An example of other uses cases are DORA metrics in Prometheus. DORA metrics are used by DevOps teams to measure their performance and find out whether they are “low performers” to “elite performers”. The four metrics used are deployment frequency (DF), lead time for changes (LT), mean time to recovery (MTTR), and change failure rate (CFR).</p><p>To measure Deployment Frequency, we could use a query to count the number of deployments that occurred over a given time period. Similarly, to measure Lead Time for Changes, we could use a query to calculate the time between when a change is made and when it is deployed.</p><h3>Deployment considerations</h3><p>Hosting Grafana in AWS for example, or using Cloud Grafana are two different ways to use it, we will highlight here some of the differences between the two</p><p>Cloud Grafana is a managed service offered by <a href="https://grafana.com/">Grafana Labs</a>, the company behind Grafana. In this case, Grafana Labs would be responsible for hosting and managing the Grafana instance, and we would use the Cloud Grafana service to create and manage our dashboards.</p><p>Some other differences between hosting Grafana in AWS or other cloud providers and using Cloud Grafana include:</p><ul><li><strong>Pricing</strong>: Hosting Grafana in AWS may have a different pricing model than Cloud Grafana. AWS charges for the use of its services based on the amount of resources that you use, such as the number of servers and the amount of data that is stored. Cloud Grafana, on the other hand, may have a fixed pricing model with different tiers based on the number of users and the amount of data that is stored.</li><li><strong>Features</strong>: Hosting Grafana in AWS and using Cloud Grafana may also have different sets of features. For example, Cloud Grafana may offer additional features that are not available when hosting Grafana in AWS, such as integrations with other Grafana Labs products or managed authentication and authorization.</li><li><strong>Support</strong>: Hosting Grafana in AWS and using Cloud Grafana may also have different levels of support. When hosting Grafana in AWS, you would be responsible for managing and maintaining the Grafana instance ourself, so we would need to have the necessary expertise and resources to do so (although the installation and configuration are fairly simple, advanced skills might be required for conducting performance optimizations)</li></ul><p>In general, the choice between hosting Grafana ourselves and using the SaaS flavor will depend on specific business needs, and it is worth considering all of the factors mentioned earlier before making a decision.</p><h3>Container deployment</h3><p>It is also possible to deploy Grafana in a Docker container. Docker is a popular platform for building and deploying applications using containers, which are lightweight and portable units of software that include everything an application needs to run, including the code, libraries, dependencies, and runtime.</p><p>To deploy Grafana in a Docker container, we would first need to install Docker on the host machine and use the docker run command to create a new container from the Grafana Docker image, which is available on Docker Hub. This would involve specifying a number of options, such as the port that Grafana should use, and any environment variables or configuration settings that we want to apply.</p><p>Once the container is running, you can access Grafana using the browser the same way as described before</p><p>Deploying Grafana in a Docker container offers several advantages over installing and running Grafana directly on a host machine. For example, we will be able to easily manage and deploy multiple instances of Grafana, and quickly scale up or down as needed. It also comes with the usual advantages of containerizing apps by making it easier to share configurations and dashboards between different environments, and to migrate to different host machines or cloud platforms.</p><p>Following is the prometheus.yml configuration mentioned earlier in this article</p><pre># my global config<br>global:<br>  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.<br>  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.<br>  # scrape_timeout is set to the global default (10s).<br><br># Alertmanager configuration<br>alerting:<br>  alertmanagers:<br>    - static_configs:<br>        - targets:<br>          # - alertmanager:9093<br><br># Load rules once and periodically evaluate them according to the global &#39;evaluation_interval&#39;.<br>rule_files:<br>  # - &quot;first_rules.yml&quot;<br>  # - &quot;second_rules.yml&quot;<br><br># A scrape configuration containing exactly one endpoint to scrape:<br># Here it&#39;s Prometheus itself.<br>scrape_configs:<br>  # The job name is added as a label `job=&lt;job_name&gt;` to any timeseries scraped from this config.<br>  - job_name: &quot;prometheus&quot;<br><br>    # metrics_path defaults to &#39;/metrics&#39;<br>    # scheme defaults to &#39;http&#39;.<br><br>    static_configs:<br>      - targets: [&quot;localhost:9090&quot;]<br><br>  - job_name: &quot;CustomerMetrics&quot;<br>    static_configs:<br>      - targets: [&quot;localhost:8003&quot;]<br>    metrics_path: /metrics-text<br>    scheme: https<br>  - job_name: &quot;ProductMetrics&quot;<br>    static_configs:<br>      - targets: [&quot;localhost:8005&quot;]<br>    metrics_path: /metrics-text<br>    scheme: https</pre><h3>Conclusion</h3><p>Prometheus and Grafana are powerful tools for monitoring and visualizing time-series data. Together, they offer a robust and flexible platform for monitoring and analyzing systems and applications, and for identifying and troubleshooting performance issues.</p><p>I hope you enjoyed reading this article, thank you for reading and if you find this article useful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Disclaimer</h3><p>Credit goes to any cited articles or illustration/diagram owners</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0d589220c0b" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/observability-with-prometheus-and-grafana-c0d589220c0b">Observability with Prometheus and Grafana</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[microservices != containers]]></title>
            <link>https://towardsaws.com/microservices-containers-90f52f2c5bf7?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/90f52f2c5bf7</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 22:15:25 GMT</pubDate>
            <atom:updated>2022-12-09T22:33:32.768Z</atom:updated>
            <content:encoded><![CDATA[<h3>microservices != containers</h3><figure><img alt="Microservices and Containers" src="https://cdn-images-1.medium.com/max/1024/1*v3GxDVwSFEFzdedvuHFroQ.png" /><figcaption>Image describing microservices and containers created by the author</figcaption></figure><blockquote>“Orchestration and monitoring tools vendors made a lot of damage by trying to get everybody adopting microservices so they could sell their shiny tools, then developers found themselves producing <strong>distributed entangled spaghetti aberrations”</strong></blockquote><p>This is a comment i read the other day on a discussion in a social media platform, and i think it is spot on at describing the current state of affairs</p><p>Microservices have become increasingly popular in recent years, <a href="https://www.verifiedmarketresearch.com/product/cloud-microservices-market/">verified market research</a> predicts the Cloud Microservices Market size that was valued at USD 0.95 Billion in 2022 to reach USD 6.62 Billion by 2030, growing at a CAGR of 21.7% from 2023 to 2030. No longer a buzzword, they have been implemented at major players like Netflix, Amazon, and eBay. And with good reason: they can help scale in many ways. However, they are often used in conjunction with container software packaging technologies which leads to some confusion and even using both terms interchangeably when trying to describe cloud native architectures.</p><h3>Definitions leading to aberrations</h3><figure><img alt="Cloud Computing" src="https://cdn-images-1.medium.com/max/1024/1*3I8UbAShsSgHEJORJpyThg.png" /><figcaption>The Cloud as imagined by Stable Diffusion</figcaption></figure><p>There are definitions such as “<strong>Microservices is an architectural design for building a distributed application using containers</strong>”, and while i have no problem with it’s first part, the “using containers” is what i think is out of context</p><p>Microservices describe components of an application that can be deployed independently and the components communicate with each other through a standardized interface, and the definition that makes more sense to me is a <a href="https://twitter.com/boicy">James Lewis</a> quote “Microservices architecture buy you options”</p><p>The most significant benefits of a microservices architecture are usually:</p><ul><li><strong>Independent deployability</strong>: at the end of the day, it is still a distributed system, components are loosely coupled but they still have to talk to each other, so the key here is not chasing a zero risk, but working towards more independent modules (monolithic single process runtime) or components (microservices) that allows a greater flexibility in terms of deployment</li><li><strong>Options for scaling up applications</strong></li><li><strong>Organizational scaling</strong>: when you have multiple teams specializing in different domains within the same system, microservices architecture allow greater ownership of those respective domains, and reduce the amount of coordination and communication required during deployments. Another argument that can be made here is the isolation of domains whereby it comes harder for team A to violate certain boundaries set by team B, as opposed to a distributed monolithic architecture where those boundaries are much easier to break</li><li><strong>Data isolation</strong>: think GDPR or HIPAA. Microservices makes it easier to constrain certain types of data processing (such as personally identifiable information for example) into a well defined boundary</li></ul><p>However, this architecture has it’s drawbacks:</p><ul><li>A lager and complex <strong>attack surface</strong> as each microservice comes with additional entry points, and unless a strong authentication and zero trust policy is in place, the APIs are exposed to attacks</li><li><strong>Logging</strong> becomes an issue in muti-cloud environments and consisting of multiple distributed, stateless independent components, where log structure is heterogeneous, but this can be mitigated with data aggregation platforms from all services and present all relevant information</li><li><strong>Polyglot architecture</strong> when multiple teams have their own tech stacks and eventually end up requiring security experts who specialize in these respective stack</li><li>Higher complexity, Increased network traffic, Limited reuse of code, Difficult debugging and Dependency on DevOps amongst others</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-fnH8fuC9XbW2JR776f1A.png" /><figcaption>Image property owned by <a href="https://maveric-systems.com/blog/microservices-i-microservices-vs-soa/">https://maveric-systems.com</a></figcaption></figure><p>So, to summarize, microservice architecture is an evolution over SOA as <strong>its services are more fine-grained, and function independently of each other</strong></p><p>On the other hand, containerization is an evolution over Virtualization as <strong>it is designed to provide a much lightweight compute environment while abstracting more elements such as the operating system and application dependencies</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tT3rxcoPBMV1n4YjWsw4_g.jpeg" /><figcaption>Image property is owned by <a href="https://www.weave.works/blog/a-practical-guide-to-choosing-between-docker-containers-and-vms">https://www.weave.works</a></figcaption></figure><blockquote>As you can see, both paradigms and technologies are part of different realm, software and infrastructure</blockquote><h3>The point is?</h3><p>We have a whole generation of developers who grew up with DevOps and Cloud native, with the mindset that it is the “best” method, approach, technique, technology, stack (call it whatever you want) they studied and used. They heard about monoliths, they heard about N-Tier architecture, but what should they care, the world apparently runs on microservices and containers</p><p>In an ideal situation, requirements are translated into clear design guidelines and direction on what to use and how, but that is not always true, which brings us to the majority of use cases out there</p><figure><img alt="Facebook Apple Amazon Netflix Google, FAANG" src="https://cdn-images-1.medium.com/max/690/0*nuqSZhmvvRwFG8-O" /><figcaption>All trademarks, logos and brand names are the property of their respective owners</figcaption></figure><p>Actually, a lot of companies out there are nowhere near the size of the behemoths (FAANG), nonetheless they want to adopt their scalable architectures and run their products and services the same way, future proof, modern stacks, agile, rapid go to market and highly automated operations. What they do not realize however is that not everything has to containerized, and certainly not everything has to be designed as microservices</p><p>I have worked on projects that ran at 100% uptime month to month for years, that doesn&#39;t come from being microservices or containerized packaged software but from clean code, extensive testing, deployment strategies and robust infrastructure. Whether the service runs on a container or a VM, when it’s down, it is down</p><blockquote>Try running a dockerized SQL Server or SAP in production and see what happens, you are just shooting yourself! Containers are transient, Data is persistent, so <em>Not Everything Has run inside a Container</em></blockquote><h3>Conclusion</h3><p>Build your application with the focus on how to obtain a desired outcome rather than insisting on using a certain approach. I would almost certainly say that the default should not be microservices. Remember that a monolithic architecture IS a distributed system, whether you are retrieving data from another computer, or delivering data to a browser, that is the definition of a distributed system, it’s just a simple one</p><p>Use microservices when there is a really good reason to use it. Having a thousand line of code program you insist on breaking down into multiple modules is just a bad one!</p><p>Having said that, building your applications with microservices in mind would be a good approach when the decision is justified, separation of concerns is what’s been driving innovation in the IT industry since it’s inception, and it is mainly what led to the amazing technology advancements we have today. So, designing software with domain separation is key to having a microservice-ready architecture when you need to “flip the switch”</p><p>I hope this article has given you some food for thought!</p><p>Thank you for reading and if you find this article useful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Disclaimer</h3><p>Credit goes to any cited articles or illustration/diagram owners</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90f52f2c5bf7" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/microservices-containers-90f52f2c5bf7">microservices != containers</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SecOps best practices: Bastion Host and ELB considerations]]></title>
            <link>https://towardsaws.com/secops-best-practices-bastion-host-and-elb-considerations-e7840d305602?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7840d305602</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[vpc]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 21:24:03 GMT</pubDate>
            <atom:updated>2021-12-10T06:37:38.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NY2P0KquJ0JeQvIC.png" /><figcaption>Amazon Web Services</figcaption></figure><p>Let’s spin a couple of EC2 instances and deploy our workloads there, but first we need to connect to our newly launched machines and perform some bootstrapping and updates. SSH or RDP directly…Easy, right?</p><h3>Wrong!</h3><p>Yes, nothing beats the simplicity of connecting directly to your instances, and if you think that you are secure today by implementing a good credential hygiene, digital certificates and two-factor authentication, then you should think again</p><p>There are many security risks exposing your instances to the public internet over ports used for remote connection when it is not necessary</p><p>Recent <a href="https://atlasvpn.com/blog/rdp-attacks-surged-by-330-in-the-us-amid-pandemic">reports</a> suggest that RDP brute force attacks soared during 2021 by a whooping 330% in the US amid the COVID-19 pandemic</p><p><a href="https://securelist.com/remote-spring-the-rise-of-rdp-bruteforce-attacks/96820/">Another one</a> by Kaspersky demonstrates the significant rise of such attacks and expands on the do’s and don’t</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6__-AecLDt3wh15H.png" /><figcaption>Growth in the number of attacks by the Bruteforce.Generic.RDP family, February–April 2019</figcaption></figure><p>The only way to secure remote access to workloads is to prevent them from exposing RDP/SSH ports publicly by placing them inside private subnets, and we will demonstrate the use of <strong>bastion host</strong> only accessible from a corporate network to manage these workloads remotely</p><p>By default, subnets in AWS VPC’s are public (according to the documentation, a public subnet is and a private subnet is), and you can see that by checking the route table of the subnet, you will see that 0.0.0.0/0 traffic is routed via an IGW (Internet Gateway)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*LebUdKXa2QYN1F0PSdyEVA.png" /><figcaption>Route table with Internet Gateway target</figcaption></figure><p>By removing that line on the route table , we render any subnet associated with this route table as private</p><p>First, we will create a new route table on our VPC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBnG7BqwnQlt__XJtzChDQ.png" /><figcaption>New “private” route table with a single route with VPC range</figcaption></figure><p>Then we will go back to our subnet (let’s call it the Private Subnet) and edit the route table association, then change the association from the default route table to the one we just created. This effectively would render our subnet as a private one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Z4zmLRcyX71j7Bq-kIrPQ.png" /><figcaption>Changing subnet route table association</figcaption></figure><p>In some cases, even when our EC2 instances are placed within a private subnet, we still want these instances to be able to get updates, call API’s or send emails, in which case we can add a new route as <em>Destination: 0.0.0.0/0 and Target NAT Gateway</em> (as opposed to a internet gateway)</p><p>We can do that by creating a NAT Gateway first</p><blockquote>A NAT Gateway is an AWS service that allows a private subnet to have access to the Internet, but prevents the Internet from initiating a connection directly to the instances. While the NAT Gateway is needed for private subnets to have Internet access, <strong>it is created in a public subnet</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*2N7vAuTQm4yLAiMoMoJgug.png" /><figcaption>Creating a NAT Gateway</figcaption></figure><p>Now, we can go back to our routing table and add a new route where the target will be our NAT Gateway</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bO_CD-RrfXuhg_-gE0zoGQ.png" /><figcaption>Additional route in our private routing table with NAT target</figcaption></figure><p>With this, we have now a private subnet where we can deploy instances that have internet access, and internet connections to these instances is prevented</p><p>To demonstrate that, we will launch a couple of instances, one in a public subnet and one in a private subnet, and we will try to SSH to both and see what happens</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06lgfWYvriLM8Ig25DN-Dw.png" /><figcaption>Launching an EC2 on a public subnet</figcaption></figure><p>The security group we will use for both is exactly the same, SSH TCP port 22 from 0.0.0.0/0, and the only difference between these two instances will be the subnet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aBu6y4qHMmbBiamNgjXcQ.png" /><figcaption>Launching an EC2 on a private subnet</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*wOyuX7o1lFcBOwPL-Jj29w.png" /><figcaption>Public instance connecting via SSH</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*DUFQt7ARu44HTmX98-ULow.png" /><figcaption>Private instance refusing SSH connections</figcaption></figure><p>Now, trying to connect to our private instance from our public one is working just fine, that’s because the private instance cannot have connections from the public internet, and the same scenario applies to RDP to Windows machines as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*mXyYgc-G0BPXgk53FKt4Sg.png" /><figcaption>Testing SSH connection to our private instance from the bastion (Telnet port 22)</figcaption></figure><p>Now, we have our quick and dirty bastion proxy host that we can use exclusively to manage instances on a private subnet, but that is not our entire objective</p><p>What about security groups?</p><p>In general, you would want to ensure that:</p><ul><li>Your instances accept RDP/SSH ONLY from the bastion SG</li><li>Your bastion SG accepts RDP/SSH ONLY from a corporate network IP</li><li>Shut down your bastion when done to avoid incurring any charges</li></ul><h3>Elastic Load Balancer Considerations</h3><p>This setup would typically achieve the desired results and improve security, however the majority of production use cases would require the web servers to sit behind load balancers, and therefore there are some important points to consider</p><blockquote>By design, internet-facing Application Load Balancers (ALB) and Classic ELB’s must be provisioned exclusively in <strong>public </strong>subnets, regardless of whether the instances behind the ELB are in public subnets or private ones</blockquote><ul><li>If you try to place the ELB in private subnets, clients won’t be able to establish connections to it</li><li>If you try to place the ELB in a mix of public and private subnets, clients will intermittently timeout with a misrouting response as some connections will reach the ELB while others won’t. Have a look at this CloudWatch metric showing that while it is being reported as healthy, not all 100% of the probes are reporting a healthy status</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKc8sXiiqyonTtVgo_-8Bg.png" /></figure><blockquote>By design, an ELB can be provisioned in multiple Availability Zones, however there is a limitation of at most one subnet per AZ</blockquote><p>So now, what does this mean when we have public and private subnets?</p><p>Let’s consider the use case where we have the following</p><ul><li>Public subnet a in US-EAST-1 region and AZ1</li><li>Public subnet b in US-EAST-1 region and AZ2</li><li>Private subnet c in US-EAST-1 region and AZ3</li><li>ALB provisioned in subnet a and b (AZ 1 and 2)</li></ul><p>If our ALB is provisioned in subnet a and b and our instances sit in those subnets, everything is fine. HOWEVER, when provisioning instances in the “private” subnet c, those instances simply won’t register as healthy in our ALB target group and you will a message saying <strong>“Target is in an Availability Zone that is not enabled for the load balancer”</strong></p><p><em>The confusion probably comes from the fact that the default VPC comes pre-configured with a subnet in each AZ, which leads to a mix up between AZ and subnets. You can have multiple subnets within the same AZ and those can be public and private, so when dealing with ELB’s, they must be provisioned within public subnets (refer to the previous point), but also when trying to register targets provisioned in AZ’s not associated with the ELB, traffic will not be routed to these targets</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EpuUJoLyZZHpqQFMyfaNtg.png" /></figure><p>The solution is to simply design your solution around subnets in AZ’s we plan on deploying the ALB into, so the above configuration becomes:</p><ul><li>Public subnet a in US-EAST-1 region and AZ1</li><li>Public subnet b in US-EAST-1 region and AZ2</li><li>Private subnet c in US-EAST-1 region and AZ1</li><li>ALB provisioned in subnet a and b (AZ 1 and 2)</li></ul><p>Now, instances we provision in subnet c (or a/b) would have traffic reaching them via the ALB, regardless of whether or not they have public IPs</p><h3>Conclusion</h3><p>We can summarize by saying that there are usually three cases where we can apply the above recommendations and decide where to put our EC2 instances and how:</p><ol><li><em>For workloads not requiring any type of internet accessibility, provision within private subnets </em><strong><em>without </em></strong><em>NAT</em> (example, Database engines)</li><li><em>For workloads requiring outbound connections to the internet, provision within private subnets </em><strong><em>with </em></strong><em>NAT</em>. Ability to perform software updates, download files, run some agents, send outbound emails, call API’s are just some of the examples</li><li>For anything else where inbound/outbound connectivity is required, place them inside public subnets</li></ol><p>Thank you for reading and if you find this article useful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Disclaimer</h3><p>Credit goes to any cited articles or illustration/diagram owners</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7840d305602" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/secops-best-practices-bastion-host-and-elb-considerations-e7840d305602">SecOps best practices: Bastion Host and ELB considerations</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TV shows, Image processing and High performance message queuing services: an SQS and .NET case]]></title>
            <link>https://towardsaws.com/tv-shows-image-processing-and-high-performance-message-queuing-services-an-sqs-and-net-case-3518c137d780?source=rss-23349e332d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/3518c137d780</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sqs]]></category>
            <dc:creator><![CDATA[Majdi Dhissi]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 14:53:10 GMT</pubDate>
            <atom:updated>2021-11-22T14:52:23.585Z</atom:updated>
            <content:encoded><![CDATA[<h3>TV shows, Image processing, and High-performance message queuing services: an SQS and .NET case</h3><p>So, there is this TV show viewed by millions of people where performers demonstrate their amazing and unique talents, and at the end of every episode, the public is invited to vote for their favorite performance in a short time frame.</p><p>Something that might keep you up at night as the principal architect of the system used by the audience to vote is either scalability, resilience, cost, or all of them together!</p><p>In your spare time, you also contribute to a service that allows users to upload images in different formats, sizes, and resolutions and these images need to be indexed, resized, and watermarked as well. They will be used later on to display home interiors in a real-estate app</p><p>There are multiple ways to achieve the desired results for both scenarios and applications, you might want to go for a fleet of scheduled EC2 instances and deal with auto-scaling and the cost associated with having all these instances up and running for a certain period of time, but you will probably need to overprovision as well in order to handle the expected workload and potentially unexpected peaks</p><p>BUT Wait… what if there are significantly fewer people who are going to vote, you were expecting millions of votes, and yet you ended up with a lot less. In this case, you would end up paying a lot for nothing!</p><p>In this article, we look into using AWS Simple Queue Service (SQS) to implement a reliable and high performance messaging queue delivery for similar cases</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*pqBiZHDeQg4ZTUwi.png" /><figcaption>AWS Simple Queue Service</figcaption></figure><p>Amazon Simple Queue Service (SQS) is a fully managed message queuing service that allows decoupling and scaling microservices, distributed systems, and serverless applications. You don’t really need to have a microservices architecture in order to use SQS, monolithic systems could also benefit in most cases from a certain level of decoupling as a simple way to decouple distributed systems</p><p>Being fully managed means that you don’t have to worry about resilience or scalability, it’s all taken care of behind the scenes and even security gets a boost whereby DDoS attempts against your service are absorbed by SQS instead of cascading down to your servers</p><p>What is also great about message queues and decoupling components in your system is that delivery is guaranteed in most cases, so if your polling service or tier goes down, the messages won’t be lost and will be received the next time the service goes online</p><blockquote>It’s important to understand that SQS is not a pub/sub notification service unlike SNS, it inherently introduces some latency in message delivery in SQS unlike SNS where messages are immediately pushed to subscribers. SNS on the other hand supports multiple subscribers, uses a push mechanism which eliminates the need to periodically check or “poll” for updates</blockquote><p>Without further due, let’s get to work and build our main tiers that would demonstrate the solution, which consist of the following component</p><ul><li>REST service endpoint exposing asynchronous methods for casting votes that will be used by a mobile application</li><li>SQS queue</li><li>Windows service polling continuously for new queue messages and processing/deleting them</li></ul><h3>What do you need for this project?</h3><ul><li>An AWS account, you will be able to use free tier with SQS up to 1 million requests each month</li><li>Visual Studio 2019 or 2022 and .NET 5 or 6 SDK installed</li><li>SQL Server Developer edition and SSMS (I am using v 18.8 in this project)</li></ul><h3>Creating the SQS queue using AWS Console</h3><p>The first thing we need to do is head to IAM and create a programmatic access user account that has sufficient policy access permissions to SQS</p><p>For the sake of simplicity, we will just assign the default AWS Managed Policy “<a href="https://console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AmazonSQSFullAccess">AmazonSQSFullAccess</a>” for now, but we will go back to this user account later on to restrict access to our queue only</p><blockquote>Please make sure you download your access key and secret once you create your user account, we will need them later on for sending and receiving messages from our .NET projects</blockquote><p>Now, let’s head to our AWS console and search for SQS, then click on “Create Queue”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKhgFCr0kG_TnZnyxcds2w.png" /><figcaption>Creating the queue in AWS Console</figcaption></figure><p>We will go with the default settings but we will change the retention period to a lower value (a few minutes or hours, for example, to accommodate for the possibility of having our polling service breaking and needing a restart). We don’t really need to receive messages in a particular order here, so we will go with a standard rather than FIFO</p><p>Next is our access policy, we will use the ARN of the IAM user account we created earlier as the only account that has the ability to send and receive messages from/to the queue</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*ED11Eg64S8j5nQPD1ULeaA.png" /><figcaption>Apply policy setup</figcaption></figure><p>Now that we have created our queue, we can copy it’s ARN identifier and go back to our user account for further refinement. We will detach the managed policy and create a new access policy instead that only has access to our queue, then attach the custom policy to our user account</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;sqs:ListQueues&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor1&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;sqs:*&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:sqs:us-east-1:798876925625:my-registration-queue&quot;<br>        }<br>    ]<br>}</pre><h3>Creating our .NET solutions for sending and receiving messages</h3><p>Here, we will go for a Web API project in Visual Studio 2022 and a console application as the message receiver for the sake of simplicity, however, you can also build the same functionality using a worker service and publish it, or even a task scheduler running a job that triggers the polling service during specific times</p><p>Let’s create a new project (Web API template)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*yG784NFoLHICfe1WyJyBDg.png" /><figcaption>Visual Studio 2022 — Create a new Web API project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*9Sv1G0WWOlYgINcEk7QNfA.png" /><figcaption>Visual Studio 2022 — Create a new Web API project II</figcaption></figure><p>Then we will select .NET 5.0 as our target framework and enable HTTPS configuration and OpenAPI support (this would add the Swagger necessary files and configuration as well)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*ZvGdlqyV-B2kp7O4XtBYNA.png" /><figcaption>Visual Studio 2022 — Select a target framework</figcaption></figure><p>Then we will slightly modify our appsettings.json to add the key, secret and the URL to be able to access SQS programmatically</p><pre>{</pre><pre>&quot;Logging&quot;: {</pre><pre>&quot;LogLevel&quot;: {</pre><pre>&quot;Default&quot;: &quot;Information&quot;,</pre><pre>&quot;Microsoft&quot;: &quot;Warning&quot;,</pre><pre>&quot;Microsoft.Hosting.Lifetime&quot;: &quot;Information&quot;</pre><pre>}</pre><pre>},</pre><pre>&quot;AllowedHosts&quot;: &quot;*&quot;,</pre><pre>&quot;ApiKey&quot;: &quot;**********&quot;,</pre><pre>&quot;AwsServiceConfiguration&quot;: {</pre><pre>&quot;AccessKey&quot;: &quot;**************&quot;,</pre><pre>&quot;SecretKey&quot;: &quot;***************************&quot;,</pre><pre>&quot;SQSUrl&quot;: &quot;https://sqs.us-east-1.amazonaws.com/**********/my-registration-queue&quot;</pre><pre>}</pre><pre>}</pre><p>Next, let’s make sure the required packages are installed as well, for this project we will mostly need the following NuGet packages:</p><ul><li>AWSSDK.SQS is the main SQS SDK</li><li>AWSSDK.Extensions.NETCore.Setup is used for dependency injection</li><li>Newtonsoft.Json for serialization</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rczOJ2JpSKv2wvWgedrKhg.png" /><figcaption>NuGet packages</figcaption></figure><p>Our Web API will have a service middleware that acts as a helper and would look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*nfzMhv4sKzURliMj8q1s3g.png" /><figcaption>AWSSQSService.cs</figcaption></figure><p>It simply takes care of the dependency injection for the AWS configuration that we added earlier on the appsettings.json, and a single method for casting votes</p><p>Our controller would then implement the following code for a POST method taking the JSON payload that includes votes to publish in the queue</p><blockquote>For the sake of simplicity, the method we are using here is a GET and we assume that we already have multiple user accounts populated into our database</blockquote><pre>[HttpGet(&quot;{id}&quot;)]</pre><pre>public async Task&lt;bool&gt; CastVote(int id)</pre><pre>{</pre><pre>Vote vote = new Vote() { UserId = new Random().Next(1,50),  VoteValue = new Random().Next(1,5), VotedOn = DateTime.UtcNow };</pre><pre>var result = await _AWSSQSService.PostVoteAsync(vote);</pre><pre>return result;</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dP2TSROP0Sjgi1sqYxNkyQ.png" /><figcaption>REST service for publishing messages into the queue</figcaption></figure><p>If we now test our Web API, we will see that it is successfully posting messages to our queue, you can verify that by going to the SQS section and hit the “Poll for messages” button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6W4WAEr_xQ5LdqJh0XkUEw.png" /><figcaption>Polling for new messages in the AWS Console</figcaption></figure><p>Viewing a message on the console does increase the “Receive count” property for each message, but once deleted, the messages are then considered as received and no other consumer can view them (assuming they have been consumed within the their retention period)</p><h3>Let’s create our consumer service</h3><p>This is a simple console application that would run continuously and poll for messages. As new messages are published, the service will then process these messages by:</p><ul><li>Inserting the data into SQL Server</li><li>Delete the message so it doesn’t get processed again</li></ul><p>To make sure we are performing both actions in a transactional way (either both or nothing), we will use Entity Framework’s context.SaveChanges() return value to check if the vote has been successfully persisted before deleting the message, if not then we will retry</p><p>We will also need some to import some NuGet packages in order to use Entity Framework database reverse engineering in addition to the standard SQS SDK that will be used to pull messages from our queue</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqokyDKNygwRmpPVUPxYyQ.png" /><figcaption>NuGet packages for our polling service</figcaption></figure><pre>do</pre><pre>{</pre><pre>var msg = await GetMessage(sqsClient, url, WaitTime);</pre><pre>if (msg.Messages.Count != 0)</pre><pre>{</pre><pre>//ProcessMessage(msg.Messages[0]);</pre><pre>if (ProcessMessage(msg.Messages.FirstOrDefault()))</pre><pre>await DeleteMessage(sqsClient, msg.Messages.FirstOrDefault(), url);</pre><pre>}</pre><pre>} while (!Console.KeyAvailable);</pre><p>Our data model is simple and consists of three tables that we can replicate using Scaffold-DBContext command (Entity Framework)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*gOREQmPrOmoyN2tR_4ET_g.png" /><figcaption>Database schema</figcaption></figure><pre>Scaffold-DbContext &quot;Server=.;Database=WebAppDB;Trusted_Connection=True;&quot; Microsoft.EntityFrameworkCore.SqlServer -ContextDir Models -OutputDir Models -Namespace &quot;DomainLayer.Models&quot; -ContextNamespace &quot;DataAccessLayer.Context&quot; -Force</pre><p>Now, upon firing the service, you should start seeing messages being processed and our database being populated with votes</p><p>I am using a little Chrome extensions that simulates a bunch of HTTPS calls to the web service and i used a scenario of 1000 votes with a 5ms delay between calls. The whole operation completed in a few seconds and all the votes were saved once the polling service became online</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*MzppiaLBl9MdQKC_ykkP-w.png" /><figcaption>Windows polling service</figcaption></figure><p>Our polling service is now processing messages and storing them into our backend, then immediately deleting them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*yuj5-qpVVVitwVib.gif" /></figure><p>If we look at our Vote table, we will see that the results are being persisted as well, Yayyyy!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sN36SMd7nF7Zzu4H4hJcog.png" /><figcaption>Vote table populated</figcaption></figure><p>Real world scenarios would be obviously different where thousands of votes are being performed within a few seconds, and it is therefore important to architect your API in a way that scales as well and responds to calls in a consistent way. API Gateway and Lambda are two managed services that help achieve the resilience and performance required</p><h3>Additional concepts</h3><p><strong><em>Dead-letter queue and redrive policy: </em></strong>Amazon SQS supports <em>dead-letter queues</em>, which other “source queues” can target for messages that can’t be consumed successfully. Dead-letter queues are configured via <em>redrive policies</em> and are useful for debugging applications or messaging system because they let you isolate problematic messages to determine why their processing doesn’t succeed</p><p><strong><em>Monitoring via CloudWatch:</em></strong><em> You can add your SQS metrics to an existing or new CloudWatch dashboard, and setup alarms for the following events in order to take action whenever a certain queue starts performing in a different way:</em></p><ul><li>ApproximateNumberOfMessagesDelayed</li><li>NumberOfMessagesDeleted</li><li>NumberOfMessagesSent</li><li>NumberOfMessagesReceived</li><li>NumberOfEmptyReceives</li><li>ApproximateAgeOfOldestMessage</li><li>ApproximateNumberOfMessagesVisible</li><li>ApproximateNumberOfMessagesNotVisible</li><li>SentMessageSize</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePa3k7o68AkjizSwdVJqfg.png" /><figcaption>CloudWatch SQS dashboard</figcaption></figure><h3>Conclusion</h3><p>There are many valid use cases justifying the use of SQS, i have seen cases where it is implement it to introduce a buffer for CRUD operations into an RDBMS cluster for saving log information and system events, but also more traditional tasks of decoupling components in a system, batch processing, scheduling jobs and distributing workloads from a central node to worker nodes amongst others</p><p>If you want to learn about additional SQS concepts, i recommend checking out the following</p><p>Thank you for reading and if you find this article useful, please</p><ul><li><strong>Clap</strong> and let others find this article</li><li><strong>Share</strong> it on your feed or social media</li><li><strong>Follow me </strong><a href="https://medium.com/@majdid">Majdi Dhissi</a> to receive updates</li><li><strong>Keep in touch </strong><a href="https://www.linkedin.com/in/majdidhissi/">LinkedIn</a></li></ul><h3>Useful Resources</h3><blockquote><a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html"><strong><em>SQS Developer guide</em></strong></a></blockquote><blockquote><a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-security-best-practices.html"><strong><em>Amazon SQS security best practices</em></strong></a></blockquote><blockquote><a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/working-with-messages.html"><strong><em>Working with Amazon SQS messages</em></strong></a></blockquote><blockquote><a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/reducing-costs.html"><strong><em>Reducing SQS Costs</em></strong></a></blockquote><h3>Disclaimer</h3><p>Credit goes to any cited articles or illustration/diagram owners</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3518c137d780" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/tv-shows-image-processing-and-high-performance-message-queuing-services-an-sqs-and-net-case-3518c137d780">TV shows, Image processing and High performance message queuing services: an SQS and .NET case</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>