<?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 Emiliano Sgrano on Medium]]></title>
        <description><![CDATA[Stories by Emiliano Sgrano on Medium]]></description>
        <link>https://medium.com/@emiliano.sgrano?source=rss-a3721ecae932------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FfP2Lkjg-QKlfDZd</url>
            <title>Stories by Emiliano Sgrano on Medium</title>
            <link>https://medium.com/@emiliano.sgrano?source=rss-a3721ecae932------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:43:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emiliano.sgrano/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[Stop Using Lambdas in Step Functions!]]></title>
            <link>https://medium.com/@emiliano.sgrano/stop-using-lambdas-in-step-functions-4cd242ab19eb?source=rss-a3721ecae932------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cd242ab19eb</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Emiliano Sgrano]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 16:44:16 GMT</pubDate>
            <atom:updated>2025-03-26T16:45:04.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Here’s Why You Should Leverage AWS Integrations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cq-2M42Uebvhe66BlXNx_Q.jpeg" /></figure><p><a href="https://aws.amazon.com/step-functions/">AWS Step Functions</a> is a powerful service for orchestrating workflows across AWS services. However, many engineers fall into the habit of overusing AWS Lambda functions within Step Functions, even for tasks that could be easily handled with native AWS integrations.</p><p>Lambda is great for executing small units of logic, but it can lead to higher costs, increased latency, and additional complexity as well as maintenance overhead.</p><p>In this article, we’ll explore why you should reconsider using Lambda functions within Step Functions and how you can leverage AWS service integrations to build more efficient, scalable workflows.</p><h3>What Are AWS Step Functions?</h3><p>AWS Step Functions is a fully managed <strong>workflow orchestration service</strong> that allows you to build <strong>serverless workflows</strong> using state machines. It helps automate processes by <strong>coordinating multiple AWS services</strong> in a reliable and scalable way.</p><p>With Step Functions, you define workflows using <strong>Amazon States Language (ASL)</strong> and break down complex operations into individual steps, improving maintainability and monitoring.</p><p>Traditionally, developers used AWS Lambda functions to simply call services, but in the past few years AWS has significantly expanded <strong>direct service integrations</strong>, reducing the need for Lambda in many cases.</p><h3>Step Functions Integrations with AWS Services</h3><p>Instead of relying on Lambda functions for simple tasks like querying a database, calling an API, or transforming data, Step Functions now offers <strong>over 200 direct integrations</strong> with AWS services.</p><p>There are two ways you can use Step Functions integration:</p><ul><li>by using the <strong>SDK integration</strong>: you can simply call the service SDK function (e.g. <strong>arn:aws:states:::aws-sdk:s3:listBuckets</strong> to list S3 buckets)</li><li>by using <strong>Optimized Integrations</strong> (e.g <strong>arn:aws:states:::dynamodb:getItem</strong> to retrieve an item from DynamoDB)</li></ul><p>Using these integrations eliminate unnecessary compute layers, reducing cost and execution time.</p><p>Here are some examples where Step Functions integrations can <strong>replace Lambda functions</strong>:</p><h3>1. Calling AWS SDKs Directly</h3><p>Instead of using Lambda to invoke an AWS service through its SDK, you can use Step Functions’ <strong>Service Integrations</strong> feature.</p><h3>Example: Writing to DynamoDB</h3><p>Instead of:</p><ol><li>Invoking a Lambda function</li><li>The function calling the AWS SDK to write to DynamoDB</li></ol><p>You can <strong>directly</strong> integrate with DynamoDB in your Step Function:</p><pre>{<br>  &quot;Type&quot;: &quot;Task&quot;,<br>  &quot;Resource&quot;: &quot;arn:aws:states:::dynamodb:putItem&quot;,<br>  &quot;Parameters&quot;: {<br>    &quot;TableName&quot;: &quot;Orders&quot;,<br>    &quot;Item&quot;: {<br>      &quot;OrderId&quot;: { &quot;S&quot;: &quot;12345&quot; },<br>      &quot;Status&quot;: { &quot;S&quot;: &quot;Pending&quot; }<br>    }<br>  }<br>}</pre><h3>2. Processing Data</h3><h3>Example: Using AWS Glue for ETL Workflows</h3><p>Instead of a Lambda function orchestrating data processing jobs, Step Functions can directly invoke <strong>AWS Glue</strong>:</p><pre>{<br>  &quot;Type&quot;: &quot;Task&quot;,<br>  &quot;Resource&quot;: &quot;arn:aws:states:::glue:startJobRun&quot;,<br>  &quot;Parameters&quot;: {<br>    &quot;JobName&quot;: &quot;CustomerDataETL&quot;<br>  }<br>}</pre><h3>3. S3 Event-Driven Workflows</h3><p>Instead of using Lambda to trigger a workflow after an S3 event, Step Functions can <strong>directly process S3 events</strong> and move data accordingly.</p><h3>Example: Copying an S3 Object Using Step Functions</h3><p>Instead of a Lambda function copying an object, you can use the <strong>S3 CopyObject API</strong> directly:</p><pre>{<br>  &quot;Type&quot;: &quot;Task&quot;,<br>  &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:s3:copyObject&quot;,<br>  &quot;Parameters&quot;: {<br>    &quot;Bucket&quot;: &quot;destination-bucket&quot;,<br>    &quot;CopySource&quot;: &quot;source-bucket/object-key&quot;,<br>    &quot;Key&quot;: &quot;new-object-key&quot;<br>  }<br>}</pre><h3>4. Calling API Gateway Directly</h3><p>Instead of a Lambda function acting as a proxy between Step Functions and an API Gateway endpoint, you can <strong>invoke API Gateway directly</strong>.</p><pre>{<br>  &quot;Type&quot;: &quot;Task&quot;,<br>  &quot;Resource&quot;:&quot;arn:aws:states:::apigateway:invoke&quot;,<br>  &quot;Parameters&quot;: {<br>    &quot;ApiEndpoint&quot;: &quot;example.execute-api.us-east-1.amazonaws.com&quot;,<br>    &quot;Method&quot;: &quot;GET&quot;,<br>    &quot;Headers&quot;: {<br>      &quot;key&quot;: [&quot;value1&quot;, &quot;value2&quot;]<br>    },<br>    &quot;Stage&quot;: &quot;prod&quot;,<br>    &quot;Path&quot;: &quot;bills&quot;,<br>    &quot;QueryParameters&quot;: {<br>      &quot;billId&quot;: [&quot;123456&quot;]<br>    },<br>    &quot;RequestBody&quot;: {},<br>    &quot;AuthType&quot;: &quot;NO_AUTH&quot;<br>  }<br>}</pre><h3>Full Step Functions State Machine Example</h3><p>Let’s put everything together into a <strong>real-world state machine</strong> that:</p><ol><li><strong>Receives an order request</strong></li><li><strong>Writes the order to DynamoDB</strong></li><li><strong>Processes a payment using AWS SDK</strong></li><li><strong>Sends an order confirmation via Amazon SNS</strong></li></ol><p>Here’s a Step Functions definition in <strong>Amazon States Language (ASL)</strong> that <strong>avoids using Lambda functions</strong>:</p><pre>{<br>  &quot;Comment&quot;: &quot;Order Processing Workflow Without Lambda&quot;,<br>  &quot;StartAt&quot;: &quot;SaveOrderToDynamoDB&quot;,<br>  &quot;States&quot;: {<br>    &quot;SaveOrderToDynamoDB&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:states:::dynamodb:putItem&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;TableName&quot;: &quot;Orders&quot;,<br>        &quot;Item&quot;: {<br>          &quot;OrderId&quot;: { &quot;S.$&quot;: &quot;$.orderId&quot; },<br>          &quot;Status&quot;: { &quot;S&quot;: &quot;Pending&quot; }<br>        }<br>      },<br>      &quot;Next&quot;: &quot;ProcessPayment&quot;<br>    },<br>    &quot;ProcessPayment&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:sqs:sendMessage&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;QueueUrl&quot;: &quot;&lt;https://sqs.us-east-1.amazonaws.com/123456789012/PaymentQueue&gt;&quot;,<br>        &quot;MessageBody.$&quot;: &quot;States.JsonToString($.orderId)&quot;<br>      },<br>      &quot;Next&quot;: &quot;SendConfirmation&quot;<br>    },<br>    &quot;SendConfirmation&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:states:::sns:publish&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;TopicArn&quot;: &quot;arn:aws:sns:us-east-1:123456789012:OrderNotifications&quot;,<br>        &quot;Message.$&quot;: &quot;States.Format(&#39;Order {} has been successfully processed.&#39;, $.orderId)&quot;<br>      },<br>      &quot;End&quot;: true<br>    }<br>  }<br>}</pre><h3>Conclusion</h3><p>While AWS Lambda is a fantastic tool, its overuse in Step Functions can increase costs, introduce unnecessary latency, and add complexity. With AWS continuously expanding direct integrations, you can now eliminate Lambda functions for many common tasks, including calling AWS services, processing data, and handling API interactions.</p><p>In an upcoming post, we&#39;ll explore detailed numbers and performance comparisons between Lambda functions and direct AWS integrations within Step Functions workflows.</p><p>By adopting native AWS integrations, you can build workflows that are faster, more cost-effective, and maintain simpler, more scalable architectures. Next time you design a Step Functions workflow, ask yourself: <strong>Do I really need a Lambda function for this?</strong> Chances are, you don’t!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cd242ab19eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load testing on AWS using Grafana K6]]></title>
            <link>https://medium.com/@emiliano.sgrano/load-testing-on-aws-using-grafana-k6-7c1acbbf2331?source=rss-a3721ecae932------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c1acbbf2331</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ecs-fargate]]></category>
            <category><![CDATA[grafana-k6]]></category>
            <dc:creator><![CDATA[Emiliano Sgrano]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 20:38:33 GMT</pubDate>
            <atom:updated>2025-01-19T20:38:33.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxFyVOxYJBRPculwTvHQbg.png" /></figure><h3>1. Introduction</h3><p>Whether you’re running a website, API, or distributed system, understanding how your application behaves under different loads is critical to ensuring its performance and reliability. This is where load testing plays a pivotal role.</p><p>AWS offers a highly scalable infrastructure to perform load testing, and when paired with <a href="https://grafana.com/docs/k6/latest/"><strong>Grafana k6</strong></a>, the process becomes even more streamlined. In this post, we’ll explore how you can effectively execute load testing on AWS using Grafana k6 and cover key considerations for optimal results.</p><h3>2. What is Grafana k6?</h3><p><strong>Grafana k6</strong> is an open-source load testing tool designed to measure the performance and reliability of applications. It allows users to create, automate, and execute tests that simulate real-world traffic and stress conditions, helping identify bottlenecks or weaknesses in systems before they go live. Integrating with Grafana enables real-time monitoring and visualization of test results, making it a powerful tool for tracking system health and performance over time.</p><p>While there are many load testing tools available, like <a href="https://jmeter.apache.org/">JMeter</a>, I chose k6 for several compelling reasons:</p><ul><li><strong>Developer-Centric and Scriptable: </strong>Script-based testing using JavaScript makes it developer-friendly and easy to integrate into CI/CD pipelines for continuous testing and performance optimization.</li><li><strong>Real-Time Monitoring and Visualization: </strong>K6 integrates seamlessly with Grafana to offer real-time dashboards and visual insights, enabling easy monitoring of test results and system performance metrics.</li><li><strong>Integrations: </strong>Grafana k6 supports seamless integration with a variety of systems, including: <br>- <a href="https://grafana.com/"><strong>Grafana</strong></a><strong>:</strong> For real-time visualization and reporting of performance metrics.<br>- <a href="https://prometheus.io/"><strong>Prometheus</strong></a><strong>:</strong> For monitoring and alerting on test results.<br>- <a href="https://aws.amazon.com/cloudwatch/"><strong>AWS CloudWatch</strong></a><strong>:</strong> For tracking system performance alongside test metrics.<br>- <a href="https://www.influxdata.com/"><strong>InfluxDB</strong></a><strong>:</strong> For storing and querying time-series data generated during tests.</li></ul><p>These integrations make k6 a versatile tool for teams already invested in observability stacks.</p><ul><li><strong>Extensibility with Extensions: </strong>k6 can be extended to suit diverse use cases through its rich ecosystem of extensions. Examples include:<br>- <strong>xk6:</strong> A framework to create custom k6 extensions, enabling support for additional protocols or functionality.<br>- <strong>xk6-websockets:</strong> For testing real-time applications relying on WebSocket connections.<br>- <strong>xk6-distributed-tracing:</strong> For integrating performance testing with distributed tracing tools like OpenTelemetry or Jaeger.<br>H<a href="https://grafana.com/docs/k6/latest/extensions/explore/">ere</a> you can find a full list of extensions.</li><li><strong>Scalable Load Testing: </strong>Allows for scalable load and performance testing, simulating real-world user traffic to assess an application’s capacity under stress</li></ul><h3>3. Types of Load Testing</h3><p>Grafana k6 supports various types of load testing, each serving a distinct purpose in your performance testing strategy. Let’s explore these types from basic validation to complex stress scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*GutuaKzGDbdqMAZ9JF0Tyw.png" /></figure><h3>1. Smoke Testing</h3><p>Smoke testing is your first line of defense in load testing. Before running more intensive tests, this basic validation ensures your system functions correctly under minimal load.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*nMu9tsQQmD2HlHRURXRWcw.png" /></figure><p><strong>2. Average Load Testing</strong></p><p>Once your smoke tests pass, the next step is to evaluate your system under normal conditions. Average load testing simulates typical day-to-day user traffic, helping you verify that your application performs well under expected load.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*wC3lLwZDLJcNPbJjVxFcYw.png" /></figure><p><strong>3. Stress Testing</strong></p><p>After confirming your system handles normal loads well, stress testing takes things further. This type of testing pushes your system beyond its comfort zone to identify breaking points and performance bottlenecks.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*b-COKpBMA1AmJVygBvpDQg.png" /></figure><p><strong>4. Spike Testing</strong></p><p>While stress testing gradually increases load, spike testing simulates sudden traffic surges. This is particularly relevant for applications that might experience unexpected traffic spikes, such as e-commerce sites during flash sales.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*WTABJwdI0M7COLVktrWe8Q.png" /></figure><p><strong>5. Soak Testing</strong></p><p>While spike and stress tests reveal how your system handles intense loads over short periods, they might miss issues that only surface over time. This is where soak testing comes in. By running sustained load tests over extended periods — typically hours or even days — soak testing examines your system’s long-term stability and performance, uncovering subtle issues like memory leaks, resource exhaustion, or gradual performance degradation that might otherwise go unnoticed in shorter tests.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Kj7lXiOEahFR0_Nvoxdjrg.png" /></figure><p><strong>6. Breakpoint Testing</strong></p><p>While stress testing helps identify that your system can fail under load, breakpoint testing takes a more precise approach. Rather than simply pushing the system until it breaks, this methodology systematically identifies the exact threshold where performance begins to degrade or fail. By pinpointing these specific limits, you can establish clear capacity planning guidelines and set realistic performance SLAs for your application.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*91vPcQsEkIpBYq5fY_dUBQ.png" /></figure><h3>4. Solution and Implementation</h3><p>While a single blog post can’t cover all of Grafana k6’s capabilities, I’ll show you a cost-effective solution that leverages AWS ECS for load testing. This solution is easily customizable and adaptable to your specific needs.</p><h3>Deployment Steps</h3><ol><li>Follow the <a href="https://github.com/sgrilux/aws-solution-load-testing/blob/main/README.md">README</a> to deploy the solution to your account using Terraform</li><li>Once deployed to your ECS Cluster, run load tests using the make command provided</li><li>After test completion:<br>a. A report is automatically uploaded to an S3 bucket<br>b. The report is served via CloudFront distribution<br>c. Access is protected by Lambda@Edge basic authentication<br>d. Report URL is sent to your email through SNS</li></ol><p>An <strong>index.html</strong> file provides a centralised view of all generated reports, organised by:</p><ul><li>Application name</li><li>Environment (e.g. development, staging, production)</li></ul><p>This hierarchical organization makes it easy to track and compare test results across different scenarios and deployments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Wk-Rz8iSzKhJ-NB_yEpLHA.png" /></figure><p>Each load test generates a comprehensive report using the xk6-dashboard extension, which includes:</p><ul><li>HTTP Performance overview</li><li>Failed request analysis</li><li>Virtual user statistics</li><li>Response time distributions</li><li>Blocked request analysis</li><li>…and much more.</li></ul><p>The dashboard presents these metrics through interactive visualizations, enabling you to:</p><ul><li>Identify performance bottlenecks</li><li>Track system behavior under load</li><li>Compare results across different test runs</li><li>Share insights with stakeholders</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*wVxnRXtKfCsxRyeCH7RQzQ.png" /></figure><p>For those eager to get started, the <a href="https://github.com/sgrilux/aws-solution-load-testing">codebase</a> provided in this blog includes Terraform scripts for provisioning infrastructure and sample k6 scripts.</p><h3>5. Key Considerations</h3><p>When implementing load testing on AWS with Grafana k6, keep these important factors in mind:</p><p><strong>Security and Compliance: </strong>Ensure your load testing adheres to AWS’s policies, particularly regarding:</p><ul><li>Restrictions on unauthorised activities like DDoS simulations</li><li>Pre-approval requirements for certain types of tests</li><li>Compliance with AWS’s acceptable use policy</li></ul><p><strong>Network Bandwidth Management: </strong>High-volume test traffic can impact your infrastructure:</p><ul><li>Monitor network resource utilization</li><li>Consider potential effects on other services</li><li>Plan tests during off-peak hours when possible</li></ul><p><strong>Cost Control: </strong>Load testing can lead to increased resource usage:</p><ul><li>Set up cost monitoring and alerts</li><li>Plan test schedules to optimize resource usage</li><li>Consider using AWS cost allocation tags for better tracking</li></ul><h3>6. Conclusion</h3><p>Load testing is a crucial step in ensuring the scalability and reliability of your applications. Leveraging the combination of AWS and Grafana k6 provides a robust solution for modern load testing needs. From creating scalable test scenarios to visualizing performance metrics, this stack empowers teams to optimize their systems with confidence.</p><p>By following the steps and considerations outlined in this blog, you’ll be well on your way to mastering load testing on AWS. Whether you’re preparing for peak traffic or building resilient microservices, Grafana k6 and AWS make a powerful pair to elevate your performance testing strategy.</p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c1acbbf2331" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Automate AWS ECS Blue/Green Deployment with Terraform]]></title>
            <link>https://medium.com/aws-specialists/how-to-automate-aws-ecs-blue-green-deployment-with-terraform-0a5286cbd22f?source=rss-a3721ecae932------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a5286cbd22f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-codepipeline]]></category>
            <category><![CDATA[aws-code-deploy]]></category>
            <category><![CDATA[ec]]></category>
            <category><![CDATA[blue-green-deployment]]></category>
            <dc:creator><![CDATA[Emiliano Sgrano]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 18:19:58 GMT</pubDate>
            <atom:updated>2024-11-26T18:28:22.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Automate AWS ECS Blue/Green Deployment with Terraform" src="https://cdn-images-1.medium.com/max/1024/1*3l3wo_3kYOPWUfhR8rps_Q@2x.jpeg" /></figure><p>A Blue/Green deployment is a deployment strategy that allows for seamless updates of an application with minimal downtime. In this approach, two separate environments, the “Blue” and the “Green,” coexist.</p><p>The “Blue” environment represents the current production version, while the “Green” environment is a duplicate of the production environment where the new version is deployed.</p><p>To switch from Blue to Green, a simple change in a load balancer or DNS routing is made, directing traffic to the new environment. This enables thorough testing and validation of the Green environment before making it the new production version, ensuring a smooth transition.</p><p>Here’s a simple diagram illustrating the concept:</p><figure><img alt="Simple diagram illustrating the Blue/green deployment concept with Terraform" src="https://cdn-images-1.medium.com/max/1024/1*3nAy-WdbarjBHCE26DAiwA.png" /></figure><p>During a Blue/Green deployment, traffic is initially routed to the Blue environment.</p><p>Once the Green environment is verified to function correctly, traffic is switched to it, making it the new production environment, while the Blue environment remains available as a backup as long as needed.</p><p>This approach minimizes the risk of deployment-related issues impacting users and allows for quick rollbacks if problems arise in the Green environment.</p><p>In this blog post, I’ll show you how to automate Blue/Green deployment using <a href="https://aws.amazon.com/codepipeline/">CodePipeline</a>, <a href="https://aws.amazon.com/codebuild/">CodeBuild</a>, and <a href="https://aws.amazon.com/codedeploy/">CodeDeploy</a>.</p><p><strong>The Process</strong></p><ol><li>A developer pushes the new version of the application to Git.</li><li>CodePipeline is triggered and starts a BuildStage using CodeBuild, which creates a new Docker image of the application and pushes it to ECR.</li><li>CodeBuild artifacts, such as the ECS task and image definitions, are stored in S3.</li><li>The next step is the deployment, managed by CodeDeploy, which takes the artifacts and uses them to deploy the new version of the service on ECS in a different target group.</li><li>Once the deployment is completed, the CodeDeploy automatically shifts the traffic from the blue target group to the green.</li></ol><p>Here is the diagram that shows what we are going to implement. You can <a href="https://github.com/RedeployAB/ecs-bg-deployment-example">find the full terraform code here</a>.</p><figure><img alt="Architecture diagram of AWS ECS Blue/Green Deployment with Terraform" src="https://cdn-images-1.medium.com/max/1024/1*8PLyb256a_xcxrDt6BnXJA.png" /></figure><p><strong>The Setup</strong></p><p>To follow this tutorial, you will need the following:</p><ul><li>An AWS account</li><li>Terraform installed on your local machine</li><li>An ECS cluster</li><li>A bucket for CodeBuild artifacts</li></ul><h3><strong>1. Create a Task Definition and Service on ECS</strong></h3><p>First, we must create an <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html">Amazon Elastic Container Service (ECS) service</a> that will serve our application.</p><p>An ECS Service is a higher-level abstraction that allows you to define how many tasks (instances of a container) should run and maintain a specified number of tasks in a specified state. ECS Services ensure that a specified number of tasks are running and healthy at all times, making them a fundamental component for managing and scaling containerized applications.</p><p>The service will be behind an application load balancer and a target group. However, for a Blue/Green deployment, you need to create two Target Groups. We will name them Blue and Green, respectively.</p><p>It is also important to ensure that the deployment controller is set to “CODE_DEPLOY” when creating the ECS Service.</p><p>Below is an example that creates a Task Definition, an Application Load Balancer (ALB), the Blue and Green Target Groups, and the ECS Service.</p><pre># Task Definition <br>resource &quot;aws_ecs_task_definition&quot; &quot;example&quot; { <br>  family                   = &quot;example&quot; <br>  execution_role_arn       = aws_iam_role.execution_role.arn <br>  network_mode             = &quot;awsvpc&quot; <br>  requires_compatibilities = [&quot;FARGATE&quot;] <br>  cpu                      = 1024 <br>  memory                   = 2048 <br> <br>  container_definitions = jsonencode([ <br>    { <br>      name  = &quot;example&quot; <br>      image = &quot;nginx:latest&quot; <br> <br>      portMappings = [ <br>        { <br>          containerPort = 80 <br>          hostPort   = 80 <br>        } <br>      ], <br> <br>      logConfiguration = { <br>        logDriver = &quot;awslogs&quot; <br>        options = { <br>          awslogs-group         = &quot;/ecs/example&quot; <br>          awslogs-region        = &quot;eu-west-1&quot; <br>          awslogs-create-group  = &quot;true&quot; <br>          awslogs-stream-prefix = &quot;example&quot; <br>        } <br>      } <br> <br>      essential = true <br>      memory    = 512 <br>      cpu       = 256 <br>    } <br>  ]) <br>} <br> <br># Public Load Balancer <br>resource &quot;aws_lb&quot; &quot;public&quot; { <br>  name               = &quot;example-alb&quot; <br>  internal           = false <br>  load_balancer_type = &quot;application&quot; <br>  subnets            = var.public_subnets <br>  security_groups    = [aws_security_group.alb.id] <br> <br>} <br> <br># Blue Target Group <br>resource &quot;aws_lb_target_group&quot; &quot;blue&quot; { <br>  name        = &quot;example-target-group-blue&quot; <br>  port        = 80 <br>  protocol    = &quot;HTTP&quot; <br>  vpc_id      = var.vpc_id <br>  target_type = &quot;ip&quot; <br> <br>  health_check { <br>    path     = &quot;/&quot; <br>    port     = 80 <br>    protocol = &quot;HTTP&quot; <br>  } <br>} <br> <br># Green Target Group <br>resource &quot;aws_lb_target_group&quot; &quot;green&quot; { <br>  name        = &quot;example-target-group-green&quot; <br>  port        = 80 <br>  protocol    = &quot;HTTP&quot; <br>  vpc_id      = var.vpc_id <br>  target_type = &quot;ip&quot; <br> <br>  health_check { <br>    path     = &quot;/&quot; <br>    port     = 80 <br>    protocol = &quot;HTTP&quot; <br>  } <br>} <br> <br># ALB Listener <br>resource &quot;aws_lb_listener&quot; &quot;example&quot; { <br>  load_balancer_arn = aws_lb.public.arn <br>  port              = 80 <br>  protocol          = &quot;HTTP&quot; <br> <br>  default_action { <br>    type             = &quot;forward&quot; <br>    target_group_arn = aws_lb_target_group.blue.arn <br>  } <br> <br>  lifecycle { <br>    ignore_changes = [default_action] <br>  } <br>} <br> <br># ECS Service <br>resource &quot;aws_ecs_service&quot; &quot;example&quot; { <br>  name            = &quot;example&quot; <br>  cluster         = &quot;my-ecs-cluster&quot; <br>  task_definition = aws_ecs_task_definition.example.arn <br>  desired_count   = 1 <br>  launch_type     = &quot;FARGATE&quot; <br> <br>  deployment_controller { <br>    type = &quot;CODE_DEPLOY&quot; <br>  } <br> <br>  network_configuration { <br>    subnets         = var.private_subnets <br>    security_groups = [aws_security_group.service.id] <br>  } <br> <br>  load_balancer { <br>    target_group_arn = aws_lb_target_group.blue.arn <br>    container_name   = var.service_name <br>    container_port   = 80 <br>  } <br>} </pre><p>As shown in the example above, the deployment controller for the ECS Service is set to “CODE_DEPLOY.” Additionally, the ALB Listener has a lifecycle attribute set to ignore changes. This is because CodeDeploy deploys the application to the other Target Group and automatically switches the ALB listener from the Blue to the Green Target Group once the deployment is completed.</p><h3><strong>2. Automate the deployment process with CodeDeploy</strong></h3><p>AWS CodeDeploy is a fully managed service, and it will be used to automate deploying our service to ECS.</p><p>Below is an example of a Terraform code snippet to automate AWS ECS blue/green deployment using AWS CodeDeploy. It includes the configuration for the deployment group, deployment style, blue/green deployment settings, ECS service, and load balancer information.</p><pre>resource &quot;aws_codedeploy_app&quot; &quot;example&quot; { <br>  compute_platform = &quot;ECS&quot; <br>  name             = &quot;example&quot; <br>} <br> <br>resource &quot;aws_codedeploy_deployment_group&quot; &quot;example&quot; { <br>  app_name               = aws_codedeploy_app.example.name <br>  deployment_group_name  = &quot;example-deployment-group&quot; <br>  deployment_config_name = &quot;CodeDeployDefault.ECSAllAtOnce&quot; <br>  service_role_arn       = aws_iam_role.codedeploy.arn <br> <br>  auto_rollback_configuration { <br>    enabled = true <br>    events  = [&quot;DEPLOYMENT_FAILURE&quot;] <br>  } <br> <br>  deployment_style { <br>    deployment_type   = &quot;BLUE_GREEN&quot; <br>    deployment_option = &quot;WITH_TRAFFIC_CONTROL&quot; <br>  } <br> <br>  blue_green_deployment_config { <br>    deployment_ready_option { <br>      action_on_timeout = &quot;CONTINUE_DEPLOYMENT&quot; <br>    } <br> <br>    terminate_blue_instances_on_deployment_success { <br>      action                           = &quot;TERMINATE&quot; <br>      termination_wait_time_in_minutes = 5 <br>    } <br>  } <br> <br>  ecs_service { <br>    service_name = aws_ecs_service.example.name <br>    cluster_name = &quot;my-ecs-cluster&quot; <br>  } <br> <br>  load_balancer_info { <br>    target_group_pair_info { <br>      prod_traffic_route { <br>        listener_arns = [aws_lb_listener.example.arn] <br>      } <br> <br>      target_group { <br>        name = aws_lb_target_group.blue.arn <br>      } <br> <br>      target_group { <br>        name = aws_lb_target_group.green.arn <br>      } <br>    } <br>  } <br>} </pre><p>In this example, we are utilizing the deployment configuration <strong>CodeDeployDefault.ECSAllAtOnce</strong>, which implies that the entire traffic will be swiftly transitioned to the new environment. However, you have the flexibility to configure alternative settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vc8EYGZba51ty9R1XFtuhg.png" /></figure><p>CodeDeploy requires a file called <strong>appspec.yml</strong> that contains all the necessary information for deploying our service to ECS.</p><p>This file, along with a <strong>taskdef.json</strong> (task definition file), will be placed in the root folder of our application.</p><h3><strong>3. Build and push the Docker Image with CodeBuild</strong></h3><p>CodeBuild is a fully managed service provided by AWS. It is used to build and push our Docker image to ECR (Elastic Container Registry).</p><p>To use CodeBuild, you need to have a <strong>buildspec.yml</strong> file placed in the root folder of your application, along with the <em>appspec.yml</em> and <em>taskdef.json</em> files described above.</p><p>The <em>buildspec.yml</em> file will contain all the necessary commands to create and push the Docker image to ECR.</p><p>Here is an example of a CodeBuild project:</p><pre>resource &quot;aws_codebuild_project&quot; &quot;example&quot; { <br>  name          = &quot;example&quot;<br>  description   = &quot;Example App&quot; <br>  service_role  = aws_iam_role.codebuild.arn <br>  build_timeout = &quot;5&quot; <br> <br>  artifacts { <br>    type = &quot;NO_ARTIFACTS&quot; <br>  } <br> <br>  environment { <br>    compute_type    = &quot;BUILD_GENERAL1_SMALL&quot; <br>    image           = &quot;aws/codebuild/standard:7.0&quot; <br>    type            = &quot;LINUX_CONTAINER&quot; <br>    privileged_mode = true <br> <br>  source { <br>    type            = &quot;GITHUB&quot; <br>    location        = &quot;https://github.com/example/example.git&quot; <br>    git_clone_depth = 1 <br>  } <br>} </pre><h3><strong>4. Orchestrate the Components with CodePipeline</strong></h3><p>Now that we have all the components in place, we need something to orchestrate everything. CodePipeline comes to the rescue.</p><p>The following example creates a pipeline with three stages: Source, Build, and Deploy.</p><ul><li><strong>Source:</strong> Download Source from Git.</li><li><strong>Build:</strong> Triggers a build using CodeDeploy.</li><li><strong>Deploy:</strong> Deploys the application to ECS via CodeDeploy.</li></ul><pre>resource &quot;aws_codepipeline&quot; &quot;example&quot; { <br>  name     = &quot;example-pipeline&quot; <br>  role_arn = aws_iam_role.codepipeline.arn <br> <br>  artifact_store { <br>    location = &quot;artifact-bucket-example&quot; <br>    type     = &quot;S3&quot; <br>  } <br> <br>  stage { <br>    name = &quot;Source&quot; <br> <br>    action { <br>      name             = &quot;Source&quot; <br>      category         = &quot;Source&quot; <br>      owner            = &quot;AWS&quot; <br>      provider         = &quot;CodeStarSourceConnection&quot; <br>      version          = &quot;1&quot; <br>      output_artifacts = [&quot;SourceArtifact&quot;] <br> <br>      configuration = { <br>        ConnectionArn    = aws_codestarconnections_connection.github.arn <br>        FullRepositoryId = &quot;example/example&quot; <br>        BranchName       = &quot;main&quot; <br>      } <br>    } <br>  } <br> <br>  stage { <br>    name = &quot;Build&quot; <br> <br>    action { <br>      name             = &quot;Build&quot; <br>      category         = &quot;Build&quot; <br>      owner            = &quot;AWS&quot; <br>      provider         = &quot;CodeBuild&quot; <br>      version          = &quot;1&quot; <br>      input_artifacts  = [&quot;SourceArtifact&quot;] <br>      output_artifacts = [&quot;BuildArtifact&quot;] <br> <br>      configuration = { <br>        ProjectName = aws_codebuild_project.example.name <br>      } <br>    } <br>  } <br> <br>  stage { <br>    name = &quot;Deploy&quot; <br> <br>    action { <br>      name            = &quot;DeployAction&quot; <br>      category        = &quot;Deploy&quot; <br>      owner           = &quot;AWS&quot; <br>      provider        = &quot;CodeDeployToECS&quot; <br>      version         = &quot;1&quot; <br>      input_artifacts = [&quot;BuildArtifact&quot;] <br> <br>      configuration = { <br>        ApplicationName                = aws_codedeploy_app.example.name <br>        DeploymentGroupName            = aws_codedeploy_deployment_group.example.deployment_group_name <br>        TaskDefinitionTemplateArtifact = &quot;BuildArtifact&quot; <br>        TaskDefinitionTemplatePath     = &quot;taskdef.json&quot; <br>        AppSpecTemplateArtifact        = &quot;BuildArtifact&quot; <br>        AppSpecTemplatePath            = &quot;appspec.yml&quot; <br>      } <br>    } <br>  } <br>} </pre><p>As shown in the example above, the pipeline is triggered whenever there is a push to the main branch of a Git repository.</p><p>CodePipeline utilizes CodeStar connections to establish a connection with GitHub using the GitHub provider v2. Here is how you can create a connection to GitHub using Terraform.</p><pre>resource &quot;aws_codestarconnections_connection&quot; &quot;github&quot; { <br>  name          = &quot;github-connection&quot; <br>  provider_type = &quot;GitHub&quot; <br>}</pre><p>Once the connection is created, it enters a PENDING status and requires manual approval. <a href="https://docs.aws.amazon.com/codepipeline/latest/userguide/connections-github.html#connections-github-cli">More information in AWS’ documentation here</a>.</p><h3><strong>5. The Deployment</strong></h3><p>Now, CodePipeline will be triggered automatically every time you push the code to Git.</p><p>As shown in the picture below, the pipeline starts the Source stage by downloading the code from Git. The second stage is building the application via CodeBuild (instruction provided from the <em>buildspec.yml</em>).</p><figure><img alt="The code pipeline for AWS Blue/green deployment with terraform, showing the stages of; source, build, deploy.w" src="https://cdn-images-1.medium.com/max/1024/1*qNk3xGvemt6QrXMXS_Ek_Q.png" /></figure><p>In the last stage, deploy the application to ECS (Blue/Green) and shift the traffic to the new environment once everything is completed. You can see the progress in the CodeDeploy console, where you can also Stop the deployment.</p><figure><img alt="An example of deployment status of AWS ECS Blue/Green Deployment with Terraform" src="https://cdn-images-1.medium.com/max/1024/1*kc41SrPZVyerlpUCqjrQcw.png" /></figure><figure><img alt="An example of traffic shifting progress of AWS ECS Blue/Green deployment with Terraform" src="https://cdn-images-1.medium.com/max/1024/1*EGkhCRuwNQXxkKx7aICfZw.png" /></figure><h3><strong>Conclusion</strong></h3><p>In summary, the integration of AWS ECS with Terraform for Blue/Green deployments offers a robust and efficient strategy for application updates. By leveraging AWS services like CodePipeline, CodeBuild, and CodeDeploy, this approach ensures minimal downtime and higher stability assurance during deployments. The Blue/Green model, characterized by its parallel environment structure, allows for thorough testing in the Green environment before transitioning to production. This method significantly reduces the risk of deployment-related issues, offering a safety net through quick rollbacks if needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a5286cbd22f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aws-specialists/how-to-automate-aws-ecs-blue-green-deployment-with-terraform-0a5286cbd22f">How to Automate AWS ECS Blue/Green Deployment with Terraform</a> was originally published in <a href="https://medium.com/aws-specialists">AWS Specialists</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>