<?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 Kevin MONVOISIN on Medium]]></title>
        <description><![CDATA[Stories by Kevin MONVOISIN on Medium]]></description>
        <link>https://medium.com/@monvoisinkevin?source=rss-49bf7667589a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2ckSyN-lbvCFoL8pvbQ4bA.jpeg</url>
            <title>Stories by Kevin MONVOISIN on Medium</title>
            <link>https://medium.com/@monvoisinkevin?source=rss-49bf7667589a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:16:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@monvoisinkevin/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[Cut self-hosted Azure DevOps agent costs using AWS Fargate]]></title>
            <link>https://medium.com/@monvoisinkevin/cut-self-hosted-azure-devops-agent-costs-using-aws-fargate-582290e489ac?source=rss-49bf7667589a------2</link>
            <guid isPermaLink="false">https://medium.com/p/582290e489ac</guid>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[ecs-fargate]]></category>
            <category><![CDATA[azure-devops-pipeline]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Kevin MONVOISIN]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 19:24:42 GMT</pubDate>
            <atom:updated>2025-10-26T19:24:42.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>⚡ TL:DR</h3><p>In this article, we’ll cover how to use an AWS ECS Fargate cluster to run Azure DevOps agents and reduce the cost of our current agents. We’ll be creating a serverless solution, and the source code is available in the conclusion section of the article.</p><h3>📋 Table of content</h3><p>· <a href="#2887">⚡ TL:DR</a><br>· <a href="#510b">📋 Table of content</a><br>· <a href="#e37e">🌍 Introduction</a><br>· <a href="#7afc">🛠️Requirements</a><br>· <a href="#a39b">🤔 Solution Architecting</a><br>· <a href="#40f8">🔨Implementing our solution</a><br>· <a href="#a606">👀 Room for improvements</a><br>· <a href="#0c64">🏁 Conclusion</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*izYLN8vIYPtyJyTXKYDV4A.gif" /><figcaption>Welcome, take a seat and enjoy!</figcaption></figure><h3>🌍 Introduction</h3><p>Are you currently using Azure DevOps as your CI/CD tool and spending way too much each month by running your own agent on EC2 instances or ECS services 24/7? This article might interest you.</p><p>At my current workplace, we use Azure DevOps because we have workloads on both AWS and Azure. We have dedicated agents running 24/7 on AWS, which costs a lot of money. I want to find a way to reduce this monthly cost for agents that aren’t needed as frequently.</p><p>In this article, we will go through the creation of an on-demand agent system. You will provision agents only when required, and they will automatically terminate once the stage is over, saving you additional money.</p><p>We will use a few AWS services to create a serverless solution. The following services and technologies will be used:</p><ul><li>AWS Lambda Function</li><li>AWS DynamoDB</li><li>AWS Elastic Cluster Service — FARGATE</li><li>AWS Secrets Manager</li><li>AWS API Gateway</li><li>Python 3</li><li>Azure DevOps (obviously)</li></ul><h3>🛠️Requirements</h3><p>To create this solution, you will need a text editor or any IDE of your choice. You will also require the following:</p><ul><li>Terraform</li><li>An AWS Account</li><li>Azure DevOps (from now on, we’ll refer to it as ADO)</li><li>Docker</li><li>Git (if you want to get the source code, available at the end)</li></ul><h3>🤔 Solution Architecting</h3><p>If you’re new here, you should know that I love to do research and dig deep before coming up with a solution. I like to try things and learn from them. We will go through a list of possible approaches and ways to achieve our goal: reducing costs by using on-demand agents in ADO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*mG1wO1S1_VxtOkYT.gif" /></figure><p>The first thing we might want to consider is the solution for hosting the agent. We have countless options, such as an EC2 instance, creating a pod on an EKS cluster, creating an ECS cluster. There is a wide range of choices available.</p><p>We want to reduce our costs. If we don’t already have an EKS cluster available, we won’t use EKS. That’s my situation right now — I don’t have an EKS cluster.<br>We have two other options: EC2 or ECS. If you’ve read my previous article, you know I like ECS, and an EC2 instance might seem too “heavy” to manage. I will be using an ECS Fargate cluster and tasks to host my agents.</p><p>Now, we need to find a way for ADO to communicate with AWS and spawn agents on the fly. But how? I’m not an ADO expert, but since I use it at work, I have some knowledge of it. There’s a feature called “Service Connections.” I like that name — it sounds like I can connect ADO to AWS here! AAAAAAAAAAAAND there’s something called “Generic,” which allows me to provide any URL to be called. Do you see where I’m going?</p><p>Great, we have a way to communicate with AWS from ADO, but how do we use it? By exploring a bit further, I found that when we create an “Agent Pool,” there’s a tab called “Approvals and Checks.” This feature allows us to add our newly created Generic Service Connection. But what does that mean?</p><p>It means that when the agent pool starts a new stage, it will reference our defined Approvals and Checks and trigger our service connection request. Our defined endpoint will then need to call ADO back and say, “Hey, my check is complete and succeeded — go ahead and continue!”</p><p>Now, we need to think about our request receiver on the AWS side. We have multiple options again: an EC2 instance with a Python/Node.js web server, an ECS task running the same code as the EC2 instance, a Lambda function with Lambda URL enabled, or an API Gateway/Lambda function combo.</p><p>I prefer the API Gateway/Lambda function approach because, with API Gateway, we can define throttling, attach an AWS Web Application Firewall, use AWS Shield, create stages… The list of benefits is long enough to make this the preferred solution.</p><p>Let’s have a small recap of what we have so far. We have an approval &amp; check integrated into our Agent Pool that will call an API Gateway that triggers a Lambda Function. Our Lambda Function will start a new ECS task. Great, seems like we’re fine right? Well, technically yes but, we need a way to tell ADO that the agent is ready, when the agent is ready.</p><p>If you’re familiar with AWS Lambda and API Gateway, you know that API Gateway has a timeout of 29 seconds. This value can be increased (since June 2024), but it still takes time to create the ECS task, wait for it to start running, and then wait for the agent to be ready.</p><p>How can we improve this? Our task will produce logs, and if you look at an ADO agent’s logs, you’ll see something like “Listening for jobs” when the agent is ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*xw747LbqQsbJNVKLbuemxw.png" /></figure><p>You may know about a feature called “Log Subscription Filter.” We can use it to monitor a CloudWatch Log Group for a specific pattern and trigger an action whenever that pattern is detected. And what can tell ADO that the agent is ready? You guessed it — a Lambda function! But here’s the challenge: how can this second Lambda function know which endpoint to call and with what values when the agent is ready? The solution: let’s include a database in our architecture.</p><p>When it comes to databases on AWS, and considering cost savings, the first solution that comes to mind is AWS DynamoDB. DynamoDB offers an “On-Demand” configuration, so we are billed only when writing or reading items from the database, we’re not charged when nothing happens. Plus, we won’t be using complex queries, so NoSQL works perfectly for our use case.</p><p>To prevent anyone from using our API Gateway if they discover the endpoint and URL, we will include a password that ADO will send to our API. We will also need a Personal Access Token to make requests to ADO. To store these secrets, we will use AWS Secrets Manager.</p><p>It looks like our architecture is coming together. Here is our schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twNm5U_-U0_F_5dSqVxDxQ.png" /></figure><h3>🔨Implementing our solution</h3><p>To implement our solution, we will use Infrastructure as Code (Terraform), GitHub to store our code, AWS, and ADO.</p><p>Please note that I won’t cover all the code in this article, but a link to a GitHub repository will be available at the end.</p><p>We’ll start by creating the API Gateway and its stage to obtain the values required for ADO.</p><pre># apigw.tf<br>resource &quot;aws_api_gateway_rest_api&quot; &quot;aod_api&quot; {<br>  name        = &quot;ado-on-demands-agents-api&quot;<br>  description = &quot;API Gateway for Agents On Demand&quot;<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br><br>resource &quot;aws_api_gateway_resource&quot; &quot;create_ecs_task&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.aod_api.id<br>  parent_id   = aws_api_gateway_rest_api.aod_api.root_resource_id<br>  path_part   = &quot;create-ecs-task&quot;<br>}<br><br>resource &quot;aws_api_gateway_method&quot; &quot;post_create_ecs_task&quot; {<br>  rest_api_id   = aws_api_gateway_rest_api.aod_api.id<br>  resource_id   = aws_api_gateway_resource.create_ecs_task.id<br>  http_method   = &quot;POST&quot;<br>  authorization = &quot;NONE&quot;<br>}<br><br><br>resource &quot;aws_api_gateway_deployment&quot; &quot;aod_api_deployment&quot; {<br>  depends_on  = [aws_api_gateway_integration.lambda_integration]<br>  rest_api_id = aws_api_gateway_rest_api.aod_api.id<br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br><br>resource &quot;aws_api_gateway_stage&quot; &quot;aod_api_stage&quot; {<br>  stage_name    = &quot;prod&quot;<br>  rest_api_id   = aws_api_gateway_rest_api.aod_api.id<br>  deployment_id = aws_api_gateway_deployment.aod_api_deployment.id<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br></pre><p>We will also create the authentication password and output it to the console. I like the idea of not storing sensitive values in the Terraform state, so we’ll use an “ephemeral” resource type to generate the password dynamically.</p><pre>ephemeral &quot;random_password&quot; &quot;authentication_password&quot; {<br>  length           = 32<br>  special          = true<br>  upper            = true<br>  lower            = true<br>  override_special = &quot;!#$%^*&quot;<br>}<br><br>resource &quot;aws_secretsmanager_secret&quot; &quot;authentication_password&quot; {<br>  name                    = &quot;ado/on_demands/authentication&quot;<br>  description             = &quot;Authentication secret use for on demands agent used between AzureDevOps and ApiGW&quot;<br>  recovery_window_in_days = 7<br>}<br><br><br>resource &quot;aws_secretsmanager_secret_version&quot; &quot;authentication_password&quot; {<br>  secret_id = aws_secretsmanager_secret.authentication_password.id<br>  secret_string_wo = jsonencode({<br>    password = ephemeral.random_password.authentication_password.result<br>  })<br><br>  secret_string_wo_version = 1<br>}<br><br>resource &quot;aws_secretsmanager_secret&quot; &quot;pat_token&quot; {<br>  name                    = &quot;ado/on_demands/pat_token&quot;<br>  description             = &quot;Personal Access Token for Azure DevOps&quot;<br>  recovery_window_in_days = 7<br>}</pre><p>Now, let’s create an output.tf file and get the values required on ADO’s side.</p><pre>output &quot;authentication_secret_arn&quot; {<br>  description = &quot;The ARN of the secret containing the authentication password for the Lambda function.&quot;<br>  value       = aws_secretsmanager_secret.authentication_password.arn<br>}<br><br>output &quot;get_secret_authentication_password_value&quot; {<br>  description = &quot;The value of the authentication password for the Lambda function.&quot;<br>  value       = &quot;aws secretsmanager get-secret-value --secret-id ${aws_secretsmanager_secret.authentication_password.id} --query SecretString --output text&quot;<br>}<br><br>output &quot;api_gw_invoke_url&quot; {<br>  description = &quot;The invoke URL of the API Gateway&quot;<br>  value       = &quot;${aws_api_gateway_stage.aod_api_stage.invoke_url}/${aws_api_gateway_resource.create_ecs_task.path_part}&quot;<br>}</pre><p>Great! Now, when running terraform apply, we’ll see the secret ARN, the invoke URL, and the AWS CLI command to fetch the password value. We can then go to ADO and specify those values.</p><p>Now, go to ADO, open your project, and click the cog icon at the bottom left of the page. Select <strong>Service Connections</strong>, then click <strong>New Service Connection</strong>. Choose <strong>Generic</strong> and enter the values from the terraform apply output. In <strong>Password/Token</strong>, specify the value from Secrets Manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLxj1gwplwlRAz6lg7xxBg.png" /></figure><p>Once that’s done, we can create our new Agent Pool (or use an existing one) and integrate a new <strong>Approval and Check</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*aUIulBI2WFnt_B_oRv5JGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJ0UL0CaRPzE7dI9Y-oUig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2XQgQVyjPOpdcyH_v8y0A.png" /></figure><p>By default, a payload is already provided in the <strong>Headers</strong>. I’ve added a few new lines to include additional parameters. More information is available <a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&amp;tabs=yaml">here</a>.</p><pre>{<br>  &quot;Content-Type&quot;:&quot;application/json&quot;, <br>  &quot;PlanUrl&quot;: &quot;$(system.CollectionUri)&quot;, <br>  &quot;ProjectId&quot;: &quot;$(system.TeamProjectId)&quot;, <br>  &quot;HubName&quot;: &quot;$(system.HostType)&quot;, <br>  &quot;PlanId&quot;: &quot;$(system.PlanId)&quot;, <br>  &quot;JobId&quot;: &quot;$(system.JobId)&quot;, <br>  &quot;TimelineId&quot;: &quot;$(system.TimelineId)&quot;, <br>  &quot;TaskInstanceId&quot;: &quot;$(system.TaskInstanceId)&quot;, <br>  &quot;AuthToken&quot;: &quot;$(system.AccessToken)&quot;,<br>  &quot;StageName&quot;: &quot;$(System.StageName)&quot;,<br>  &quot;PipelineId&quot;: &quot;$(System.DefinitionId)&quot;,<br>  &quot;BuildId&quot;: &quot;$(Build.BuildId)&quot;,<br>  &quot;CollectionUri&quot;: &quot;$(System.CollectionUri)&quot;<br>}</pre><p>We have one final step on ADO to do, we have to create a Personal Access Token so our newly created agent can register itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*SsdoYrYm_Z-xi35Il5-GWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*fPiLU2jc1p9073tSyBohrw.png" /></figure><p>Here, I will be using a full-access scope. Note that you should always restrict the permissions granted when using your PAT token. Also, be aware that you’ll need to update the PAT token once it expires.</p><p>Next, go to <strong>AWS Secrets Manager</strong>, find the secret named ado/on_demands/pat_token, set the key to azure-devops-secret-token, and the value to your PAT token.</p><p>We now need to focus on creating the agent image. As mentioned earlier, we’ll be using Docker. So, let’s create a simple Dockerfile that includes only the ADO agent binaries.</p><pre>FROM ubuntu:24.04<br>RUN apt update<br>RUN apt upgrade -y<br><br>RUN apt-get install -y -qq --no-install-recommends \<br>    apt-transport-https \<br>    apt-utils \<br>    ca-certificates \<br>    curl \<br>    git \<br>    iputils-ping \<br>    jq \<br>    lsb-release \<br>    software-properties-common \<br>    wget \<br>    unzip \<br>    gnupg-agent \<br>    golang-go \<br>    groff<br><br>ENV TARGETARCH=linux-x64<br><br>WORKDIR /azp/<br><br>COPY ./start.sh ./<br>RUN chmod +x ./start.sh<br><br>RUN useradd agent<br>RUN chown agent ./<br>USER agent<br><br>USER root<br>RUN apt-get update &amp;&amp; apt-get install -y jq<br><br>ARG TARGETARCH=linux-x64<br><br>RUN curl -LsS https://download.agent.dev.azure.com/agent/4.261.0/vsts-agent-linux-x64-4.261.0.tar.gz | tar -xz -C /azp<br><br><br>RUN wget http://security.ubuntu.com/ubuntu/pool/main/o/openssl1.0/libssl1.0.0_1.0.2n-1ubuntu5.13_amd64.deb \<br>        &amp;&amp; apt install ./libssl1.0.0_1.0.2n-1ubuntu5.13_amd64.deb<br><br>ENV AGENT_ALLOW_RUNASROOT=&quot;true&quot;<br><br>ENTRYPOINT [&quot;/bin/bash&quot;, &quot;./start.sh&quot;]<br><br>HEALTHCHECK --interval=1m --timeout=10s --start-period=5s --retries=3 \<br>  CMD pgrep -F /var/run/azp_agent.pid || exit 1</pre><p>And the terraform code that will build the image and push it into our ECR Repository:</p><pre>resource &quot;aws_ecr_repository&quot; &quot;on_demands_repository&quot; {<br>  name = &quot;ado-on-demands-repository&quot;<br>}<br><br>resource &quot;null_resource&quot; &quot;build_and_push_docker_image&quot; {<br><br>  triggers = {<br>    dockerfile_hash = filemd5(&quot;${path.module}/../docker/Dockerfile&quot;)<br>  }<br><br>  provisioner &quot;local-exec&quot; {<br>    command     = &lt;&lt;EOT<br>      #!/bin/bash<br>      set -e<br>      IMAGE_TAG=${aws_ecr_repository.on_demands_repository.repository_url}:latest<br>      # Authenticate Docker to the ECR registry<br>      aws ecr get-login-password --region ${data.aws_region.current.region} | docker login --username AWS --password-stdin ${aws_ecr_repository.on_demands_repository.repository_url}<br>      # Build the Docker image<br>      docker build -t $IMAGE_TAG ${path.module}/../docker<br>      # Push the Docker image to ECR<br>      docker push $IMAGE_TAG<br>    EOT<br>    interpreter = [&quot;/bin/bash&quot;, &quot;-c&quot;]<br>  }<br>  depends_on = [aws_ecr_repository.on_demands_repository]<br><br>}</pre><p>Now, we will focus on the Lambda Function’s content. We will be creating the first Lambda that create the ECS Task.</p><pre>import boto3<br>import json<br>import os<br>import base64<br><br>import ecs # Custom file available on GitHub<br>import ado # Custom file available on GitHub<br><br><br>from logger import get_logger # Custom file available on GitHub<br>from dynamodb import write_to_dynamodb # Custom file available on GitHub<br><br>ADO_PIPELINE_FAILED_STATUS = &#39;failed&#39;<br>ADO_PIPELINE_SUCCEEDED_STATUS = &#39;succeeded&#39;<br>ADO_AGENT_ON_DEMAND_CAPABILITY = &#39;agent_on_demands&#39;<br><br>def get_authentication_secret():<br>    secret_arn = os.environ.get(&quot;ADO_AUTHENTICATION_PASSWORD&quot;)<br>    if not secret_arn:<br>        raise ValueError(&quot;Environment variable ADO_AUTHENTICATION_PASSWORD is not set&quot;)<br><br>    client = boto3.client(&#39;secretsmanager&#39;)<br>    response = client.get_secret_value(SecretId=secret_arn)<br>    secret = json.loads(response[&#39;SecretString&#39;])<br>    return secret[&#39;password&#39;]<br><br>def base64_decode(data):<br>    return base64.b64decode(data).decode(&#39;utf-8&#39;)<br><br>def get_access_denied_response():<br>    return {<br>        &#39;statusCode&#39;: 403,<br>        &#39;body&#39;: json.dumps(&#39;Forbidden: Invalid credentials&#39;)<br>    }<br><br>def get_authorization_passed_password(headers):<br>    authorization = headers.get(&#39;Authorization&#39;, &#39;&#39;)<br>    if not authorization.startswith(&#39;Basic &#39;):<br>        return None<br>    <br>    password = base64_decode(authorization.split(&#39; &#39;)[1])<br>    if password and password[0] == &#39;:&#39;:<br>        password = password[1:]<br>    return password<br><br>def fetch_pat_token():<br>    secret_arn = os.environ.get(&quot;ADO_TOKEN_ARN&quot;)<br>    client = boto3.client(&#39;secretsmanager&#39;)<br>    response = client.get_secret_value(SecretId=secret_arn)<br>    secret = json.loads(response[&#39;SecretString&#39;])<br>    return secret[&#39;azure-devops-secret-token&#39;]<br><br><br>def lambda_handler(event, context):<br><br>    logger = get_logger()<br><br>    try:  <br>        authorization = event[&#39;headers&#39;].get(&#39;Authorization&#39;, &#39;&#39;)<br>        project_id = event[&#39;headers&#39;].get(&#39;ProjectId&#39;, &#39;&#39;)<br>        hub_name = event[&#39;headers&#39;].get(&#39;HubName&#39;, &#39;&#39;)<br>        plan_id = event[&#39;headers&#39;].get(&#39;PlanId&#39;, &#39;&#39;)<br>        task_id = event[&#39;headers&#39;].get(&#39;TaskInstanceId&#39;, &#39;&#39;)<br>        job_id = event[&#39;headers&#39;].get(&#39;JobId&#39;, &#39;&#39;)<br>        authorization_token = event[&#39;headers&#39;].get(&#39;AuthToken&#39;, &#39;&#39;)<br>        stage_name = event[&#39;headers&#39;].get(&#39;StageName&#39;, &#39;&#39;)<br>        build_id = event[&#39;headers&#39;].get(&#39;BuildId&#39;, &#39;&#39;)<br>        collection_uri = event[&#39;headers&#39;].get(&#39;CollectionUri&#39;, &#39;&#39;)<br><br>        pat_token = fetch_pat_token()<br><br>        if not all([project_id, hub_name, plan_id, task_id, job_id, authorization_token]):<br>            return get_access_denied_response()<br><br>        if not authorization.startswith(&#39;Basic &#39;):<br>            ado.send_ado_pipeline_callback(collection_uri, ADO_PIPELINE_FAILED_STATUS, project_id, hub_name, plan_id, task_id, job_id, authorization_token)<br>            return get_access_denied_response()<br><br>        password = get_authentication_secret()<br>        received_password = get_authorization_passed_password(event[&#39;headers&#39;])<br><br>        if password != received_password:<br>            ado.send_ado_pipeline_callback(collection_uri, ADO_PIPELINE_FAILED_STATUS, project_id, hub_name, plan_id, task_id, job_id, authorization_token)<br>            return get_access_denied_response()<br>        <br>        ecs_response = ecs.start_ecs_task(os.environ.get(&quot;AGENT_TASK_DEFINITION_ARN&quot;), collection_uri, pat_token)<br>        ecs_task_id = ecs_response[&#39;tasks&#39;][0][&#39;taskArn&#39;].split(&#39;/&#39;)[-1]<br>        ado_callback_url = ado.get_ado_pipeline_callback_url(https://medium.com/collection_uri,%20project_id,%20hub_name,%20plan_id)<br><br>        write_to_dynamodb(ecs_task_id, authorization_token, ado_callback_url, task_id, job_id)        <br><br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: json.dumps(&#39;Request processed successfully, ECS task started&#39;)<br>        }<br>    except Exception as e:<br>        print(f&quot;Error: {str(e)}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: json.dumps({<br>                &#39;error&#39;: str(e)<br>            })<br>        }</pre><p>If you look at the lambda_handler function, it basically does the following:</p><ol><li>Checks if all required headers are provided</li></ol><p>2. Verifies that the request contains an authorization header and compares its value to the secret stored in Secrets Manager</p><p>3. Starts a new ECS task</p><p>4. Stores the task details in a DynamoDB table</p><p>Now that we can create a new task, let’s move on to the second Lambda function. This function will be triggered once the agent is running and will notify ADO.</p><pre>import gzip<br>import json<br>import base64<br>import boto3<br>import os<br>import requests<br>from logger import get_logger # Custom file available on GitHub<br><br>def process_cloudwatch_logs_data(cloudwatch_logs_data):<br>    compressed_payload = base64.b64decode(cloudwatch_logs_data)<br>    uncompressed_payload = gzip.decompress(compressed_payload)<br>    payload = json.loads(uncompressed_payload)<br>    return payload<br><br>def get_dynamodb_item(taskId):<br>    dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>    table_name = os.environ.get(&quot;DYNAMODB_TABLE_NAME&quot;)<br>    table = dynamodb.Table(table_name)<br><br>    response = table.get_item(Key={&#39;taskId&#39;: taskId})<br>    return response.get(&#39;Item&#39;, None)<br><br>def delete_dynamodb_item(taskId):<br>    dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>    table_name = os.environ.get(&quot;DYNAMODB_TABLE_NAME&quot;)<br>    table = dynamodb.Table(table_name)<br><br>    table.delete_item(Key={&#39;taskId&#39;: taskId})<br><br>def lambda_handler(event, context):<br>    logger = get_logger()<br><br>    cloudwatch_logs_data = event[&#39;awslogs&#39;][&#39;data&#39;]<br>    payload = process_cloudwatch_logs_data(cloudwatch_logs_data)<br><br>    logger.debug(f&quot;Processed payload: {json.dumps(payload)}&quot;)<br><br>    log_stream = payload.get(&#39;logStream&#39;, None)<br><br>    if log_stream is None:<br>        logger.error(&quot;logStream not found in payload&quot;)<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: json.dumps(&#39;Bad Request: logStream not found in payload&#39;)<br>        }<br><br>    task_id = log_stream.split(&#39;/&#39;)[-1] if &#39;/&#39; in log_stream else None<br>    if task_id is None:<br>        logger.error(&quot;task ID not found in logStream&quot;)<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: json.dumps(&#39;Bad Request: task ID not found in logStream&#39;)<br>        }<br>    <br>    logger.info(f&quot;Extracted task ID: {task_id}&quot;)<br>    dynamodb_item = get_dynamodb_item(task_id)<br>    <br>    if dynamodb_item is None:<br>        logger.error(f&quot;No DynamoDB item found for task ID: {task_id}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 404,<br>            &#39;body&#39;: json.dumps(&#39;Not Found: No DynamoDB item found for task ID&#39;)<br>        }<br>    <br>    logger.info(f&quot;DynamoDB item found for task ID: {task_id}, proceeding to notify ADO&quot;)<br>    authorization_token = dynamodb_item[&#39;authorizationToken&#39;]<br>    ado_callback_url = dynamodb_item[&#39;adoPipelineCallbackURL&#39;]<br>    ado_task_id = dynamodb_item[&#39;adoTaskId&#39;]<br>    ado_job_id = dynamodb_item[&#39;adoJobId&#39;]<br><br><br>    response = requests.post(<br>        ado_callback_url,<br>        headers={<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;Authorization&#39;: &#39;Basic &#39; + str((base64.b64encode(bytes(&#39;ado:&#39;+ authorization_token, &#39;ascii&#39;))), &#39;ascii&#39;)<br>        },<br>        json={<br>            &#39;name&#39;: &#39;TaskCompleted&#39;,<br>            &#39;taskId&#39;: ado_task_id,<br>            &#39;jobId&#39;: ado_job_id,<br>            &#39;result&#39;: &quot;succeeded&quot;<br>        }<br>    )<br><br>    delete_dynamodb_item(task_id)<br><br><br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(f&#39;Task ID: {task_id}&#39;)<br>    }</pre><p>If you look at the lambda_handler function, it basically does the following:</p><ol><li>Decode the CloudWatch Logs input</li><li>Extract Task ID from CloudWatch Log Stream name</li><li>Get details of task from DynamoDB</li><li>Notify Azure DevOps</li><li>Remove item from DynamoDB</li></ol><p>This is a good time to take a break and note that I won’t be covering the full infrastructure code for this solution in this article. The source code is available at the end of the article in the conclusion section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*8bpzmf1f_GaK-sCy.gif" /></figure><p>We’ve reached the final step of our solution implementation: creating the pipeline. We’ll create a new repository with a very basic pipeline that runs our beloved “Hello World” on the newly created agent :)</p><p>Here is the content of my pipeline:</p><pre>trigger:<br>  branches:<br>    include:<br>    - &#39;*&#39;<br><br>stages:<br>- stage: helloworld<br>  displayName: &#39;[DEMO] AWS Agent On Demand&#39;<br>  jobs:<br>  - job: RunAll<br>    displayName: &#39;[DEMO] AWS Agent On Demand&#39;<br>    pool:<br>      name: Medium-My-OnDemand-Agent-Pool<br>    steps:<br>    - task: CmdLine@2<br>      displayName: Hello World<br>      inputs:<br>        script: |<br>          echo &quot;Hello, World!&quot;</pre><p>Now let’s run it and see what happens !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hnjW_xPL1sXEODCBRAmSg.png" /></figure><p>As you can see, we received an HTTP 200 status code with a message indicating that the request was processed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uI9Hu9Q_oS010CITtk-qgA.png" /></figure><p>We also have our ECS task up and running. If we check the logs, we’ll see that our task is “Listening for jobs” and should be executing our job:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKC70cPqC0uRQamFdENDRQ.png" /></figure><p>Finally, if we check our pipeline in ADO, we should see that everything ran smoothly!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTIEFU_dbAjKgOFZKG9Y_g.png" /></figure><p>That’s a wrap! If you’ve made it this far, thank you, and I hope you’ve learned something new today. But stick with me — we’re not done yet. Let’s go over what we can improve in our system.</p><h3>👀 Room for improvements</h3><p><strong>Using on demand agent with 24/7 agents</strong><br>The main goal is to save money, right? But for some use cases, you might want to keep agents running 24/7, such as in a production environment. At my current company, we’ve been experimenting with capabilities. We created a capability named &quot;agent_on_demand&quot;, and the Lambda function create-ecs-task will call the Azure DevOps REST API to check the pipeline’s capabilities. If the capability is present, it creates an on-demand agent; otherwise, it does nothing and uses a provisioned agent.</p><p><strong>Task Slow Start Time</strong><br>You may have noticed that creating a new ECS task takes time, and it’s getting slower as we add more tools to our Docker image. We can speed this up by using SOCI indexes. In the near future, I might write a follow-up article on using SOCI indexes to make our solution even faster! In the meantime, check out <a href="https://github.com/awslabs/soci-snapshotter">soci-snapshotter</a>.</p><p><strong>Tasks That Fail/Crash</strong><br>Currently, we have no monitoring system for task failures. A task might continue running for any reason, and you’ll be spending money unnecessarily. Adding an auto-task killer solution will help save costs.</p><p><strong>Notification / Alerting</strong><br>Similarly, if a Lambda function fails, we currently have no way to know. We need a monitoring and alerting system to ensure everything is running smoothly.</p><h3>🏁 Conclusion</h3><p>If you are still reading this, I just want to thank you! It took quite some time implementing the solution and writing this article. I hope you have learned new things like I did.</p><p>The source code is available here: <a href="https://github.com/Synchroneyes/medium-ado-agents-on-demands-fargate/tree/main">https://github.com/Synchroneyes/medium-ado-agents-on-demands-fargate</a></p><p>Feel free to share your thoughts, I will be happy to read you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=582290e489ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an Automated Terraform Module Test factory with your CI/CD and AWS]]></title>
            <link>https://medium.com/@monvoisinkevin/build-an-automated-terraform-module-test-factory-with-your-ci-cd-and-aws-64f93fead08b?source=rss-49bf7667589a------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f93fead08b</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Kevin MONVOISIN]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 07:55:20 GMT</pubDate>
            <atom:updated>2025-06-04T15:50:27.626Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>⚡ TL:DR</strong></h3><p>This article will talk about creating a factory that automate terraform module testing and report genetation sent via Email using AWS and GitHub. The project source code is available in the “<a href="#e81a">🏁 Conclusion</a>” section.</p><h3><strong>📋 Table of content</strong></h3><p>· <a href="#da93">⚡ TL:DR</a><br>· <a href="#9e2f">📋 Table of content</a><br>· <a href="#32b1">🌍 Introduction</a><br>· <a href="#eb25">💪 Goals and Objectives</a><br>· <a href="#e3f3">🛠️ Requirements</a><br>· <a href="#c5f7">📘 About Terraform Tests</a><br>· <a href="#8744">🤔 Solution Architecting</a><br>· <a href="#adb3">🛠️ Implementing our solution</a><br>· <a href="#7fe6">👀 Room for improvements</a><br>· <a href="#e81a">🏁 Conclusion</a></p><h3><strong>🌍 Introduction</strong></h3><p>In the ever-evolving world of DevOps and Infrastructure as Code, the reliability and quality of infrastructure code have become critical concerns. Terraform, one of the leading tools for Infrastructure as Code, offers testing capabilities. This feature is pretty new and needs to become a new standard when it comes to building robust modules.</p><p>Automated testing for Terraform has become essential for maintaining reliable infrastructure deployments. Setting up an effective testing pipeline can be complex, but it provide a lot to a team, the team can focus on other topics instead of daily checking existing modules if they are still working successfully.</p><p>In this article, we will explore how to create an automated test factory for your Terraform modules. We will see how to leverage GitHub Workflows, AWS and Terraform to automate module tests on a schedule, send results to AWS and generate a report that can be sent anywhere you want, email, webhook, it’s up to you!</p><p>Now, let’s set our goals and objectives!</p><h3><strong>💪 Goals and Objectives</strong></h3><p>In this article, we want to learn more about Terraform tests and how to implement them in your Terraform modules. We also want to build an automated factory that automatically test your modules on a defined schedule, and receive a report via Email with the tests results.</p><h3><strong>🛠️ Requirements</strong></h3><p>In this article, we will be talking about few topics that you need to know, otherwise this article might not be that fun for you.</p><ul><li>Terraform — We will deploy our backend infrastructure using Terraform and write tests.</li><li>AWS — We will be using services like AWS Lambda, AWS DynamoDB, AWS Simple Notification Service.</li><li>Python — We will be writing two scripts in Python to generate a report and store data into a database.</li><li>GitHub — We will be creating a workflow, setting repository secrets.</li></ul><p>And that should be it, let’s start!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*zifWuoqB2Aulp7tQ.gif" /></figure><h3>📘 <strong>About Terraform Tests</strong></h3><p>We cannot start this article without talking about Terraform tests, what are they, what they do, why should we create tests and how to create tests.</p><p>Since Terraform v1.6.0, Hashicorp introduced a new command into its Terraform CLI. The command “terraform test”. Terraform test let your Terraform code with assertions that you define. It has two mode, you can either test your infrastructure with the “terraform plan” command, or deploy your infrastructure, just like you would do using “terraform apply” and make your tests.</p><p>You may ask, what is the difference between <strong>terraform test</strong> and <strong>terraform validate</strong> right? They are two very different commands. <strong>Terraform validate</strong> will validate that your code is right, call existing resources from your provider, check your syntax and the variable you specify while <strong>terraform test</strong> will test the code you wrote after the deployment (if using command apply) or after the plan (if using command plan).</p><p>Another question to answer, why would I test my terraform code? This isn’t C, Python, NodeJS…</p><p>I have my answers to this question. First, to ensure that no matter what time of the year you are, you want to ensure your module is still working. Secondly, if you are writing company modules, your module may have a <a href="http://readme.md/">README.md</a> file with a code snippet. You want to be sure that the snippet in the <a href="http://read.me/">READ</a><a href="http://me.md/">ME.md</a> file is still working today. Finally, why not?</p><p>We will cover in this part the basic of testing, like file names, code structure, and dig deeper in the implementation part of this article.</p><p>To write your terraform tests, Hashicorp made it easy, it use the HCL language, similar to what you write for your terraform code. You have to create a folder named “tests” (name can also be arbitrary) and inside files ending with <strong>.tftest.hcl</strong></p><p>Inside of your test files, you may declare few blocks:</p><ul><li>Provider (to setup your provider, eg: AWS with a region)</li><li>Run</li><li>Variables (to set variable for the whole test file)</li></ul><p>There is a new block that is not useful when writing terraform code, the <strong>run</strong> block. You may have guessed it, this is the block where you would declare your tests!</p><p>Let’s write a simple test and explain what we’re doing in it. Imagine you have the following structure:</p><pre>- MyModule<br>| -&gt; main.tf<br>| -&gt; variables.tf<br>| -&gt; outputs.tf<br>| -&gt; provider.tf<br>| -&gt; tests/</pre><p>Now, let’s define “values” that reside inside your files:</p><pre># main.tf<br>resource &quot;aws_s3_bucket&quot; &quot;my_bucket&quot; {<br>	bucket = var.name<br>}</pre><pre># variables.tf</pre><pre>variable &quot;name&quot; {<br>	type = string<br>}</pre><pre># outputs.tf<br>output &quot;bucket_arn&quot; {<br>	value = aws_vpc.my_vpc.id<br>}</pre><p>We can write our first test file:</p><pre># tests/my_module.tftest.hcl<br>provider &quot;aws&quot; {<br>	region = &quot;eu-west-1&quot;<br>}</pre><pre>variables {<br>	name = &quot;my-bucket&quot;<br>}</pre><pre>run &quot;my-test-named-plan&quot; {<br>  command = plan</pre><pre>  module {<br>    source = &quot;./&quot; # &lt;- This is because when running the command terraform test, we are locating in the root folder of our module<br>  }<br>}</pre><p>We started by declaring the provider options that we will use for the tests. Then, we declared a global variable named “name” that will automatically be passed to our “run” blocks.</p><p>We also create our first test named “my-test-named-plan”. We’ve set the command to use to “plan”, specified the module location and gave the second required variable which is “cidr_block”. Since we defined a global variable, “name” will be passed automatically and there is no need to redefine it.</p><p>Now, we can run “terraform init” then “terraform test” and see the output.</p><pre>-&gt; % terraform test<br>tests/my_module.tftest.hcl... in progress<br>  run &quot;my-test-named-plan&quot;... pass<br>tests/my_module.tftest.hcl... tearing down<br>tests/my_module.tftest.hcl... pass</pre><pre>Success! 1 passed, 0 failed.</pre><p>This test was fairly easy right? You may ask, what’s the difference between this and running the terraform plan myself? Well, we know that AWS Bucket name requires to be unique, and… it is very likely that a bucket named “my-bucket” already exists. Let’s add another test but this time, with a <strong>command = apply</strong> and check if our test is still working.</p><pre># tests/my_module.tftest.hcl<br><br># We know this test will fail, we will add another one after<br>run &quot;apply_fail&quot; {<br>  command = apply<br>  module {<br>    source = &quot;./&quot;<br>  }<br><br>  # No variables here, we will be using root level variables<br>}<br>run &quot;apply_success&quot; {<br>  command = apply<br>  module {<br>    source = &quot;./&quot;<br>  }<br><br>  # Let&#39;s redefine our variables<br>  variables {<br>    name = &quot;medium-article-random-value-554181fdsqv&quot;<br>  }<br>}</pre><p>The odds of getting another error with the second apply test are very low. Let’s try to run terraform test again!</p><pre>-&gt; % terraform test<br>tests/my_module.tftest.hcl... in progress<br>  run &quot;my-test-named-plan&quot;... pass<br>  run &quot;apply_failed&quot; ... failed<br>  run &quot;apply_success&quot; ... pass<br>tests/my_module.tftest.hcl... tearing down<br>tests/my_module.tftest.hcl... pass</pre><pre>Success! 2 passed, 1 failed.</pre><p>Isn’t it awesome? Let’s talk about asserts now, and then we will be talking about the automated test factory. I hope you are still with my and that, at this point, you’ve already learned something new!</p><p>We have the ability to ensure our module returns the right values, and to ensure that the variables we passed are successfully being passed. Let’s try!</p><pre># tests/my_module.tftest.hcl<br>[...]<br><br>run &quot;test_asserts&quot; {<br>  command = apply<br>  module {<br>    source = &quot;./&quot;<br>  }<br><br>  variables {<br>    name = &quot;medium-article-random-value-554181fdsqv-bis&quot;<br>  }<br><br>  assert {<br>    condition     = aws_s3_bucket.my_bucket.arn == &quot;arn:aws:s3:eu-west-1:0123456789:medium-article-random-value-554181fdsqv-bis&quot;<br>    error_message = &quot;Invalid bucket ARN. Expected: arn:aws:s3:eu-west-1:0123456789:medium-article-random-value-554181fdsqv-bis&quot;<br>  }<br>}</pre><p>Let’s run our tests again:</p><pre>-&gt; % terraform test<br>tests/my_module.tftest.hcl... in progress<br>  run &quot;my-test-named-plan&quot;... pass<br>  run &quot;apply_failed&quot; ... failed<br>  run &quot;apply_success&quot; ... pass<br>  run &quot;test_asserts&quot; ... pass<br>tests/my_module.tftest.hcl... tearing down<br>tests/my_module.tftest.hcl... pass</pre><pre>Success! 3 passed, 1 failed.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*tUNKg9N85lI1t0tR.gif" /></figure><p>One last thing, this one is REALLY IMPORTANT. When you perform a <strong>terraform test</strong> with <strong>command = apply</strong>, it really apply the infrastructure, and destroy it at the end of the test automatically. The state of the deployed infrastructure is stored in memory. In case of a crash, the state is lost and resource still deployed. We will talk more about that in the Solution Architecting part of the article.</p><h3><strong>🤔 Solution Architecting</strong></h3><p>Do you remember what was our main goal? Build an automated Terraform module test factory! And how can we do this? Usually, in this part of my articles, I like to list any possibility, list the pros and cons of each possibilities, and make a choice.</p><p>We will need somewhere to store our modules. I am thinking about either GitHub, or GitLab since they are both very popular, both has a free plan that can fit our needs. I will pick GitHub since I am already using GitHub to store all of my projects.</p><p>We will need a CI/CD solution to run “terraform test”, and send reports to AWS automatically. We have multiple choices, GitHub Actions, Jenkins, <a href="http://drone.io/">Drone.io</a>. A good choice here based on our previous decision would be to use GitHub Actions. They are already integrated in GitHub and available for free. Our goal is to learn, and learning with a low budget is always better.</p><p>Now, let’s discuss about AWS. I could have gone with any other Cloud Provider, or server renting and building everything myself but hey, I am a Cloud Engineer and I work on AWS platform, let’s improve our knowledge there. Earlier, we said that we will need to send the test outputs into our AWS environment AND generate a report, but how ? We have many entry points possible:</p><ul><li>API Gateway</li><li>Lambda (with Lambda URL, or invoke via AWS CLI)</li><li>ECS Container with a custom built solution</li><li>EC2 instance with a custom built solution</li><li>EKS pod with a custom built solution</li><li>Many more…</li></ul><p>Using any of the above solution (except Lambda via AWS CLI) requires to expose something to the internet. I am not a huge fan. However, using AWS CLI requires our GitHub workflow to have access to our AWS Account. But, we will need that in order to run terraform tests.. This might be our easiest solution. I recommend using a totally separated AWS account that no access to any resources your organization might have.</p><p>Since we will generate a report, and that we might have a lot of modules that will require testing, we will need to store results somewhere before the report is generated. Once again, we have many AWS services available:</p><ul><li>AWS DynamoDB</li><li>AWS RDS (Aurora, MySQL, Oracle, PostgreSQL, MSSQL, …)</li><li>AWS S3</li><li>AWS EBS Volume</li><li>Many more …</li></ul><p>AWS RDS seems like a solid choice, however we mentioned earlier that we want to keep the cost low. Since RDS instances are running almost 24/7 it has a hourly price.</p><p>AWS S3 may be a cheap solution however this may not be the most easiest solution to deal with. We have the same issue with a EBS volume, with the added monthly cost based of the size we provisioned for the EBS volume. We will also need a EC2 instance to write into our volume.</p><p>We have one last listed solution left, AWS DynamoDB. DynamoDB offers a On-Demand mode, our cost will be based on our usage of the table we have created. This might be the best suited solution and offer a very low cost of usage, near to free. It can be free thanks to the AWS Free Tier.</p><p>We want to trigger the AWS Lambda function that generate the report at a given time of the day/week. We can use AWS EventBridge Scheduler for that.</p><p>For the report delivery, we have few options depending on what is the destination of the report output. In our case, we want to send a mail to our DevOps team, and in the futur a message into a Slack/Microsoft teams channel. We can use the following services:</p><ul><li>AWS Simple Notification Service</li><li>AWS Simple Email Service</li></ul><p>AWS SNS supports multiple subscription targets such as Email, WebHooks and more. Exactly what we want to do.</p><p>Here is what our architecture would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNOqLn9mFAP1x4t8FoXx7Q.png" /></figure><h3><strong>🛠️ Implementing our solution</strong></h3><p>After a lot of reading, you might want to take a pause. That’s what I would do, enjoy your coffee, and come back later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*mT65NQmcP7qXizHZ.gif" /></figure><blockquote>Quick Note: At the end of this article, a link to every resources used to build the solution will be provided. Feel free to jump at the end and get the link to the demonstration GitHub repository 😊.</blockquote><p>Now that you are back and fully focused, let’s deep dive into the implementation. Remember our target? A GitHub workflow, a couple of Lambda Function, a DynamoDB table and a SNS topic. And, the most important resource here, some Terraform module to test. Let’s begin with this.</p><p>We will be writing two modules, two very simple modules with tests. Below is what our folder will look like:</p><p>As you have probably noticed, we will be creating two modules, “vpc” and “securitygroup”. Let’s set the code for our tests.</p><pre># /modules/securitygroup/tests/securitygroup.tftest.hcl<br>provider &quot;aws&quot; {<br>  region = &quot;eu-west-1&quot;<br>}  <br><br>run &quot;plan&quot; {<br>  command = plan<br>  module {<br>    source = &quot;./&quot;<br>  }<br>  variables {<br>    application_environment    = &quot;dev&quot;<br>    application_name           = &quot;test-app-sg&quot;<br>    security_group_description = &quot;Security group for test&quot;<br>    ingress_rules = [<br>      {<br>        from_port   = 80<br>        to_port     = 80<br>        protocol    = &quot;tcp&quot;<br>        cidr_blocks = [&quot;10.0.0.0/16&quot;]<br>      }<br>    ]<br>    egress_rules = [<br>      {<br>        from_port   = 0<br>        to_port     = 0<br>        protocol    = &quot;-1&quot;<br>        cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>      }<br>    ]<br>  }<br>  assert {<br>    condition     = aws_security_group.security_group.tags_all[&quot;Name&quot;] == &quot;test-app-sg-dev-sg&quot;<br>    error_message = &quot;Security Group Name tag should be test-app-sg-dev-sg&quot;<br>  }<br>}</pre><p>Note that a more detailed test file is available in the demo repository available at the end of this article.</p><p>And now, for the VPC module:</p><pre># /modules/vpc/tests/vpc.tftest.hcl<br>provider &quot;aws&quot; {<br>  region = &quot;eu-west-1&quot;<br>}<br><br>run &quot;plan&quot; {<br>  command = plan<br>  module {<br>    source = &quot;./&quot;<br>  }<br>  variables {<br>    application_environment = &quot;dev&quot;<br>    application_name        = &quot;test-app&quot;<br>    vpc_cidr_block          = &quot;10.0.0.0/16&quot;<br>    enable_dns_support      = true<br>    enable_dns_hostnames    = true<br>  }<br>  assert {<br>    condition     = aws_vpc.vpc.enable_dns_hostnames == true<br>    error_message = &quot;DNS hostnames should be enabled in the VPC.&quot;<br>  }<br>  assert {<br>    condition     = aws_vpc.vpc.enable_dns_support == true<br>    error_message = &quot;DNS Support should be enabled in the VPC.&quot;<br>  }<br>  assert {<br>    condition     = aws_vpc.vpc.tags_all[&quot;Name&quot;] == &quot;test-app-dev-vpc&quot;<br>    error_message = &quot;VPC Name tag should be test-app-dev-vpc&quot;<br>  }<br>}<br>run &quot;apply&quot; {<br>  command = apply<br>  module {<br>    source = &quot;./&quot;<br>  }<br>  variables {<br>    application_environment = &quot;dev&quot;<br>    application_name        = &quot;test-app&quot;<br>    vpc_cidr_block          = &quot;10.0.0.0/16&quot;<br>    enable_dns_support      = true<br>    enable_dns_hostnames    = true<br>  }<br>}<br>run &quot;verify&quot; {<br>  module {<br>    source = &quot;./tests/loader&quot;<br>  }<br>  variables {<br>    application_environment = &quot;dev&quot;<br>    application_name        = &quot;test-app&quot;<br>  }<br>  assert {<br>    condition     = data.aws_vpc.vpc.enable_dns_support == true<br>    error_message = &quot;DNS hostnames should be enabled in the VPC.&quot;<br>  }<br>  assert {<br>    condition     = data.aws_vpc.vpc.enable_dns_hostnames == true<br>    error_message = &quot;DNS Support should be enabled in the VPC.&quot;<br>  }<br>}</pre><p>Now, let’s focus with the AWS part of the infrastructure. Remember the diagram?</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CNOqLn9mFAP1x4t8FoXx7Q.png" /></figure><p>We need to deploy 2 AWS Lambda Functions, one DynamoDB table, one SNS topic and one EventBridge Scheduler rule. Let’s focus with our Lambda Functions first.</p><p>We will begin with the Registration Lambda Function</p><pre>import boto3<br>import json<br>import os<br><br>def handler(event, context):<br><br>    module_name = event[&#39;module_name&#39;]<br>    module_version = event[&#39;module_version&#39;]<br>    module_status = event[&#39;module_status&#39;]<br>    module_url = event[&#39;module_url&#39;]<br><br>    # Create a DynamoDB client<br>    dynamodb = boto3.client(&#39;dynamodb&#39;)<br>    <br>    # Define the table name<br>    table_name = os.environ[&#39;DYNAMODB_TABLE_NAME&#39;]<br><br>    # Create the item to be inserted<br>    item = {<br>        &#39;ModuleName&#39;: {&#39;S&#39;: module_name},<br>        &#39;ModuleVersion&#39;: {&#39;S&#39;: module_version},<br>        &#39;ModuleStatus&#39;: {&#39;S&#39;: module_status},<br>        &#39;ModuleUrl&#39;: {&#39;S&#39;: module_url}<br>    }<br><br>    # Insert the item into the DynamoDB table<br>    try:<br>        response = dynamodb.put_item(<br>            TableName=table_name,<br>            Item=item<br>        )<br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: json.dumps(&#39;Module result registered successfully!&#39;)<br>        }<br>    except Exception as e:<br>        raise Exception(f&#39;Error registering module result: {str(e)}&#39;)</pre><p>The code is fairly easy. Read the given parameters, store them into DynamoDB and return a success message. We don’t need anything else right now. We will now write the code for the report generation feature.</p><pre>import boto3<br>import json<br>import os<br><br><br>def generate_report_content(items):<br>    report = &quot;Daily Module Report\n\n&quot;<br>    for item in items:<br>        module_name = item[&#39;ModuleName&#39;][&#39;S&#39;]<br>        module_version = item[&#39;ModuleVersion&#39;][&#39;S&#39;]<br>        module_status = item[&#39;ModuleStatus&#39;][&#39;S&#39;]<br>        module_url = item[&#39;ModuleUrl&#39;][&#39;S&#39;]<br>        <br>        report += &quot;-&quot; * 20 + &quot;\n&quot;<br>        report += f&quot;Module Name: {module_name}\n&quot;<br>        report += f&quot;Module Version: {module_version}\n&quot;<br>        report += f&quot;Module Status: {module_status}\n&quot;<br>        report += f&quot;Module URL: {module_url}\n&quot;<br>        <br>    return report<br><br>def handler(event, context):<br><br>    # Create a DynamoDB client<br>    dynamodb = boto3.client(&#39;dynamodb&#39;)<br><br>    # Define the table name<br>    table_name = os.environ[&#39;DYNAMODB_TABLE_NAME&#39;]<br><br>    # Fetch all items from the DynamoDB table<br>    try:<br>        response = dynamodb.scan(<br>            TableName=table_name<br>        )<br>        items = response.get(&#39;Items&#39;, [])<br><br>        if not items or len(items) == 0:<br>            return {<br>                &#39;statusCode&#39;: 200,<br>                &#39;body&#39;: json.dumps(&#39;No items found in the DynamoDB table.&#39;)<br>            }<br>       <br>        failed_item_count = 0<br>        for item in items:<br>            module_status = item[&#39;ModuleStatus&#39;][&#39;S&#39;]<br>            if module_status != &#39;success&#39;:<br>                failed_item_count += 1<br><br>        email_content = generate_report_content(items)<br><br>        # send message content to SNS<br>        sns = boto3.client(&#39;sns&#39;)<br>        topic_arn = os.environ[&#39;SNS_TOPIC_ARN&#39;]<br>        subject = os.environ[&#39;EMAIL_SUBJECT&#39;]<br><br>        sns.publish(<br>            TopicArn=topic_arn,<br>            Subject=f&quot;{subject} - {failed_item_count} failed/total {len(items)}&quot;,<br>            Message=email_content,<br>            MessageStructure=&#39;string&#39;<br>        )<br><br>        # Clear data in the DynamoDB table<br>        for item in items:<br>            dynamodb.delete_item(<br>                TableName=table_name,<br>                Key={<br>                    &#39;ModuleName&#39;: item[&#39;ModuleName&#39;],<br>                    &#39;ModuleVersion&#39;: item[&#39;ModuleVersion&#39;]<br>                }<br>            )<br><br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: json.dumps(f&quot;Send message: {email_content} to SNS&quot;)<br>        }<br><br><br>    except Exception as e:<br>        raise Exception(f&#39;Error fetching module results: {str(e)}&#39;)</pre><p>This one is a bit longer. Basically, it reads the DynamoDB table and fetch latest tests registered, deletes them from the table, and generate a report message that will be published into our SNS topic.</p><p>We will now create the Terraform code for our SNS topic, our Event rule and our DynamoDB Table.</p><pre>locals {<br>  sns_module_report_topic = &quot;aws-terraform-test-module-report-generation&quot;<br>  ses_email_destination   = &quot;john-doe@example.com&quot;<br>}<br><br>resource &quot;aws_cloudwatch_event_rule&quot; &quot;lambda_trigger&quot; {<br>  name                = &quot;scheduler-generate-module-report&quot;<br>  description         = &quot;Trigger Lambda function to generate module report&quot;<br>  schedule_expression = &quot;cron(0 4 * * ? *)&quot;<br>}<br><br>resource &quot;aws_cloudwatch_event_target&quot; &quot;lambda_target&quot; {<br>  rule = aws_cloudwatch_event_rule.lambda_trigger.name<br>  arn  = aws_lambda_function.generate_module_report.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.generate_module_report.function_name<br>  principal     = &quot;events.amazonaws.com&quot;<br>  source_arn    = aws_cloudwatch_event_rule.lambda_trigger.arn<br>}<br><br>resource &quot;aws_sns_topic&quot; &quot;report_topic&quot; {<br>  name = local.sns_module_report_topic<br>}<br><br>resource &quot;aws_sns_topic_subscription&quot; &quot;email&quot; {<br>  topic_arn = aws_sns_topic.report_topic.arn<br>  protocol  = &quot;email&quot;<br>  endpoint  = local.ses_email_destination<br>}<br><br>resource &quot;aws_dynamodb_table&quot; &quot;module_report_table&quot; {<br>  name         = &quot;ModuleReportTable&quot;<br>  billing_mode = &quot;PAY_PER_REQUEST&quot;<br>  hash_key     = &quot;ModuleName&quot;<br>  range_key    = &quot;ModuleVersion&quot;<br><br>  attribute {<br>    name = &quot;ModuleName&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  attribute {<br>    name = &quot;ModuleVersion&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  tags = {<br>    Name        = &quot;ModuleReportTable&quot;<br>  }<br>}</pre><p>Now, let’s focus on our GitHub Actions Workflow! We need to:</p><ol><li>Checkout the repository</li><li>Set our AWS credentials</li><li>Setup Terraform</li><li>Run the terraform tests</li><li>Send the test result to our Lambda Function</li></ol><p>Here’s what I’ve done to make it work:</p><pre>name: Terraform Test Module - Security Group<br><br>on:<br>  push:<br>    branches:<br>      - main<br>  pull_request:<br>    branches:<br>      - main<br>  workflow_dispatch:<br>  schedule:<br>    - cron: &#39;0 0 * * *&#39;  # Every day at 00:00 <br>env:<br>  REPOSITORY_URL: https://github.com/${{ github.repository }}<br>  MODULE_NAME: securitygroup<br>  MODULE_PATH: modules/securitygroup<br>  VERSIONS: &quot;v1.0 v1.1 v1.1.1&quot;<br>  LAMBDA_FUNCTION_NAME: register_module_result<br>  LAMBDA_REGION: eu-west-1<br><br>  <br>jobs:<br>  terraform-test:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v4<br><br>    - name: Configure AWS credentials<br>      uses: aws-actions/configure-aws-credentials@v4<br>      with:<br>        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>        aws-secret-access-key: ${{ secrets.AWS_SECRET_KEY }}<br>        aws-region: eu-west-1<br><br>    - name: Setup Terraform<br>      uses: hashicorp/setup-terraform@v2<br>      with:<br>        terraform_version: 1.11.4<br><br>    - name: Loop through tags and test Terraform<br>      shell: bash<br>      run: |<br>        IFS=&#39; &#39; read -r -a TAGS &lt;&lt;&lt; &quot;$VERSIONS&quot;<br><br>        for TAG in &quot;${TAGS[@]}&quot;; do<br>          echo &quot;===== Processing tag: $TAG =====&quot;<br><br>          # Clean working directory<br>          git reset --hard &gt; /dev/null 2&gt;&amp;1<br>          git clean -fdx &gt; /dev/null 2&gt;&amp;1<br><br>          # Checkout tag<br>          git fetch --tags &gt; /dev/null 2&gt;&amp;1<br>          git checkout &quot;$TAG&quot; &gt; /dev/null 2&gt;&amp;1<br><br>          # Init &amp; test<br>          cd $MODULE_PATH<br>          terraform init &gt; /dev/null 2&gt;&amp;1<br>          if terraform test; then<br>            RESULT=&quot;success&quot;<br>            echo &quot;✅ Test succeeded for $TAG&quot;<br>          else<br>            RESULT=&quot;failure&quot;<br>            echo &quot;❌ Test failed for $TAG&quot;<br>          fi<br><br>          aws lambda invoke \<br>            --function-name $LAMBDA_FUNCTION_NAME \<br>            --region $LAMBDA_REGION \<br>            --payload &quot;{\&quot;module_name\&quot;: \&quot;$MODULE_NAME\&quot;, \&quot;module_version\&quot;: \&quot;$TAG\&quot;, \&quot;module_status\&quot;: \&quot;$RESULT\&quot;, \&quot;module_url\&quot;: \&quot;$REPOSITORY_URL/tree/$TAG\&quot;}&quot; \<br>            /tmp/lambda-response.json \<br>            --cli-binary-format raw-in-base64-out &gt; /dev/null 2&gt;&amp;1 || true<br><br>            cd -<br>        done</pre><p>As you can see, there are few parameters you will need to adapt like the module name, the versions you want to test (using tags) and the Lambda function informations like the name and the region where it’s being deployed.</p><p>That’s it ! We have something working. To test, manually trigger the pipeline and ensure data are being sent to the Lambda Function, and manually trigger the GenerateReport Lambda Function. You should be receiving a mail containing your report!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*F8BVVdaOvXovvltfK6Pkuw.png" /></figure><h3><strong>👀 Room for improvements</strong></h3><p>I started writing this article a month ago, I also was learning about Terraform tests and by now, I have learned a lot and had time to take a real step back about my implementation.</p><p><strong>The GitHub workflow</strong></p><p>I hate having such a long script for this. Teddious to maintain and not the best use case of a GitHub Action workflow. What would be best would be to create our own GitHub action(s), and keep our workflow file as minimal as it can be.</p><p>I am also not a fan of specifying versions to test in the file. It should retrieve the tags automatically and run the tests.</p><p><strong>Terraform Test</strong></p><p>I have not talked about resource mocking which is super useful as the modules I’ve created does not really need them, however it can be mandatory if you are writing and testing a module about Secrets Manager that has a delay between the secret deletion request and the actual deletion. I’ve been reading this article that was super helpful and help me in my company job: <a href="https://mattias.engineer/blog/2024/terraform-test-mocks/">https://mattias.engineer/blog/2024/terraform-test-mocks/</a></p><h3><strong>🏁 Conclusion</strong></h3><p>If you are still reading this, I just want to thank you! It took quite some time implementing the solution and writing this article. I hope you have learned new things like I did.</p><p>The source code is available here: <a href="https://github.com/Synchroneyes/medium-automated-terraform-test-factory/tree/main">https://github.com/Synchroneyes/medium-automated-terraform-test-factory</a></p><p>Feel free to share your thoughts, I will be happy to read you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f93fead08b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How I created a Minecraft server provider with Discord and AWS]]></title>
            <link>https://medium.com/@monvoisinkevin/how-i-created-a-minecraft-server-provider-with-discord-and-aws-1fb9a943bd38?source=rss-49bf7667589a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb9a943bd38</guid>
            <category><![CDATA[ec]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[minecraft]]></category>
            <dc:creator><![CDATA[Kevin MONVOISIN]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 13:47:34 GMT</pubDate>
            <atom:updated>2024-08-22T20:13:52.777Z</atom:updated>
            <content:encoded><![CDATA[<h3>⚡ TL:DR</h3><p>We will cover how I have created my own Minecraft Server Provider using Discord to create the servers and ECS to run the servers.</p><h3>📋 Table of content</h3><p>· <a href="#3d7a">⚡ TL:DR</a><br>· <a href="#44d3">📋 Table of content</a><br>· <a href="#070e">🌍 Introduction</a><br>· <a href="#995e">💪 Goals and Objectives</a><br>· <a href="#ff36">🛠️ Requirements</a><br>· <a href="#a389">🤔 Solution Architecting</a><br>· <a href="#e8cf">🛠️ Implementing our solution</a><br>· <a href="#e516">👀 Room for improvements</a><br>· <a href="#6800">🏁 Conclusion &amp; Source Code</a></p><h3>🌍 Introduction</h3><p>Since my teenage years, I have always been a fan of hosting my very own game servers. I used to have a well-known French community (WayCaster.fr) on a game named Garry’s Mod. We had a few servers that were up and full most of the time. I was using some open-source game panels, but none of them were interesting to me. So, I ended up using the classic Linux shell to manage the servers. Then I learned programming. I started with web development using PHP, and I thought, “Hey, let’s create my own game server panel!” It never happened. 🙄</p><p>Today, I have realized that I no longer use web apps when an alternative exists, such as phone applications or bots (Telegram, WhatsApp, Discord, etc.). So here I am now, a fully grown man with knowledge in coding, solution architecture, and the same passion for building stuff.</p><p>I would like to build a solution that allows Minecraft Players from the Mineral Contest community to start a server on the go, using Discord.</p><p>What is Mineral Contest? Mineral Contest is a Minecraft game mode that went viral in France few years ago. A French Youtuber name “Squeezie” released a YouTube video of him and his friends playing this game mode and people loved it. (for the curious ones: <a href="https://www.youtube.com/watch?v=q_xALLkdwNA">https://www.youtube.com/watch?v=q_xALLkdwNA</a>)</p><p>In a few words; the main objective is to collect resources (Iron, Gold, Diamond, Emerald) and bring them to your base to earn some points. You are playing against 3 other teams, each team is usually composed of 4 players.</p><p>This is where I came in! The game mode was private, and everyone wanted to play it. So I decided to re-create it based on the YouTube Videos and release it publicly. The plugin quickly became popular, and is still active today!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*ypCr2IMLyzzDu3WIm-RzGQ.png" /><figcaption>2024/08/08 — Current statistics for the plugin — available at <a href="https://mc.monvoisin-kevin.fr/">https://mc.monvoisin-kevin.fr/</a></figcaption></figure><h3>💪 Goals and Objectives</h3><p>In this article, we will dive into the creation of a system that provides Minecraft Servers using AWS, Discord, and a NodeJS bot.</p><p>We will be using the following AWS services:</p><ul><li>AWS ECR (Elastic Container Registry)</li><li>AWS ECS (Elastic Container Service)</li><li>AWS DynamoDB</li></ul><p>We will also be using the discord.js library to build our bot and the AWS SDK for JavaScript.</p><h3>🛠️ Requirements</h3><p>You will need an AWS Account, a Discord Application, Docker, NodeJS (version used in this article: 20.15.1).</p><p>The source code will also be provided, so you might need to use Terraform, Git, and the AWS CLI.</p><h3>🤔 Solution Architecting</h3><p>First thing first, what are we looking for? What are the requirements? What is the context?</p><p>Alright, so we are looking for a solution using Discord as our application client, we will be using AWS to host any virtualization service and database. We will also need to write a discord bot. Many choices to make here!</p><p>Firstly, for the Discord Bot, I would like to use NodeJS to practice this language. Lucky me, there is a well-known Discord library for Javascript named Discord.js. I want to restrict server creation to a specific set of users, to achieve this behavior, I will need to create a Discord Server Role.</p><p>How does the user should request its server? Should it be via a message sent to the moderation team? Via a server command? Here, I want the service to be fully automated, using a server command to provide automation.</p><p>Now that the user can request a server using a command, how does the user get his server details? I am not a fan of private messages, so this is not a suitable option. However, in my Discord Server, I am using a Ticketing tool. Users click on a button, it creates a new text channel that only the user and administration team can see; I like this idea a lot. Every user that requests a game server will have access to a newly created text channel that will contain every detail of its game server. Great!</p><p>Now, I need to think about server hosting, how am I going to create the game servers? We have many options here:</p><ol><li>EC2 instance: Either create a Golden AMI (an Amazon Machine Image that contains any dependencies and server binaries, pre-built that can be used without any further configuration) or use a configuration solution like AWS System Manager (Automation or RunCommand).</li><li>ECS Cluster: Using ECS Fargate we don’t have to manage any EC2, we only have to create our Docker Image, and specify the CPU and Memory needed.</li><li>EKS Cluster: Using Kubernetes, we don’t have to manage any EC2, we only have to create our Docker Image, and specify the CPU and Memory needed, however, this solution sounds a bit overkill for our usage and is expensive.</li></ol><p>On a side note, I do not need to have a persistent EBS volume since the game server will be temporary.</p><p>We now have to choose between an EC2 instance and an ECS Cluster. I already have experience using EC2 instances, coupled with SSM and I would like to learn and use this project to get knowledge about ECS so I will be selecting ECS.</p><p>We have to figure out how to create a game server on ECS. We have many possibilities here:</p><ul><li>Using a service: a service is a feature on ECS that guarantees a specific amount of containers up and running. Kinda like the AutoScaling Group on EC2. If a task fails or gets stopped, the service will automatically shut down the task and start a new one.</li><li>Using a task: a task contains a container to use, CPU and Memory to allocate, and Network configuration. This option is lighter than using a service and more suitable for what we are looking to achieve.</li></ul><p>Let’s recap what we’ve said so far:</p><ol><li>The user needs to have a special role</li><li>The user needs to use a Discord command to request a server creation</li><li>A new ECS task has to be created</li><li>The details of the ECS task need to be retrieved (IP Address, Current State, …)</li><li>A new Discord text channel needs to be created, only the administration team and the server owner can have access to it.</li><li>Send the details to the newly created text channel.</li></ol><p>We now have to think about data persistence. How do we ensure the bot has a list of active ECS tasks, knows when the task was created, how long before the tasks need to be killed, how to ensure the bot keeps this data stored somewhere “safe” (i.e: not in memory) in case the bot crash and has to restart?</p><p>We have here many solutions:</p><ol><li>Use a memory database (Redis, H2, …)</li><li>Use a SQL database (MariaDB, MySQL, SQL Server, …)</li><li>Use a No-SQL Database (MongoDB, DynamoDB, …)</li></ol><p>Since this is my own money, I want the solution to be cheap, nearly free. DynamoDB would be a solid choice since it’s managed, almost free for my usage, and runs outside of my bot application.</p><p>Let’s create a diagram showing what our solution would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rRd4evK-N9rCPrHH" /></figure><p>Currently, I am happy with the choices we made, let’s begin implementing our solution!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*2oSk1yBvlp8jCobh2NC8CQ.gif" /></figure><h3>🛠️ Implementing our solution</h3><p>Before actually implementing our solution, I just want to give some words. I won’t be going through every step required to build this project. I will go through basic things, and the whole project will be available at the end of this post. Thank you if you already made it that far!</p><p>Our first step here is to create our discord application. Simply head to <a href="https://discord.com/developers/applications">https://discord.com/developers/applications</a> and click on “New Application”. Generate a new Token, grab the Client ID, and save it somewhere, we will need it later.</p><p>We will now create the bot application logic. Based on the Discord.js documentation, installing the library is as easy as 1–2–3. Simply run the following command:</p><pre>npm install discord.js dotenv</pre><p>And now, create our file first:</p><pre>// main.js<br>import { Client, GatewayIntentBits } from &#39;discord.js&#39;;<br>const client = new Client({ intents: [GatewayIntentBits.Guilds] });<br><br>client.on(&#39;ready&#39;, () =&gt; {<br>  console.log(`Logged in as ${client.user.tag}!`);<br>});<br><br>client.login(&quot;token&quot;);</pre><p>Run the bot with the following command:</p><pre>$ node main.js                                                                                                                                      N<br>Logged in as bot1271486725746720900#4545!</pre><p>Awesome! We now have the basic code that allows our bot to log in! For those who want to explore a little bit more, the “Getting Started” page of Discord.Js is full of useful information, you can read more <a href="https://discord.js.org/docs/packages/discord.js/main">here</a>.</p><p>Let’s now create our application structure, with files and folder names. Here, I will be using the following structure:</p><pre>medium-discord-bot-aws/<br>├── commands/<br>│   └── typeOfCommand/<br>│       ├── commandExecutor1.js<br>│       └── ...<br>├── events/<br>│   ├── onMessage.js<br>│   ├── onReady.js<br>│   └── ...<br>├── .env<br>├── deploy-commands.js<br>├── main.js<br>└── package.json   </pre><ul><li>In the commands folder, we will have every command that our bot will support.</li><li>In the events folder, we will define every event that our bot will listen to.</li><li>In the .env file, we will have every environment variable required and read by our bot.</li><li>In the deploy-command.js file, we will have the logic to register commands into our discord server.</li><li>In the main.js file, we will have our application code.</li><li>The package.json file will contain the project description, dependencies, the main script to execute, and a little bit more.</li></ul><p>With that structure in mind, let’s add and create the deploy-commands.js file.</p><pre>const { REST, Routes } = require(&#39;discord.js&#39;);<br>const fs = require(&#39;node:fs&#39;);<br>const path = require(&#39;node:path&#39;);<br>require(&#39;dotenv&#39;).config()<br><br><br>const commands = [];<br>// Grab all the command folders from the commands directory you created earlier<br>const foldersPath = path.join(__dirname, &#39;commands&#39;);<br>const commandFolders = fs.readdirSync(foldersPath);<br><br>for (const folder of commandFolders) {<br> // Grab all the command files from the commands directory you created earlier<br> const commandsPath = path.join(foldersPath, folder);<br> const commandFiles = fs.readdirSync(commandsPath).filter(file =&gt; file.endsWith(&#39;.js&#39;));<br> // Grab the SlashCommandBuilder#toJSON() output of each command&#39;s data for deployment<br> for (const file of commandFiles) {<br>  const filePath = path.join(commandsPath, file);<br>  const command = require(filePath);<br>  if (&#39;data&#39; in command &amp;&amp; &#39;execute&#39; in command) {<br>   commands.push(command.data.toJSON());<br>  } else {<br>   console.log(`[WARNING] The command at ${filePath} is missing a required &quot;data&quot; or &quot;execute&quot; property.`);<br>  }<br> }<br>}<br><br>// Construct and prepare an instance of the REST module<br>const rest = new REST().setToken(process.env.DISCORD_TOKEN);<br><br>// and deploy your commands!<br>(async () =&gt; {<br> try {<br>  console.log(`Started refreshing ${commands.length} application (/) commands.`);<br><br>  // The put method is used to fully refresh all commands in the guild with the current set<br>  const data = await rest.put(<br>   Routes.applicationGuildCommands(process.env.DISCORD_CLIENT_ID, process.env.DISCORD_GUILD_ID),<br>   { body: commands },<br>  );<br><br>  console.log(`Successfully reloaded ${data.length} application (/) commands.`);<br> } catch (error) {<br>  // And of course, make sure you catch and log any errors!<br>  console.error(error);<br> }<br>})();</pre><p>When you execute this script, the bot will automatically register any command location in our “commands” folder to our discord server. Great! For those wondering, I did not write all this by myself 👀, the code came from the Discord.js documentation available <a href="https://discordjs.guide/creating-your-bot/command-deployment.html#guild-commands">here</a>.</p><p>We will now edit our main.js file to include command processing event processing, and auto-completion on our commands.</p><pre>const fs = require(&#39;node:fs&#39;);<br>const path = require(&#39;node:path&#39;);<br>const { Client, Collection, GatewayIntentBits, Events } = require(&#39;discord.js&#39;);<br><br>require(&#39;dotenv&#39;).config()<br><br>const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });<br><br>client.commands = new Collection();<br>const foldersPath = path.join(__dirname, &#39;commands&#39;);<br>const commandFolders = fs.readdirSync(foldersPath);<br><br>for (const folder of commandFolders) {<br> const commandsPath = path.join(foldersPath, folder);<br> const commandFiles = fs.readdirSync(commandsPath).filter(file =&gt; file.endsWith(&#39;.js&#39;));<br> for (const file of commandFiles) {<br>  const filePath = path.join(commandsPath, file);<br>  const command = require(filePath);<br>  if (&#39;data&#39; in command &amp;&amp; &#39;execute&#39; in command) {<br>   client.commands.set(command.data.name, command);<br>  } else {<br>   console.log(`[WARNING] The command at ${filePath} is missing a required &quot;data&quot; or &quot;execute&quot; property.`);<br>  }<br> }<br>}<br><br>const eventsPath = path.join(__dirname, &#39;events&#39;);<br>const eventFiles = fs.readdirSync(eventsPath).filter(file =&gt; file.endsWith(&#39;.js&#39;));<br><br>for (const file of eventFiles) {<br> const filePath = path.join(eventsPath, file);<br> const event = require(filePath);<br> if (event.once) {<br>  client.once(event.name, (...args) =&gt; event.execute(...args));<br> } else {<br>  client.on(event.name, (...args) =&gt; event.execute(...args));<br> }<br>}<br><br>client.on(Events.InteractionCreate, async interaction =&gt; {<br> if (interaction.isAutocomplete()) {<br>  const command = interaction.client.commands.get(interaction.commandName);<br><br>  if (!command) {<br>   console.error(`No command matching ${interaction.commandName} was found.`);<br>   return;<br>  }<br><br>  try {<br>   await command.autocomplete(interaction);<br>  } catch (error) {<br>   console.error(error);<br>  }<br> }<br>});<br><br><br><br>client.login(process.env.DISCORD_TOKEN);<br></pre><p>Don’t worry, the whole code will be available at the end of this blog post. Now that we have the basics of the bot, let’s head into the AWS part.</p><p>To provision any resource, we will be using Terraform.</p><p>“Terraform is an infrastructure as code tool that lets you build, change, and version cloud and on-prem resources safely and efficiently.” — <a href="https://developer.hashicorp.com/terraform/intro">https://developer.hashicorp.com/terraform/intro</a></p><p>To make things right, we will start by creating an S3 Bucket, and a DynamoDB table to store our remote state. That way, the infrastructure state isn’t saved on our computer and we cannot remove it accidentally. Enable Object Versioning on your S3 bucket to ensure the terraform state file cannot be deleted accidentally and can be retrieved if any accident happens. While we are here, also create an ECR repository.</p><p>Here is our provider.tf file:</p><pre>// provider.tf<br>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br><br>  backend &quot;s3&quot; {<br>    bucket = &quot;mybucket&quot;<br>    key    = &quot;path/to/my/key&quot;<br>    region = &quot;eu-west-1&quot;<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = local.region<br>}</pre><p>I like to work with configuration files rather than terraform variables. This is my own opinion. Here I will be working with a YAML configuration file and locals.</p><pre># config.yaml<br>region: eu-west-1<br>cluster_name: MineralContest<br>ecr_repository: your_repository_id.dkr.ecr.eu-west-1.amazonaws.com<br>image_name: mineralcontest</pre><pre>// locals.tf<br>locals {<br>  raw_data         = yamldecode(file(&quot;${path.module}/config.yaml&quot;))<br>  region           = local.raw_data[&quot;region&quot;]<br>  ecs_cluster_name = local.raw_data[&quot;cluster_name&quot;]<br>  ecr_repository   = local.raw_data[&quot;ecr_repository&quot;]<br>  image_name       = local.raw_data[&quot;image_name&quot;]<br>}</pre><p>Our first terraform resource will be the VPC. I will be using the AWS VPC Module. Here is the vpc.tf file.</p><pre>// vpc.tf<br>module &quot;vpc&quot; {<br>  source = &quot;terraform-aws-modules/vpc/aws&quot;<br>  name = &quot;mineralcontest-vpc&quot;<br>  cidr = &quot;10.0.0.0/16&quot;<br>  azs            = [&quot;${local.region}a&quot;]<br>  public_subnets = [&quot;10.0.1.0/24&quot;]<br>}</pre><p>Then, we will create our ECS cluster, the ECS task definition, and the security group that our task will use. Here is the ecs.tf file</p><pre>// ecs.tf <br>resource &quot;aws_ecs_cluster&quot; &quot;cluster&quot; {<br>  name = local.ecs_cluster_name<br>}<br><br>resource &quot;aws_ecr_repository&quot; &quot;repository&quot; {<br>  name = local.ecr_repository<br>  image_tag_mutability = &quot;MUTABLE&quot;<br>  image_scanning_configuration {<br>    scan_on_push = false # Disable image scanning<br>  }<br>}<br><br>resource &quot;aws_ecs_task_definition&quot; &quot;mineralcontest_task&quot; {<br>  family                   = &quot;mineralcontest&quot;<br>  task_role_arn            = aws_iam_role.ecs_task_role.arn<br>  execution_role_arn       = aws_iam_role.ecs_task_role.arn<br>  requires_compatibilities = [&quot;FARGATE&quot;]<br>  network_mode             = &quot;awsvpc&quot;<br>  cpu                      = &quot;2048&quot;<br>  memory                   = &quot;4096&quot;<br>  container_definitions = jsonencode(<br>    [<br>      {<br>        name      = &quot;mineralcontest&quot;,<br>        image     = &quot;${local.ecr_repository}/${local.image_name}:latest&quot;,<br>        cpu       = 0,<br>        memory    = 128,<br>        essential = true,<br>        portMappings = [<br>          {<br>            containerPort = 25565,<br>            hostPort      = 25565,<br>          },<br>        ]<br>      },<br>    ]<br>  )<br><br>}<br><br>resource &quot;aws_security_group&quot; &quot;mineralcontest&quot; {<br>  vpc_id = module.vpc.vpc_id<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  ingress {<br>    from_port   = 25565<br>    to_port     = 25565<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  ingress {<br>    from_port   = 25565<br>    to_port     = 25565<br>    protocol    = &quot;udp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><p>Now, let’s create our iam.tf file that will contain every needed policies and roles.</p><pre>// iam.tf<br>resource &quot;aws_iam_instance_profile&quot; &quot;ec2_ssm_instance_profile&quot; {<br>  name = &quot;EC2-SSM-Instance-Profile&quot;<br>  role = aws_iam_role.ec2_ssm_instance_role.name<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;ec2_ssm_instance_role&quot; {<br>  name               = &quot;EC2-SSM-Instance-role&quot;<br>  assume_role_policy = &lt;&lt;EOF<br>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;Service&quot;: &quot;ec2.amazonaws.com&quot;<br>            },<br>            &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>        }<br>    ]<br>}<br>EOF<br>}<br><br><br>resource &quot;aws_iam_role&quot; &quot;ecs_task_role&quot; {<br>  name               = &quot;ECS-Task-role&quot;<br>  assume_role_policy = &lt;&lt;EOF<br>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;Service&quot;: &quot;ecs-tasks.amazonaws.com&quot;<br>            },<br>            &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>        }<br>    ]<br>}<br>EOF<br>}<br><br>resource &quot;aws_iam_policy_attachment&quot; &quot;ecs_attachment&quot; {<br>  name       = &quot;ECS-Task-attachment&quot;<br>  roles      = [aws_iam_role.ecs_task_role.name]<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy&quot;<br>}</pre><p>We’ve also mentioned the use of a DynamoDB table to store our current servers up and running, so let’s create the table.</p><pre>// dynamodb.tf<br>resource &quot;aws_dynamodb_table&quot; &quot;tasks&quot; {<br>    name           = &quot;mineralcontest_tasks&quot;<br>    billing_mode   = &quot;PAY_PER_REQUEST&quot;<br>    hash_key       = &quot;taskId&quot;<br>    attribute {<br>        name = &quot;taskId&quot;<br>        type = &quot;S&quot;<br>    }<br>}</pre><p>We are done with the AWS part. Now, we need to create our game server docker container image. In my use case, I want users to be able to become administrator by themself. So I have written a simple Java plugin that allows an user to become an admin by submitting a game command. I have also created a small script that is the entry point of the container and pass the token to the game server (for the user to become admin), plus the configuration required to make the server “official” or “non-official” (enabling or not non-official game version). Here is my dockerfile.</p><pre># Build the Spigot Server<br>FROM amazoncorretto:17-alpine3.16 as SPIGOT_BUILDER<br>WORKDIR /spigot<br>ARG version=1.19.4<br>RUN apk update &amp;&amp; apk add curl git<br>RUN curl -o BuildTools.jar https://hub.spigotmc.org/jenkins/job/BuildTools/lastSuccessfulBuild/artifact/target/BuildTools.jar<br>RUN java -jar BuildTools.jar --rev $version --final-name server.jar<br><br><br># Build the MineralContest Plugin<br>FROM maven:3.9.8-amazoncorretto-17-al2023 as MINERALCONTEST_BUILDER<br>WORKDIR /mineralcontest<br>RUN yum install -y git<br>RUN cd /mineralcontest &amp;&amp; git clone https://github.com/synchroneyes/mineralcontest<br>RUN cd /mineralcontest/mineralcontest &amp;&amp; mvn clean install<br><br># Create the final image<br>FROM amazoncorretto:17-alpine3.16 as MC_SERVER<br>WORKDIR /server<br>COPY --from=SPIGOT_BUILDER /spigot/server.jar server.jar<br>COPY MinecraftPlugins/OPRedeem.jar plugins/OPRedeem.jar<br>COPY --from=MINERALCONTEST_BUILDER /mineralcontest/mineralcontest/target/MineralContest.jar plugins/MineralContest.jar<br>COPY files/server.properties server.properties<br>COPY scripts/init.sh init.sh<br><br><br>EXPOSE 25565<br>CMD [&quot;/server/init.sh&quot;]</pre><p>We now have to build, tag, and push our image to the ECR repository. The ECR service gives us the command required to build, tag, and push. Let’s execute them.</p><pre>aws ecr get-login-password --region eu-west-1 | docker login --username AWS --password-stdin your_repository_id.dkr.ecr.eu-west-1.amazonaws.com<br>docker build -t mineralcontest .<br>docker tag mineralcontest:latest your_repository_id.dkr.ecr.eu-west-1.amazonaws.com/mineralcontest:latest<br>docker push your_repository_id.dkr.ecr.eu-west-1.amazonaws.com/mineralcontest:latest</pre><p>And voila! Our image is now pushed into our ECR repository and is ready to be used!</p><p>The (almost) final steps in our project are to create the command handler for the server creation, server stop, and automatic server shutdown after a specific amount of time. I won’t be covering every command otherwise this post will be much longer (it’s already really long, sorry about that 🙄). The whole code will be available at this end, so feel free to dig and take what’s interesting to you.</p><p>Finally, we need to package our bot application. I want this project to be as cheap as possible, for the bot hosting, I will be using a server that I am already renting and has Docker installed on it. Here is the dockerfile and the docker-compose.yaml file for the bot application</p><pre>FROM node:20.15-alpine<br>WORKDIR /app<br>COPY . .<br>RUN npm install<br>RUN npm run deploy-commands<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><pre>// docker-compose.yaml<br>version: &#39;3&#39;<br>services:<br>  mineralcontest_bot:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    restart: always<br>    network_mode: host</pre><p>Now, simply run docker-compose up -d and the bot is now running! Awesome, we did it, and everything is working smoothly. Let’s talk about cost optimization.</p><p>As mentioned earlier, this game server is running the game mode Mineral Contest, which last approximately 60 minutes. It can be more or less depending on the user’s settings. We can implement a feature that automatically terminates an ECS task after a specified amount of seconds. Here is the code I wrote for this feature:</p><pre>const { getLocalDatabase } = require(&#39;../services/serverDatabase&#39;);<br>const { killServer } = require(&#39;../services/killServer&#39;);<br><br>require(&#39;dotenv&#39;).config()<br><br><br>/**<br> * Watch servers and kill them when maximum run time is reached<br> * @returns Interval handler<br> */<br>function watchServerRunTime() {<br>  return setInterval(async () =&gt; {<br>      const localDatabase = getLocalDatabase();<br>      for(let taskId in localDatabase){<br>          let task = localDatabase[taskId];<br>          <br>          let creationDate = task.creationDate;<br>          let currentDate = Date.now();<br>          if(currentDate &gt; creationDate + process.env.GAMESERVER_MAX_DURATION){<br>              await killServer(taskId);<br>          }<br>          <br>      }<br>  }, 1000);<br>}<br><br>module.exports = { watchServerRunTime };</pre><p>Every second, the bot will fetch the local database (a copy of the DynamoDB table stored locally, to avoid excessive API calls) and check when the server was created. If the server was created more than 90 minutes ago, then the ECS task is killed.</p><p>I want to implement another feature. I want to ensure the server has at least 4 players in it. If this requirement is not met, then the server is terminated. To implement this feature, I have used a JavaScript library that allows Minecraft server queries to fetch the current player count. When the minimum player count threshold is not met, a warning is sent to the user’s Discord text channel. After 3 warnings, the server is automatically killed.</p><h3>👀 Room for improvements</h3><p>That was a long post, wasn’t it? A first improvement would be to cut this post into subsidiary posts and add a “previous” or “next” link. Let me know your thoughts about this idea!</p><p>About this project, the first improvement would be within the game server container. Currently, I am using environment variables. I could improve it by using Secrets which is supported using Docker Compose which is a feature I am currently using. <a href="https://docs.docker.com/compose/use-secrets/">https://docs.docker.com/compose/use-secrets/</a>. I would have to make some changes to my application and read secrets from /run/secrets/&lt;secret_name&gt;.</p><p>For the build of the game server container, I could use a CI/CD to automate the build and deployment. Since I am cloning a Git Repository, the version my container has of this repository could be outdated. I can use CodeBuild to build my docker images and push them to my ECR repository and EventBridge Scheduler to schedule the build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5wMWKDP2jB-xZh9aOqRug.png" /></figure><p>As you can see in the diagram above, I have added the SNS Service. Currently; we lack some observability in our application. We could add some monitoring, for instance when a server creation fails, when a new Docker image build fails or succeeds, and when anything goes wrong, a notification can save us a lot of time.</p><p>Also, within the CI/CD, it would be nice to have some sort of testing, code scanning, and convention. We could do the following:</p><ol><li>Ensure the code is formatted everywhere and use the same naming convention (snakecase/camelcase/…)</li><li>Ensure there are no over-permissive policies that could lead to big issues</li><li>Local deployment to ensure everything is ready to be used</li></ol><p>Currently, the application only supports one type of game server. It would be a nice idea to add a way to support multiple games. What’s possible is to define some sort of game server template. You would define your game server settings in a JSON file, and upload the file into the Discord Server. The Bot application would parse the file, store the details in a DynamoDB table, and make the game server available for creation.</p><p>The bot application now! It was written using SDKv2 instead of SDKv3. AWS will end support for SDKv2 in 2025, meaning this project would need some parts to be rewritten in 2025.</p><h3>🏁 Conclusion &amp; Source Code</h3><p>This was a really fun project where I have learned a lot. I had no knowledge of ECS and very poor coding skills in Javascript. I actually enjoyed this project a lot.</p><p>The application is now live within my community, and some servers have already been provided to players, they are happy, and I am happy, what else?</p><p>Thank you for reading this whole article, I hope that wasn’t too boring to read, the source code is available below, feel free to read the README.md file to understand how to deploy the solution.</p><p>Source code: <a href="https://github.com/Synchroneyes/gameserver-discord-aws-mc">https://github.com/Synchroneyes/gameserver-discord-aws-mc</a></p><p>I am excited to read your remarks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb9a943bd38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In Real-Time notification system using WebSockets on AWS]]></title>
            <link>https://medium.com/@monvoisinkevin/in-real-time-notification-system-using-websockets-on-aws-6a8bcd831cab?source=rss-49bf7667589a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a8bcd831cab</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Kevin MONVOISIN]]></dc:creator>
            <pubDate>Mon, 06 May 2024 07:40:36 GMT</pubDate>
            <atom:updated>2024-05-06T07:40:36.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>⚡ TL:DR</h3><p>We will cover how to efficiently create a WebSockets API Gateway and send real-time messages from our Lambda functions to our WebSockets client to make our applications more interactive.</p><h3>📋 Table of content</h3><p>· <a href="#6798">🌍 Introduction</a><br>· <a href="#1b69">💪 Goals and Objectives</a><br>· <a href="#fe60">🛠️ Requirements</a><br>· <a href="#a32a">🤔 Solution Architecting</a><br>· <a href="#61ed">🛠️ Implementing our solution</a><br>· <a href="#42c0">👀 Room for improvements</a><br>· <a href="#29dd">🏁 Conclusion</a></p><h3>🌍 Introduction</h3><p>In today’s fast-paced digital landscape, the demand for instant communication and real-time updates has become more and more important. Whether it’s receiving breaking news alerts, tracking deliveries, or staying connected with friends and colleagues, the need for timely information has never been greater. In such a dynamic environment, traditional methods of communication often fall short, unable to provide the immediacy and responsiveness required.</p><p>This is where real-time notification systems step in to bridge the gap. By leveraging technologies like WebSockets, these systems enable seamless, bidirectional communication between clients and servers, allowing for instantaneous updates and alerts.</p><p>In the past year, I’ve completed a project for a client that was using a fully event-driven architecture, and for me, it was missing a crucial feature, real-time notification.</p><h3>💪 Goals and Objectives</h3><p>In this article, we will dive into the creation of a simple system on AWS by providing an architecture diagram, a few principles, the limits of performing this architecture on AWS, and a little bit of code.</p><p>We will be using the following AWS services:</p><ul><li>AWS API Gateway (Rest API and WebSockets API)</li><li>AWS Lambda</li><li>AWS Simple Queue Service</li><li>AWS DynamoDB</li></ul><h3>🛠️ Requirements</h3><p>In this article, we will mostly be using AWS so make sure you have an account ready to play with.</p><h3>🤔 Solution Architecting</h3><p>We have a simple web application that performs Rest API calls, some methods will create new AWS EC2 instances and take some time, we want to be notified through the whole creation process, at every step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*0yHDoNcG5SvWhey4-QBxcg.gif" /></figure><p>Here we are, with a blank page, tons of ideas in mind but can’t get them out. We know what we are looking for, a simple notification system. While some AWS services out there perform notification such as SNS (Simple Notification Service), it might not be our best fit for real-time notification.</p><p>When thinking about web and Rest API, an idea would be to store notifications in a database and make queries to our API that fetch stored notifications. But how should we fetch these notifications? Should we add a button to our web application that fetches these notifications? Should we create code that automatically makes the request to the right API endpoint every X seconds and collects the notifications? This is a solution, but not the one we are looking for.</p><p>What we want to do is real-time, a protocol that comes into my mind is WebSockets. WebSocket is a communication protocol that provides full-duplex communication channels over a single, long-lived connection between a client and a server. Unlike traditional HTTP connections, which are stateless and involve a request-response cycle meaning that the connection is terminated when the response is received, WebSockets enable persistent, low-latency communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*uwgsSijzrb32dbG3cDAC-A.png" /><figcaption>Diagram explaining simply how WebSockets works</figcaption></figure><p>With that definition in mind, WebSockets seems to be a solid candidate for our problem. On top of that, the AWS API Gateway service allows us to create WebSockets API, just what we need.</p><p>We now have to think about how we correlate our Rest API requests and WebSockets communication. If we take a look at how WebSockets API Gateway works on AWS, we might find one solution. If we refer to the AWS documentation, to send a message to a WebSocket client, we need to perform an HTTP request to the following URL:</p><pre>POST https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}</pre><p>Here, the interesting part of the URL is “{connection_id}”. That means that each time a user connects to the WebSockets API Gateway a connection ID is generated. Don’t we have a similar feature on Rest API Gateway? When requesting Rest API Gateway, a Request ID is generated, awesome! We now have a way to correlate WebSocket Connection and Rest API requests. For each request made to the Rest API Gateway, we will have to provide the WS connection ID. We can use a database solution to store these IDs and use them in our system to send messages later.</p><p>We have to find a way to send messages from AWS to our web application. Since we are dealing with an application that creates instances, we may want to send messages once instance creation starts, when instances are successfully created, and when instances are usable. Wouldn’t it be convenient to have a centralized way of delivering messages?</p><p>First thing first, we saw earlier that sending a message to one WebSocket client can be done by making a POST HTTP request to a specific URL. We can create a Lambda Function that will perform this HTTP request. In order to invoke that lambda function, we can either invoke the Lambda Function directly from other lambda functions, we can also create an SQS Queue that will receive every message and then send them to our Lambda Function, this is the solution that we will use because it decouples our architecture, it is more resilient to failure and it gives us more visibility about the number of messages to process.</p><p>We have one last topic to address, we want to send messages when the instance is created and ready to be used, but how? We can leverage Amazon EventBridge and catch those events.</p><p>At the end, we should have the following architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIBoLAoz1TVld51AGbmsdg.png" /><figcaption>Simple diagram (using Excalidraw) of the solution described above using API Gateway (Rest API/WebSockets), Lambda functions, DynamoDB and a SQS Queue</figcaption></figure><h3>🛠️ Implementing our solution</h3><p>Before actually starting to build our solution, let’s give some context here and define some boundaries:</p><ul><li>In the provided architecture diagram above, we have mentioned the use of an SQS queue. We won’t be implementing it here.</li><li>We’ve also suggested the use of DynamoDB to store Requests IDs and remove them on disconnection, we won’t be implementing them on here.</li><li>We won’t deploy a Rest API Gateway as well, we will simply deploy a WebSockets API Gateway and create a Lambda that we will trigger manually to send back messages to our WebSocket client.</li></ul><p>We have a simple web application that allows users to create VDI instances (Virtual Desktop Interface) on the go. The application is fairly simple, users are authenticated and can request their instance from the web interface.</p><p>Users would like to get in real-time notifications about their order of instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YG0sGZ1vfSVbIITeGioKmA.png" /><figcaption>Very simple web application design that demonstrate our use case</figcaption></figure><p>Here, users want to create new instances. Creation of EC2 instances can take some time due to many factors:</p><ul><li>EC2 creation time</li><li>Instance setup (using any automation solution)</li><li>Compliance check</li></ul><p>The user requested to get an update at each step of the instance creation process. Let’s create our notification system, starting on AWS!</p><p>First, let’s log in to AWS and head to the API Gateway service. Create a new WebSocket API Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*ayyFRihYZ0wzr283RINqZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0NujN9sCSKz3GlFNI9xCw.png" /></figure><p>When communicating to a WebSocket API Gateway, you send a payload, in this payload you will need to specify the action you are trying to perform. In this input, you set which key inside of your payload is the action you are trying to perform. We will come back to this later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e3yw0uQ1HNymuvy5IQs3oA.png" /></figure><p>Add the $connect and “$disconnect” predefined routes to your API Gateway.</p><ul><li>$connect: This route is the one called when your client connects to the WebSocket API Gateway</li><li>$disconnect: This route is the one called when your client disconnects to the WebSocket API Gateway</li></ul><p>In our use-case, we don’t need to add any custom routes yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AM0PbaiaQrGimLWAm9kZEg.png" /></figure><p>Then you will want to create some Lambda Functions, one for the $connect route, and another one for the $disconnect route. This is the Lambda function that will be called when the client connect/disconnect to our API Gateway. Remember earlier when we said that we will have to match WebSocket connection ID and Rest API Request ID? Well, the $connect lambda function is a good place to write our logic that store the connection ID somewhere.</p><p>In the $disconnect lambda, we can write the logic that removes our stored connection ID.</p><p>We will write the lambda code later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqrRsi7VMOpIIG5baisVOg.png" /></figure><p>The final step is the stage. Here we are testing things, so we will simply create a first stage named “development”. Click on “Next” and deploy your API Gateway.</p><p>Once our WebSocket API Gateway is deployed, let’s try it. We will use Postman which supports WebSockets.</p><p>Grab your API Gateway WebSocket URL and open Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7ActsRWfinUc2TInBBDlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLJ215ai2Bdn8eVT-0F8gg.png" /></figure><p>Click on Connect, and you shall see that the connection is successful. Great!</p><p>We will add some code to our $connect Lambda function to analyze what’s being passed to that lambda.</p><pre>import json<br><br>def lambda_handler(event, context):<br>    <br>    print(json.dumps(event))<br>    <br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(&#39;Hello from Lambda!&#39;)<br>    }</pre><p>This code will simply dump every passed parameter to that Lambda. Let’s disconnect and then reconnect to our WebSocket API and see those parameters.</p><pre>{<br>    &quot;headers&quot;: {<br>        &quot;Host&quot;: &quot;c9if5l9rgd.execute-api.eu-west-1.amazonaws.com&quot;,<br>        &quot;Sec-WebSocket-Extensions&quot;: &quot;permessage-deflate; client_max_window_bits&quot;,<br>        &quot;Sec-WebSocket-Key&quot;: &quot;q2ueME10A76weGCzBqgq2Q==&quot;,<br>        &quot;Sec-WebSocket-Version&quot;: &quot;13&quot;,<br>        &quot;X-Amzn-Trace-Id&quot;: &quot;Root=1-65feee73-002d1ca83f839f353a4c89b4&quot;,<br>        &quot;X-Forwarded-For&quot;: &quot;xxx&quot;,<br>        &quot;X-Forwarded-Port&quot;: &quot;443&quot;,<br>        &quot;X-Forwarded-Proto&quot;: &quot;https&quot;<br>    },<br>    &quot;multiValueHeaders&quot;: {<br>        ...<br>    },<br>    &quot;requestContext&quot;: {<br>        &quot;routeKey&quot;: &quot;$connect&quot;,<br>        &quot;eventType&quot;: &quot;CONNECT&quot;,<br>        &quot;extendedRequestId&quot;: &quot;VFoyGG1vDoEF2dg=&quot;,<br>        &quot;requestTime&quot;: &quot;23/Mar/2024:15:00:03 +0000&quot;,<br>        &quot;messageDirection&quot;: &quot;IN&quot;,<br>        &quot;stage&quot;: &quot;development&quot;,<br>        &quot;connectedAt&quot;: 1711206003575,<br>        &quot;requestTimeEpoch&quot;: 1711206003576,<br>        &quot;identity&quot;: {<br>            &quot;sourceIp&quot;: &quot;xxx&quot;<br>        },<br>        &quot;requestId&quot;: &quot;VFoyGG1vDoEF2dg=&quot;,<br>        &quot;domainName&quot;: &quot;c9if5l9rgd.execute-api.eu-west-1.amazonaws.com&quot;,<br>        &quot;connectionId&quot;: &quot;VFoyGcaIjoECIjw=&quot;,<br>        &quot;apiId&quot;: &quot;c9if5l9rgd&quot;<br>    },<br>    &quot;isBase64Encoded&quot;: false<br>}</pre><p>Did you notice the important parameter here? “<strong><em>connectionId</em></strong>” that has a value of “VFoyGcaIjoECIjw=”. Note that this number is unique and generated on the client connection.</p><p>We will now create a new Lambda Function that will send a message to a given WebSocket connectionId, to ensure that we are able to reach this connectionId.</p><pre>import json<br>import boto3<br><br>api_gw_id = &quot;c9if5l9rgd&quot; # Change with your WebSocket API Gateway ID<br>region = &quot;eu-west-1&quot; # Change with the region where your WebSocket API Gateway ID is<br><br>def send_message(connectionId: str, message: str, stage: str) -&gt; None:<br>    client = boto3.client(<br>        &quot;apigatewaymanagementapi&quot;,<br>        endpoint_url=f&quot;https://{api_gw_id}.execute-api.{region}.amazonaws.com/{stage}&quot;,<br>    )<br>    client.post_to_connection(<br>        ConnectionId=connectionId, Data=json.dumps(message).encode(&quot;utf-8&quot;)<br>    )<br><br>def lambda_handler(event, context):  <br>    send_message(<br>        connectionId=event[&quot;connectionId&quot;],<br>        message=event[&quot;message&quot;],<br>        stage=event[&quot;stage&quot;]<br>    )<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(&#39;Hello from Lambda!&#39;)<br>    }</pre><p>Create a new test, and set these values:</p><pre>{<br>  &quot;connectionId&quot;: &quot;VFoyGcaIjoECIjw=&quot;, # The Connection ID caught in the $connect dump<br>  &quot;stage&quot;: &quot;development&quot;,<br>  &quot;message&quot;: &quot;Hello Medium&quot; # The message you want to send<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_G9OrN63m_PcP05EiHe0g.png" /></figure><p>We are not done yet! We need to give additional permission to our Lambda Function otherwise we will face a permission denial while invoking our test!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHILr5EvGaM4KyPinXth1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRcpqUejeVdx2EEpX9k4iQ.png" /></figure><pre>{<br>    &quot;Sid&quot;: &quot;Statement1&quot;,<br>    &quot;Effect&quot;: &quot;Allow&quot;,<br>    &quot;Action&quot;: [<br>        &quot;execute-api:ManageConnections&quot;<br>    ],<br>    &quot;Resource&quot;: [<br>        &quot;arn:aws:execute-api:YOUR_REGION:YOUR_ACCOUNT_ID:API_GATEWAY_ID/*/*&quot;<br>    ]<br>}</pre><p>Now, execute your test. You should now see your message on Postman!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBFDQFmEwZo8FmmyEpJAIA.png" /></figure><p>We’re not quite done yet. There is another thing to do, include theses messages in our web application.</p><p>There are tons of ways to perform WebSocket. Here we will use Vanilla JavaScript.</p><p>We will simply add the following code to our web application:</p><pre>&lt;script&gt;<br>const socket = new WebSocket(&#39;ws://your-websocket-server-address&#39;);<br><br>// Event listener for when the connection is established<br>socket.addEventListener(&#39;open&#39;, function (event) {<br>    console.log(&#39;WebSocket connected&#39;);<br>});<br><br>// Event listener for incoming messages<br>socket.addEventListener(&#39;message&#39;, function (event) {<br>    // Display an alert with the received message<br>    alert(&#39;Message received: &#39; + event.data);<br>});<br><br>// Function to send a message to the WebSocket server<br>function sendMessage(message) {<br>    if (socket.readyState === WebSocket.OPEN) {<br>        socket.send(message);<br>        console.log(&#39;Message sent: &#39; + message);<br>    } else {<br>        console.error(&#39;WebSocket connection is not open.&#39;);<br>    }<br>}<br><br>&lt;/script&gt;</pre><p>Once this code is added, we can refresh the page. Our web application will then send a connect request to our WebSocket API Gateway. On the AWS side, just like before, we will fetch the connection ID, and manually run our Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5aoHgqnfnjWwTPK87uVMA.png" /><figcaption>Screenshot of the web application with the message sent from AWS</figcaption></figure><p>And guess what? Our Web Application displays our message! We have made it!</p><h3>👀 Room for improvements</h3><p>Well, as you are probably wondering, I have mentioned earlier the use of a REST API Gateway, an SQS queue but not above, why?</p><p>The general idea was to provide you with a simple use case of how to use WebSockets within the AWS environment.</p><p>On our Web Application, we have a small interface that allows users to create virtual desktop instances. When clicking on the “Request New Instance” button, an HTTP request is sent to our REST API Gateway. When sending this request, we will need to send the Connection ID into our initial payload, that way we will be able to send notifications later, during our instance initialization process.</p><p>Each Lambda Function has to send a message to our SQS queue, to ensure message ordering and delivery. We can then either configure a Lambda that’s triggered on message pushed that will send messages to our WebSocket client or having a scheduler that will invoke our Lambda function and fetch messages from our SQS Queue.</p><h3>🏁 Conclusion</h3><p>We have learned how to use WebSockets on AWS, and it wasn’t that hard, right? I hope that you have enough resources to dig on your own, and maybe implement some of my ideas in one of your projects! Feel free to comment on this post with a link to your project, I will happily take a look at it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a8bcd831cab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>