<?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[The Cloud Journal - Medium]]></title>
        <description><![CDATA[Moving to the cloud is a journey. We are here to walk the path with you and share our learnings. - Medium]]></description>
        <link>https://medium.com/the-cloud-journal?source=rss----aa085d88910a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>The Cloud Journal - Medium</title>
            <link>https://medium.com/the-cloud-journal?source=rss----aa085d88910a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:10:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/the-cloud-journal" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[DevOpsJournal]]></title>
            <link>https://medium.com/the-cloud-journal/devopsjournal-9337276b8abe?source=rss----aa085d88910a---4</link>
            <guid isPermaLink="false">https://medium.com/p/9337276b8abe</guid>
            <dc:creator><![CDATA[h3nryza]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 00:18:26 GMT</pubDate>
            <atom:updated>2023-12-18T00:18:26.838Z</atom:updated>
            <content:encoded><![CDATA[<h4>DevOpsJournal</h4><p><a href="https://medium.com/devopsjournal">DevOpsJournal</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9337276b8abe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-cloud-journal/devopsjournal-9337276b8abe">DevOpsJournal</a> was originally published in <a href="https://medium.com/the-cloud-journal">The Cloud Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remediating least privilege issues using AWS IAM Access Analyser]]></title>
            <link>https://medium.com/the-cloud-journal/remediating-least-privilege-issues-using-aws-iam-access-analyser-5dbb2bbac6dc?source=rss----aa085d88910a---4</link>
            <guid isPermaLink="false">https://medium.com/p/5dbb2bbac6dc</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[least-privilege]]></category>
            <dc:creator><![CDATA[Christian Muller]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 11:34:46 GMT</pubDate>
            <atom:updated>2023-11-24T11:34:46.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXbBhSwXo3NBIJtPOIH1uA.png" /></figure><p>The ‘shift-left’ movement has put much focus on being proactive and preventing security -related issues as early as possible — which is fantastic.</p><p>Remediation and the streamlining thereof might slack behind at times.</p><p>Our responsibility as analysts often stops at the point where we log something while later checking in on a cadence until the issues are fully remediated (depending on environment).</p><p>Picture a scenario where you’re sitting with a substantial amount of excessive permission findings in AWS.</p><p>We all know that developers love analysts logging findings, but we often forget to ease the remediation process for devs.</p><p>Keeping that in mind, how do we go about remediating these excessive permission issues already deployed, while making it as convenient and fool-proof for developers?</p><p><strong><em>The run down</em></strong></p><p>IAM Access Analyser is a free service with multiple use cases. The use case at hand, is the means with which it determines the bare minimum permissions that an IAM role needs based on the principle of least privilege.</p><p>First off, enable access analyser, it’s free. Navigate to IAM to enable the service. You would have to setup/select a CloudTrail trail, to provide the log data needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*kdZYboSEyd_LOapyGpg7jQ.png" /></figure><p>Login as admin into your applicable account. Identify the IAM role you would like to evaluate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*r25cmbKHjN2TdEOcJGoDvw.png" /></figure><ul><li>Take note, that for this example I’ve assigned two AWS Full Access policies to my role ‘S3BucketRole’. This in itself is bad practice, but reflects a real-world scenario, especially in a testing environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Vu-r9x35crNMVkehF_ugAg.png" /></figure><p>You will be presented with an option to “Generate policy based on CloudTrail events”. Click “Generate policy” to kick off the process.</p><ul><li>Do take in regard, that Access Analyser might not be as effective, in cases where roles are shared between multiple workloads/cloud entities (this is not best practice anyways), especially instances from varying services. This will result in Access Analyser identifying a wide scope of permissions, which isn’t what we want.</li></ul><p>Select the timeframe and CloudTrail trail (this can be an Organization trail) plus service linked role (default is fine).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*DK1bicDysHGNBwTbz18VIQ.png" /></figure><ul><li>Might take 2–5 minutes to generate — depending on timeframe ext.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*VcLhDoKOh8-EloZpRYOtmw.png" /></figure><p>Access Analyser will generate a new policy — which is customisable. Identified actions showcased in the screenshot above.</p><ul><li>Calls which are unsuccessful or denied, will also be used to generate the new permissions (CloudTrail: DescribeTrails e.g.), as it pitches up in the logs and classified as behaviour. For example, even if you tried to open the IAM dashboard of a service in the console, while not having access, the denied ‘List’/’Describe’ calls will still be included in the Access Analyser generated policy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*el0GOtYhzeS9f_HU5MZHVg.png" /></figure><p>You do have the option to further customise the generated JSON policy.</p><ul><li>‘BucketName’ is highlighted, reason being that merely stating ‘BucketName’ does not align with the principle of least privilege. The specific bucket(s) needs to be specified to comply with the principle of least privilege.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*-2qGNfHdEEYJlfj4BwBvIw.png" /></figure><p>After navigating through the ‘Review and Create’ stage, you can attach the new generated IAM policy to your Role directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*3YFcAUBSRaFX6Lqg0g85fw.png" /></figure><p>Our role now has the least privilege policy attached. Other overly permissive policies can now be removed.</p><p>That’s about it.</p><p><strong><em>Quick mention regarding overly permissive IAM policies</em></strong></p><p>Poor IAM policies invite security incidents. Unit 42 by Prisma Cloud states that initial access through exposed credentials is a serious concern, but that once an attacker gains initial access, it’s not uncommon for attackers to move laterally with ease as <a href="https://unit42.paloaltonetworks.com/iam-cloud-threat-research/?utm_source=thenewstack&amp;utm_medium=website&amp;utm_content=inline-mention&amp;utm_campaign=platform">99% of cloud identities are overly permissive</a>. It is also known that attackers don’t even need to undergo privilege escalation at times, as IAM role permissions attached to compromised identities are so grossly over privileged.</p><p><strong><em>Conclusion</em></strong></p><p>Reduce risk and enhance your security posture by scoping down on permissions while refining the remediation process. Work smarter — not harder.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dbb2bbac6dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-cloud-journal/remediating-least-privilege-issues-using-aws-iam-access-analyser-5dbb2bbac6dc">Remediating least privilege issues using AWS IAM Access Analyser</a> was originally published in <a href="https://medium.com/the-cloud-journal">The Cloud Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECS (Fargate) with ALB Deployment Using Terraform — Part 2]]></title>
            <link>https://medium.com/the-cloud-journal/ecs-fargate-with-alb-deployment-using-terraform-part-2-5547408be49a?source=rss----aa085d88910a---4</link>
            <guid isPermaLink="false">https://medium.com/p/5547408be49a</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws-ecs-fargate]]></category>
            <category><![CDATA[aws-alb]]></category>
            <dc:creator><![CDATA[Uzairyuseph]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 10:25:22 GMT</pubDate>
            <atom:updated>2023-10-20T19:59:00.533Z</atom:updated>
            <content:encoded><![CDATA[<h3>ECS (Fargate) with ALB Deployment Using Terraform — Part 2</h3><p>This article is a continuation of a larger demonstration on how to create a robust pattern consisting of a highly secured ECS container running a Flask application with connections to a DynamoDB database.</p><p>In <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-1-442e4eae3ee">Part 1</a> of this series, we delved deeply into the architecture of this project, outlining the strategy to ensure high availability and security of our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*49k2rCv-zCQhGb_t.jpeg" /><figcaption>Architecture diagram</figcaption></figure><p>Part 2 will focus on the terraform implementation of the ECS container.</p><p><a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-3-eb52309fdd8f">Part 3</a> will continue with terraform implementation of the supporting resources as well as focusing on the deployment of the application.</p><p><strong>READY!!!</strong></p><p><strong>SET!!!</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FtoXKzaJP3WIgM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FtoXKzaJP3WIgM%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeTZyazE4aGtqeXdxZTVsbjQ1cXg3bmNhMXd0bWx1ZmtkcGN4eXhxbCZlcD12MV9naWZzX2dpZklkJmN0PWc%2FtoXKzaJP3WIgM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="261" frameborder="0" scrolling="no"><a href="https://medium.com/media/655d7c648c376b31edea59577be27bf1/href">https://medium.com/media/655d7c648c376b31edea59577be27bf1/href</a></iframe><h3>Step 3: Terraform</h3><p>Terraform is an Infrastructure as Code (IaC) tool used to define and provision infrastructure. Each resource will be defined in a separate file and will be deployed using a few commands, including the flask application. The full code can be found in <a href="https://github.com/UzairY/AWS-ALB-ECS">this GitHub</a> repo.</p><p>Each set of services in AWS will be created in separate terraform files to logically group these components. The folder structure should look like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*Ty2zC4ji6l3gX1Qf8G0i-w.png" /><figcaption>Main Folder structure</figcaption></figure><h4>Step 3.1 : ECS</h4><p>In the ECS file we define the cluster, the ECS service and the task definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*c8Ft5rKO9dQMiy2RTWgKTA.png" /><figcaption>ECS file</figcaption></figure><p>The cluster is a collection of computing resources required to run the workload. The ECS service manages and configures the tasks that needs to run. It also registers the tasks with the target group (will be discussed later) to receive the distributed traffic.</p><p>The Task Definition resource defines the configurations of the individual tasks and also includes a health check.</p><p><strong><em>ecs.tf</em></strong></p><pre>##########################################################################################<br># This file describes the ECS resources: ECS cluster, ECS task definition, ECS service<br>##########################################################################################<br><br>#ECS cluster<br>resource &quot;aws_ecs_cluster&quot; &quot;ecs_cluster&quot; {<br>    name                                = &quot;test-ecs-cluster&quot;<br>}<br><br>#The Task Definition used in conjunction with the ECS service<br>resource &quot;aws_ecs_task_definition&quot; &quot;task_definition&quot; {<br>    family                              = &quot;test-family&quot;<br>    # container definitions describes the configurations for the task<br>    container_definitions               = jsonencode(<br>    [<br>    {<br>        &quot;name&quot;                          : &quot;test-container&quot;,<br>        &quot;image&quot;                         : &quot;${aws_ecr_repository.ecr.repository_url}:latest&quot;,<br>        &quot;entryPoint&quot;                    : []<br>        &quot;essential&quot;                     : true,<br>        &quot;networkMode&quot;                   : &quot;awsvpc&quot;,<br>        &quot;portMappings&quot;                  : [<br>                                            {<br>                                                &quot;containerPort&quot; : var.container_port,<br>                                                &quot;hostPort&quot;      : var.container_port,<br>                                            }<br>                                          ]<br>        &quot;healthCheck&quot;                   : {<br>                                            &quot;command&quot;     : [ &quot;CMD-SHELL&quot;, &quot;curl -f http://localhost:8081/ || exit 1&quot; ],<br>                                            &quot;interval&quot;    : 30,<br>                                            &quot;timeout&quot;     : 5,<br>                                            &quot;startPeriod&quot; : 10,<br>                                            &quot;retries&quot;     :3<br>                                          }<br>    }<br>    ] <br>    )<br>    #Fargate is used as opposed to EC2, so we do not need to manage the EC2 instances. Fargate is serveless<br>    requires_compatibilities            = [&quot;FARGATE&quot;]<br>    network_mode                        = &quot;awsvpc&quot;<br>    cpu                                 = &quot;256&quot;<br>    memory                              = &quot;512&quot;<br>    execution_role_arn                  = aws_iam_role.ecsTaskExecutionRole.arn<br>    task_role_arn                       = aws_iam_role.ecsTaskRole.arn<br>}<br><br>#The ECS service described. This resources allows you to manage tasks<br>resource &quot;aws_ecs_service&quot; &quot;ecs_service&quot; {<br>    name                                = &quot;test-ecs-service&quot;<br>    cluster                             = aws_ecs_cluster.ecs_cluster.arn<br>    task_definition                     = aws_ecs_task_definition.task_definition.arn<br>    launch_type                         = &quot;FARGATE&quot;<br>    scheduling_strategy                 = &quot;REPLICA&quot;<br>    desired_count                       = 2 # the number of tasks you wish to run<br><br>  network_configuration {<br>    subnets                             = [aws_subnet.private_subnet_1.id , aws_subnet.private_subnet_2.id]<br>    assign_public_ip                    = false<br>    security_groups                     = [aws_security_group.ecs_sg.id, aws_security_group.alb_sg.id]<br>  }<br><br># This block registers the tasks to a target group of the loadbalancer.<br>  load_balancer {<br>    target_group_arn                    = aws_lb_target_group.target_group.arn<br>    container_name                      = &quot;test-container&quot;<br>    container_port                      = var.container_port<br>  }<br>  depends_on                            = [aws_lb_listener.listener]<br>}</pre><h4>Step 3.2 : ECR</h4><p>Amazon ECR (Elastic Container Registry) is a fully managed service which allows for the storage of docker images that can be used to launch containers in AWS.</p><p>The integration between docker and ECR means that standard docker commands can be used to interact with images. Docker commands will be used to push images to ECR.</p><p>There are two sections of the ECR portion. The first is defining the repo and the second is the building and pushing of the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*cdIk1ykId8OJulUfdZdktQ.png" /><figcaption>ECR.tf file</figcaption></figure><p><strong><em>ecr.tf</em></strong></p><pre>#################################################################################################<br># This file describes the ECR resources: ECR repo, ECR policy, resources to build and push image<br>#################################################################################################<br><br>#Creation of the ECR repo<br>resource &quot;aws_ecr_repository&quot; &quot;ecr&quot; {<br>    name                            = &quot;my-test-repo&quot;<br>}<br><br>#The ECR policy describes the management of images in the repo<br>resource &quot;aws_ecr_lifecycle_policy&quot; &quot;ecr_policy&quot; {<br>    repository                      = aws_ecr_repository.ecr.name<br>    policy                          = local.ecr_policy<br>}<br><br>#This is the policy defining the rules for images in the repo<br>locals {<br>  ecr_policy = jsonencode({<br>        &quot;rules&quot;:[<br>            {<br>                &quot;rulePriority&quot;      : 1,<br>                &quot;description&quot;       : &quot;Expire images older than 14 days&quot;,<br>                &quot;selection&quot;: {<br>                    &quot;tagStatus&quot;     : &quot;any&quot;,<br>                    &quot;countType&quot;     : &quot;sinceImagePushed&quot;,<br>                    &quot;countUnit&quot;     : &quot;days&quot;,<br>                    &quot;countNumber&quot;   : 14<br>                },<br>                &quot;action&quot;: {<br>                    &quot;type&quot;          : &quot;expire&quot;<br>                }<br>            }<br>        ]<br>    })<br>}</pre><p>In the above code, the ECR repo is defined as well as a policy. The policy expires any images older than 14 days. You can edit this policy however you prefer or even remove it completely if you want.</p><p>The next part is to push the image. Now, while it is possible to push an image from your command line, I’ve decided to include these scripts in my terraform. In doing so, once I run <em>terraform apply </em>all resources required will be created and I will not need to run any other script.</p><p>This is achieved using the <em>null resource</em> in terraform.</p><p><strong><em>ecr.tf</em></strong></p><pre>#The commands below are used to build and push a docker image of the application in the app folder<br>locals {<br>  docker_login_command              = &quot;aws ecr get-login-password --region ${var.region} --profile personal| docker login --username AWS --password-stdin ${local.account_id}.dkr.ecr.${var.region}.amazonaws.com&quot;<br>  docker_build_command              = &quot;docker build -t ${aws_ecr_repository.ecr.name} ./app&quot;<br>  docker_tag_command                = &quot;docker tag ${aws_ecr_repository.ecr.name}:latest ${local.account_id}.dkr.ecr.${var.region}.amazonaws.com/${aws_ecr_repository.ecr.name}:latest&quot;<br>  docker_push_command               = &quot;docker push ${local.account_id}.dkr.ecr.${var.region}.amazonaws.com/${aws_ecr_repository.ecr.name}:latest&quot;<br>}<br><br>#This resource authenticates you to the ECR service<br>resource &quot;null_resource&quot; &quot;docker_login&quot; {<br>    provisioner &quot;local-exec&quot; {<br>        command                     = local.docker_login_command<br>    }<br>    triggers = {<br>        &quot;run_at&quot;                    = timestamp()<br>    }<br>    depends_on                      = [ aws_ecr_repository.ecr ]<br>}<br><br>#This resource builds the docker image from the Dockerfile in the app folder<br>resource &quot;null_resource&quot; &quot;docker_build&quot; {<br>    provisioner &quot;local-exec&quot; {<br>        command                     = local.docker_build_command<br>    }<br>    triggers = {<br>        &quot;run_at&quot;                    = timestamp()<br>    }<br>    depends_on                      = [ null_resource.docker_login ]<br>}<br><br>#This resource tags the image <br>resource &quot;null_resource&quot; &quot;docker_tag&quot; {<br>    provisioner &quot;local-exec&quot; {<br>        command                     = local.docker_tag_command<br>    }<br>    triggers = {<br>        &quot;run_at&quot;                    = timestamp()<br>    }<br>    depends_on                      = [ null_resource.docker_build ]<br>}<br><br>#This resource pushes the docker image to the ECR repo<br>resource &quot;null_resource&quot; &quot;docker_push&quot; {<br>    provisioner &quot;local-exec&quot; {<br>        command                     = local.docker_push_command<br>    }<br>    triggers = {<br>        &quot;run_at&quot;                    = timestamp()<br>    }<br>    depends_on                      = [ null_resource.docker_tag ]<br>}</pre><p>These four commands are required for the push of the docker image to the repo. In each resource there is a dependency included, this ensures the commands are run in a specific order. The triggers are also set for each command to run at runtime, meaning every time a <em>terraform apply</em> is done, the image will be pushed to the repo.</p><h4>Step 3.3 : DynamoDB</h4><p>DynamoDB is a fully managed NoSQL AWS database. This database is schema-less and easy to use. This makes the perfect option for a basic application to get all the services running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*19J9B7YEyBiyaaBoQQ0Fqg.png" /><figcaption>DynamoDB.tf file</figcaption></figure><p><strong><em>dynamodb.tf</em></strong></p><pre>#################################################################################################<br># This file describes the DynamoDB resources: dynamodb table, dynamodb endpoint<br>#################################################################################################<br><br>#Dynamodb Table<br>resource &quot;aws_dynamodb_table&quot; &quot;test_table&quot; {<br>    name                = &quot;leavedays&quot;<br>    billing_mode        = &quot;PAY_PER_REQUEST&quot;<br>    hash_key            = &quot;leave_id&quot;<br>    attribute {<br>        name            = &quot;leave_id&quot;<br>        type            = &quot;N&quot;<br>    }<br>}<br><br>#DynamoDB Endpoint<br>resource &quot;aws_vpc_endpoint&quot; &quot;dynamodb_Endpoint&quot; {<br>    vpc_id              = aws_vpc.vpc.id<br>    service_name        = &quot;com.amazonaws.eu-west-1.dynamodb&quot;<br>    vpc_endpoint_type   = &quot;Gateway&quot;<br>    route_table_ids     = [aws_route_table.private.id]<br>    policy              = jsonencode({<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; : &quot;*&quot;,<br>                &quot;Action&quot;    : &quot;*&quot;,<br>                &quot;Resource&quot;  : &quot;*&quot;<br>            }<br>        ]<br>    })<br>}</pre><p>This file describes the DynamoDB table as well as the VPC Endpoint. In the definition of the endpoint a route table is attached. A route needs to be present in the route table of the private subnets in order for the ECS containers in the private subnet to connect to DynamoDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5cdAn56gZSMmy_0yU_MLA.png" /><figcaption>VPC endpoint route</figcaption></figure><p>The ‘Target’ in the above picture is the VPC endpoint ID and the ‘Destination’ is a prefix list. A prefix list is a group of IP addresses that corresponds to to that particular services in its corresponding region.<br>More information about prefix lists can be found <a href="https://docs.aws.amazon.com/vpc/latest/userguide/working-with-aws-managed-prefix-lists.html#use-aws-managed-prefix-list">here</a>.</p><p>And that’s where we’ll end Part 2. You can catch <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-3-eb52309fdd8f">Part 3</a> here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5547408be49a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-cloud-journal/ecs-fargate-with-alb-deployment-using-terraform-part-2-5547408be49a">ECS (Fargate) with ALB Deployment Using Terraform — Part 2</a> was originally published in <a href="https://medium.com/the-cloud-journal">The Cloud Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECS (Fargate) with ALB Deployment Using Terraform — Part 3]]></title>
            <link>https://medium.com/the-cloud-journal/ecs-fargate-with-alb-deployment-using-terraform-part-3-eb52309fdd8f?source=rss----aa085d88910a---4</link>
            <guid isPermaLink="false">https://medium.com/p/eb52309fdd8f</guid>
            <category><![CDATA[ecs-fargate]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Uzairyuseph]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 10:25:20 GMT</pubDate>
            <atom:updated>2023-10-20T20:07:02.781Z</atom:updated>
            <content:encoded><![CDATA[<h3>ECS (Fargate) with ALB Deployment Using Terraform — Part 3</h3><p>This article is a continuation of a larger demonstration on how to create a robust pattern consisting of a highly secured ECS container running a Flask application with connections to a DynamoDB database.</p><p>In <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-1-442e4eae3ee">Part 1</a> of this series, we delved deeply into the architecture of this project, outlining the strategy to ensure high availability and security of our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*5rc3BEEVx8Uk9iUk.jpeg" /><figcaption>Architecture diagram</figcaption></figure><p>In <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-2-5547408be49a">Part 2</a> of this series, we focused the terraform implementation of the core services of this application: ECS container, ECR repo and the DynamoDB database.</p><p>In this final Part 3, we will continue with the terraform implementation of the supporting resources as well as focus on the deployment of the application.</p><h4>Step 3.4: VPC</h4><p>The main.tf file is where the VPC, subnets, route tables and more networking resources are defined. This sets the foundation on which we can now add the other required resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*xQqAiy9mloDYD_hiGDCk9Q.png" /><figcaption>main.tf file</figcaption></figure><p><strong><em>main.tf</em></strong></p><pre>###################################################################################<br># This file describes the vpc, internet gateway, nat gateway and route tables<br>###################################################################################<br><br>resource &quot;aws_vpc&quot; &quot;vpc&quot; {<br>    cidr_block              = var.vpc_cidr<br>    enable_dns_hostnames    = true<br>    enable_dns_support      = true<br>}<br><br>resource &quot;aws_internet_gateway&quot; &quot;igw&quot; {<br>    vpc_id                  = aws_vpc.vpc.id<br>}<br><br>resource &quot;aws_nat_gateway&quot; &quot;ngw&quot; {<br>    allocation_id           = aws_eip.nateip.id<br>    subnet_id               = aws_subnet.public_subnet_1.id<br>    depends_on              = [ aws_internet_gateway.igw ]<br>}<br><br>resource &quot;aws_eip&quot; &quot;nateip&quot; {<br>    domain                  = &quot;vpc&quot;<br>}<br><br>resource &quot;aws_subnet&quot; &quot;private_subnet_1&quot; {<br>    vpc_id                  = aws_vpc.vpc.id<br>    cidr_block              = var.private_subnet_1<br>    availability_zone       = var.availibilty_zone_1<br>}<br><br>resource &quot;aws_subnet&quot; &quot;private_subnet_2&quot; {<br>    vpc_id                  = aws_vpc.vpc.id<br>    cidr_block              = var.private_subnet_2<br>    availability_zone       = var.availibilty_zone_2<br>}<br><br>resource &quot;aws_subnet&quot; &quot;public_subnet_1&quot; {<br>    vpc_id                  = aws_vpc.vpc.id<br>    cidr_block              = var.public_subnet_1<br>    availability_zone       = var.availibilty_zone_1<br>    map_public_ip_on_launch = true<br>}<br><br>resource &quot;aws_subnet&quot; &quot;public_subnet_2&quot; {<br>    vpc_id                  = aws_vpc.vpc.id<br>    cidr_block              = var.public_subnet_2<br>    availability_zone       = var.availibilty_zone_2<br>    map_public_ip_on_launch = true<br>}<br><br>resource &quot;aws_route_table&quot; &quot;public&quot; {<br>    vpc_id                  = aws_vpc.vpc.id<br>    <br>}<br><br>resource &quot;aws_route&quot; &quot;public&quot; {<br>    route_table_id          = aws_route_table.public.id<br>    destination_cidr_block  = &quot;0.0.0.0/0&quot;<br>    gateway_id              = aws_internet_gateway.igw.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public1&quot; {<br>    subnet_id               = aws_subnet.public_subnet_1.id<br>    route_table_id          = aws_route_table.public.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;public2&quot; {<br>    subnet_id               = aws_subnet.public_subnet_2.id<br>    route_table_id          = aws_route_table.public.id<br>}<br><br><br><br>resource &quot;aws_route_table&quot; &quot;private&quot; {<br>    vpc_id                  = aws_vpc.vpc.id<br>}<br>  <br>resource &quot;aws_route&quot; &quot;private&quot; {<br>    route_table_id          = aws_route_table.private.id<br>    destination_cidr_block  = &quot;0.0.0.0/0&quot;<br>    nat_gateway_id          = aws_nat_gateway.ngw.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;private1&quot; {<br>    subnet_id               = aws_subnet.private_subnet_1.id<br>    route_table_id          = aws_route_table.private.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;private2&quot; {<br>    subnet_id               = aws_subnet.private_subnet_2.id<br>    route_table_id          = aws_route_table.private.id<br>}</pre><h4>Step 3.5 : ALB</h4><p>There are three <em>parts</em> needed to configure the ALB.</p><ol><li>First is the actual Load Balancer. As seen in the configuration below, the ALB is an external Load balancer and also has a security group attached, this will be explained later.</li><li>Next is the target group. This the group of resources that will receive traffic from the ALB. A health check is also included as a measure of availability and reliability of the target groups.</li><li>Finally we have the listener. This resource specifies the protocol and port the ALB should use to process and deliver traffic. In this project only HTTP will be used. It is recommended to include HTTPS for secure traffic.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*9f1U7xuobcUvPZEJqyuzWQ.png" /><figcaption>alb.tf file</figcaption></figure><p><strong><em>alb.tf</em></strong></p><pre>#################################################################################################<br># This file describes the Load Balancer resources: ALB, ALB target group, ALB listener<br>#################################################################################################<br><br>#Defining the Application Load Balancer<br>resource &quot;aws_alb&quot; &quot;application_load_balancer&quot; {<br>  name                      = &quot;test-alb&quot;<br>  internal                  = false<br>  load_balancer_type        = &quot;application&quot;<br>  subnets                   = [aws_subnet.public_subnet_1.id, aws_subnet.public_subnet_2.id]<br>  security_groups           = [aws_security_group.alb_sg.id]<br>}<br><br>#Defining the target group and a health check on the application<br>resource &quot;aws_lb_target_group&quot; &quot;target_group&quot; {<br>  name                      = &quot;test-tg&quot;<br>  port                      = var.container_port<br>  protocol                  = &quot;HTTP&quot;<br>  target_type               = &quot;ip&quot;<br>  vpc_id                    = aws_vpc.vpc.id<br>  health_check {<br>      path                  = &quot;/health&quot;<br>      protocol              = &quot;HTTP&quot;<br>      matcher               = &quot;200&quot;<br>      port                  = &quot;traffic-port&quot;<br>      healthy_threshold     = 2<br>      unhealthy_threshold   = 2<br>      timeout               = 10<br>      interval              = 30<br>  }<br>}<br><br>#Defines an HTTP Listener for the ALB<br>resource &quot;aws_lb_listener&quot; &quot;listener&quot; {<br>  load_balancer_arn         = aws_alb.application_load_balancer.arn<br>  port                      = &quot;80&quot;<br>  protocol                  = &quot;HTTP&quot;<br><br>  default_action {<br>    type                    = &quot;forward&quot;<br>    target_group_arn        = aws_lb_target_group.target_group.arn<br>  }<br>}</pre><h4>Step 3.6 : IAM</h4><p>IAM (Identity and Access Management) roles are used to give resources and services permissions and restrict what can be done by using the principle of least privilege.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*Q0KrQZCvLaRZYvADprVC7A.png" /><figcaption>iam.tf file</figcaption></figure><p><strong><em>iam.tf</em></strong></p><pre>#################################################################################################<br># This file describes the IAM resources: ECS task role, ECS execution role<br>#################################################################################################<br><br>resource &quot;aws_iam_role&quot; &quot;ecsTaskExecutionRole&quot; {<br>    name                  = &quot;test-app-ecsTaskExecutionRole&quot;<br>    assume_role_policy    = data.aws_iam_policy_document.assume_role_policy.json<br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;assume_role_policy&quot; {<br>  statement {<br>    actions               = [&quot;sts:AssumeRole&quot;]<br><br>    principals {<br>      type                = &quot;Service&quot;<br>      identifiers         = [&quot;ecs-tasks.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecsTaskExecutionRole_policy&quot; {<br>    role                  = aws_iam_role.ecsTaskExecutionRole.name<br>    policy_arn            = &quot;arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy&quot;<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;ecsTaskRole&quot; {<br>    name                  = &quot;ecsTaskRole&quot;<br>    assume_role_policy    = data.aws_iam_policy_document.assume_role_policy.json   <br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecsTaskRole_policy&quot; {<br>    role                  = aws_iam_role.ecsTaskRole.name<br>    policy_arn            = &quot;arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess&quot;<br>}</pre><p>As seen in the ecs section, two roles are defined in the <em>ecs.tf</em> file, the <em>execution_role </em>and the <em>task_role. </em>The execution role refers to the role required for the underlying infrastructure on which the containers run. This role has the permissions of ‘<a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html">AmazonECSTaskExecutionRolePolicy</a>’.</p><p>The task role refers to permissions required for the actual application. Since the application will require connectivity to DynamoDB, an ‘<a href="https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonDynamoDBFullAccess.html">AmazonDynamoDBFullAccess</a>’ policy is attached to the task role.</p><h4>Step 3.7 : Security Groups</h4><p>Security groups in AWS act as virtual firewalls for services. Inbound and outbound traffic can be controlled using security groups.</p><p>Two security groups are created in the project, one for the ALB and the other for the ECS service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*0ZjiKHeHR6A6TIHPf2fsMQ.png" /></figure><p><strong><em>securitygroup.tf</em></strong></p><pre># ------------------------------------------------------------------------------<br># Security Group for ECS app<br># ------------------------------------------------------------------------------<br>resource &quot;aws_security_group&quot; &quot;ecs_sg&quot; {<br>    vpc_id                      = aws_vpc.vpc.id<br>    name                        = &quot;demo-sg-ecs&quot;<br>    description                 = &quot;Security group for ecs app&quot;<br>    revoke_rules_on_delete      = true<br>}<br># ------------------------------------------------------------------------------<br># ECS app Security Group Rules - INBOUND<br># ------------------------------------------------------------------------------<br>resource &quot;aws_security_group_rule&quot; &quot;ecs_alb_ingress&quot; {<br>    type                        = &quot;ingress&quot;<br>    from_port                   = 0<br>    to_port                     = 0<br>    protocol                    = &quot;-1&quot;<br>    description                 = &quot;Allow inbound traffic from ALB&quot;<br>    security_group_id           = aws_security_group.ecs_sg.id<br>    source_security_group_id    = aws_security_group.alb_sg.id<br>}<br># ------------------------------------------------------------------------------<br># ECS app Security Group Rules - OUTBOUND<br># ------------------------------------------------------------------------------<br>resource &quot;aws_security_group_rule&quot; &quot;ecs_all_egress&quot; {<br>    type                        = &quot;egress&quot;<br>    from_port                   = 0<br>    to_port                     = 0<br>    protocol                    = &quot;-1&quot;<br>    description                 = &quot;Allow outbound traffic from ECS&quot;<br>    security_group_id           = aws_security_group.ecs_sg.id<br>    cidr_blocks                 = [&quot;0.0.0.0/0&quot;] <br>}<br><br># ------------------------------------------------------------------------------<br># Security Group for alb<br># ------------------------------------------------------------------------------<br>resource &quot;aws_security_group&quot; &quot;alb_sg&quot; {<br>    vpc_id                      = aws_vpc.vpc.id<br>    name                        = &quot;demo-sg-alb&quot;<br>    description                 = &quot;Security group for alb&quot;<br>    revoke_rules_on_delete      = true<br>}<br># ------------------------------------------------------------------------------<br># Alb Security Group Rules - INBOUND<br># ------------------------------------------------------------------------------<br>resource &quot;aws_security_group_rule&quot; &quot;alb_http_ingress&quot; {<br>    type                        = &quot;ingress&quot;<br>    from_port                   = 80<br>    to_port                     = 80<br>    protocol                    = &quot;TCP&quot;<br>    description                 = &quot;Allow http inbound traffic from internet&quot;<br>    security_group_id           = aws_security_group.alb_sg.id<br>    cidr_blocks                 = [&quot;0.0.0.0/0&quot;] <br>}<br>resource &quot;aws_security_group_rule&quot; &quot;alb_https_ingress&quot; {<br>    type                        = &quot;ingress&quot;<br>    from_port                   = 443<br>    to_port                     = 443<br>    protocol                    = &quot;TCP&quot;<br>    description                 = &quot;Allow https inbound traffic from internet&quot;<br>    security_group_id           = aws_security_group.alb_sg.id<br>    cidr_blocks                 = [&quot;0.0.0.0/0&quot;] <br>}<br># ------------------------------------------------------------------------------<br># Alb Security Group Rules - OUTBOUND<br># ------------------------------------------------------------------------------<br>resource &quot;aws_security_group_rule&quot; &quot;alb_egress&quot; {<br>    type                        = &quot;egress&quot;<br>    from_port                   = 0<br>    to_port                     = 0<br>    protocol                    = &quot;-1&quot;<br>    description                 = &quot;Allow outbound traffic from alb&quot;<br>    security_group_id           = aws_security_group.alb_sg.id<br>    cidr_blocks                 = [&quot;0.0.0.0/0&quot;] <br>}</pre><h4>Step 3.8 : Variables</h4><p>Throughout the terraform files, variables have been referenced and these variables are created and stored separately from the other configuration files. The reason for this is to create an easily reusable template where the only values that need to be changed are the variables.</p><p>The variables section consists of two parts. The <em>variables.tf </em>file and the <em>terraform.tfvars</em> file. The first file declares all variables used in the project and the second file attaches a value to these variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*aklHIZj4ukAdbrOGCVuegA.png" /><figcaption>variables file</figcaption></figure><p><strong><em>terraform.tfvars</em></strong></p><pre>#These are the only value that need to be changed on implementation<br>region                      = &quot;eu-west-1&quot;<br>vpc_cidr                    = &quot;10.0.0.0/16&quot;<br>public_subnet_1             = &quot;10.0.16.0/20&quot;<br>public_subnet_2             = &quot;10.0.32.0/20&quot;<br>private_subnet_1            = &quot;10.0.80.0/20&quot;<br>private_subnet_2            = &quot;10.0.112.0/20&quot;<br>availibilty_zone_1          = &quot;eu-west-1a&quot;<br>availibilty_zone_2          = &quot;eu-west-1b&quot;<br>container_port              = 8081<br>shared_config_files         = &quot;&quot; # Replace with path<br>shared_credentials_files    = &quot;&quot; # Replace with path<br>credential_profile          = &quot;&quot; # Replace with what you named your profile</pre><p>The terraform.tfvars file is the only file that needs to be changed when implementing this project.</p><p>The complete source for this application can be found <a href="https://github.com/UzairY/AWS-ALB-ECS.git"><strong>here</strong></a>.</p><h3>Step 4: Deployment</h3><p>Its now time to deploy the application and test. Ensure that the folder structure of the directory looks something like the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*Ty2zC4ji6l3gX1Qf8G0i-w.png" /><figcaption>Main Folder structure</figcaption></figure><p>The app folder will contain the flask application and the folder directory needs to be as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*VE7I9ZuRTPBkMWEi8jQ0BA.png" /><figcaption>Flask app folder structure</figcaption></figure><p>The application is now ready to de deployed.</p><p>Open a CMD prompt in the directory of your terraform files.</p><p>Run:</p><pre>terraform init</pre><p>This will initialize the working directory for terraform and download all required providers.</p><p>Then:</p><pre>terraform plan</pre><p>The above command allows you to review the changes that will be made once applied. If there are no issues and you are happy with the configurations you can run the last step.</p><pre>terraform apply</pre><p>The above command deploys the infrastructure described in our code.</p><h3>Step 5: Accessing the app</h3><p>After step 4 is completed and terraform has deployed the required infrastructure, head over to the AWS console.<br>Locate the load balancer and find the ‘DNS name’ under the details section of the load balancer.</p><p>Copy the DNS name and paste it in your browser. You should now be able to access your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*8kqP5i86wjFEBhWH3lGErg.png" /><figcaption>Application</figcaption></figure><p>We can also confirm that our health check works as expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*UWqJ68PKziS-ug2Ldjv7-g.png" /><figcaption>Health check path</figcaption></figure><p>To summarize, we’ve embarked on an exciting journey of containerization with Amazon ECS. We’ve built resilient and highly available container tasks. We have also secured the containers in a private subnet and introduced an Application Load Balancer to add security and scalability.</p><p>Of course this isn’t the end but just a starting point. You can take this project to the next level.</p><p>A few considerations:</p><ul><li>Add an SSL certificate for HTTPS requests</li><li>Security groups can be more secure</li><li>IAM roles can be more restrictive</li><li>ECR can also use a VPC endpoint to pull images</li></ul><p>If you have more recommendations or if you would just like to share your experiences, please feel free to fill the comments below.</p><p>Once again <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-1-442e4eae3ee">Part 1</a> and <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-2-5547408be49a">Part 2</a> links are attached as well as the <a href="https://github.com/UzairY/AWS-ALB-ECS">GitHub</a> repo</p><p>Thank you!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl4pTjOu0NsrLApt0Q%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl4pTjOu0NsrLApt0Q%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl4pTjOu0NsrLApt0Q%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/df9f78a5b778181160629c804cc14b83/href">https://medium.com/media/df9f78a5b778181160629c804cc14b83/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb52309fdd8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-cloud-journal/ecs-fargate-with-alb-deployment-using-terraform-part-3-eb52309fdd8f">ECS (Fargate) with ALB Deployment Using Terraform — Part 3</a> was originally published in <a href="https://medium.com/the-cloud-journal">The Cloud Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECS (Fargate) with ALB Deployment Using Terraform — Part 1]]></title>
            <link>https://medium.com/the-cloud-journal/ecs-fargate-with-alb-deployment-using-terraform-part-1-442e4eae3ee?source=rss----aa085d88910a---4</link>
            <guid isPermaLink="false">https://medium.com/p/442e4eae3ee</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws-alb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-ecs-fargate]]></category>
            <dc:creator><![CDATA[Uzairyuseph]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 10:25:18 GMT</pubDate>
            <atom:updated>2023-10-20T19:52:24.696Z</atom:updated>
            <content:encoded><![CDATA[<h3>ECS (Fargate) with ALB Deployment Using Terraform — Part 1</h3><p>Today I will walk you through an in-depth demonstration on how to create a robust pattern consisting of a highly secured ECS container running a Flask application with connections to a DynamoDB database. To ensure seamless traffic and high availability, an Application Load Balancer will be used to serve traffic to the secured containers.</p><p>Amazon Web Services (AWS) provides many amazing services especially in the world of ‘serverless’. However, adopting Cloud is not necessarily the easiest task. Fortunately, there are millions of tutorials on the net allowing you to leverage the power of the cloud just like this one.</p><p>These are a few services and tools that will be used in this project:<br>1. Firstly <a href="https://aws.amazon.com/">AWS</a>, of course<br>2. <a href="https://aws.amazon.com/ecs/">ECS</a> — Containerization service in AWS<br>3. <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a> — NoSQL database service in AWS<br>4. <a href="https://aws.amazon.com/ecr/">ECR</a> — A Container repository containing docker images<br>5. <a href="https://aws.amazon.com/elasticloadbalancing/application-load-balancer/">ALB</a> — Application Load Balancer <br>6. <a href="https://www.terraform.io/">Terraform</a> — IaC(Infrastructure as Code) tool<br>7. <a href="https://www.docker.com/">Docker</a> — Containerization platform<br>8. <a href="https://flask.palletsprojects.com/en/3.0.x/">Flask </a>— Web application framework</p><p>The complete source for this application can be found <a href="https://github.com/UzairY/AWS-ALB-ECS.git"><strong>here</strong></a>.</p><p>Now that appetizers are done</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F64aBXTVfd90zyUH2da%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fabcnetwork-start-the-rookie-lets-begin-64aBXTVfd90zyUH2da&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeHg5aWdwamRreDk4MWdvb3hob3dycG1sMmlmNWJ6azMwendhODg5eSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F64aBXTVfd90zyUH2da%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca2a21e5bb4b5507a57186d6bd1d11c1/href">https://medium.com/media/ca2a21e5bb4b5507a57186d6bd1d11c1/href</a></iframe><p>Here are the main steps for this projects. <em>Skip at your own peril</em></p><h3>Contents:</h3><blockquote>Step 1: <a href="#e99e">Assumptions</a></blockquote><blockquote>Step 2: <a href="#8ed4">The architecture</a></blockquote><blockquote>Step 3: <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-2-5547408be49a">Terraform</a></blockquote><blockquote>Step 4: <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-3-eb52309fdd8f">Deployment</a></blockquote><blockquote>Step 5: <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-3-eb52309fdd8f">Accessing the app</a></blockquote><p>Given the extensive scope and depth of this project, I’ve divided it into three distinct parts.</p><p>Part 1 will encompass the first two steps, offering a comprehensive introduction and detailed exploration of the project’s architecture.</p><p>Step 3, focusing on Terraform implementation, will be divided across <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-2-5547408be49a">Part 2</a> and <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-3-eb52309fdd8f">Part 3</a>. In<a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-2-5547408be49a"> Part 2</a>, we’ll delve into container resources, while <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-3-eb52309fdd8f">Part 3</a> will cover the intricacies of supporting resources and also cover Step 4 and 5.</p><h3>Step 1: Assumptions</h3><p>I will assume you already have the following setup, if not, I will attach a link as to how you can set it up:</p><ul><li>Your own <a href="https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html">AWS account</a></li><li><a href="https://docs.docker.com/desktop/install/windows-install/">Docker</a> on your machine</li><li><a href="https://developer.hashicorp.com/terraform/downloads">Terraform</a></li><li><a href="https://aws.amazon.com/cli/">AWS CLI</a></li><li>A sample application(Optional. My sample flask application can be used)</li></ul><h3>Step 2: The architecture</h3><p>So before getting into the code part of the project, it’s a good idea to visualize what is actually being built and understand where the different components fit.</p><p>The diagram below was drawn using <a href="https://app.diagrams.net/">draw.io</a>. It depicts a high-level architecture of our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*LL5Tf1X3KRdOiqYVIfV_Jg.jpeg" /><figcaption>Figure 1: Architecture diagram</figcaption></figure><p>An explanation of the main components:</p><p>All resources in this project will be deployed in the Ireland region (eu-west-1). You can choose any other available <a href="https://aws.amazon.com/about-aws/global-infrastructure/regions_az/">AWS region</a> you’d like.</p><p>The resources will also be deployed in a VPC (Virtual Private Cloud). This ensures an isolated network environment, which acts as a security barrier for our application. Traffic to and from our VPC can be controlled with Security Groups, NACLs (Network Access Control lists) and subnets.</p><p>As shown in the diagram, the ECS container will be deployed in private subnets. Private subnets are totally isolated from the public internet.</p><p>It is a good security measure to ensure that when users access the application, they don’t directly access the container. And this is why we have the ALB (Application Load Balancer). The ALB will receive traffic from the internet and distribute the traffic to the ECS tasks.</p><p>The Flask application that is part of this project is structured to connect to a DynamoDB database. DynamoDB is a NoSQL database provided by AWS. The endpoint is used to ensure that the application, when connecting to DynamoDB, does not need to traverse the public internet. Traffic via an endpoint flows through the AWS network, further increasing the security standpoint of the application.</p><p>Internet gateways facilitate traffic between the VPC and the public internet. It allows users to access whatever resources are made available to the internet, in this case it is the ALB.</p><p>NAT gateways are egress-only gateways. This means it only has the capabilities for outbound connections to the internet and cannot receive traffic from the internet.</p><p>Now that we know what we are building, lets move on to <a href="https://medium.com/@uzairyuseph/ecs-fargate-with-alb-deployment-using-terraform-part-2-5547408be49a">Part 2</a> to get messy with terraform.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F7gAULpAkC2vSw%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F7gAULpAkC2vSw%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F7gAULpAkC2vSw%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd367f8bdb69bd10c68d7b178ec3bcef/href">https://medium.com/media/dd367f8bdb69bd10c68d7b178ec3bcef/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=442e4eae3ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-cloud-journal/ecs-fargate-with-alb-deployment-using-terraform-part-1-442e4eae3ee">ECS (Fargate) with ALB Deployment Using Terraform — Part 1</a> was originally published in <a href="https://medium.com/the-cloud-journal">The Cloud Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS lambda and API gateway in TERRAFORM.]]></title>
            <link>https://medium.com/the-cloud-journal/aws-lambda-and-api-gateway-in-terraform-c44f5d5b4374?source=rss----aa085d88910a---4</link>
            <guid isPermaLink="false">https://medium.com/p/c44f5d5b4374</guid>
            <dc:creator><![CDATA[Karabonkgoatau]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 19:09:20 GMT</pubDate>
            <atom:updated>2023-09-20T19:09:20.383Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, you create a REST API through which you invoke a Lambda function using an HTTP request. Your Lambda function will perform create, read, update, and delete (CRUD) operations on a Mariadb. This function is provided here for demonstration, but you will learn to configure an API Gateway REST API that can invoke any Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*mIS80SodQErLSYftalmRbA.png" /></figure><p>Amazon Web Services (AWS) API Gateway and AWS Lambda are commonly used services for building and deploying serverless applications and APIs. To set up and use these services effectively, you’ll need various resources and configurations. Below, I’ll list and explain the key resources required for AWS API Gateway and Lambda functions:</p><h4>AWS API Gateway Resources:</h4><ol><li>API Gateway: This is the core resource that acts as the front door to your APIs. It provides HTTP endpoints for clients to access your application or services. You can create and configure APIs within the API Gateway console or using the AWS CLI.</li><li>API Gateway Stage: Stages represent different versions or environments of your API, such as “dev,” “test,” or “prod.” Each stage can have its own configuration, deployment settings, and deployment history.</li><li>API Gateway Resources and Methods: Within your API Gateway, you define resources and methods. Resources represent the paths in your API (e.g., /users), while methods are the HTTP verbs (e.g., GET, POST) associated with those resources. You configure each method to connect to a Lambda function or other AWS service.</li><li>API Gateway Authorizers: Authorizers control access to your API by validating user credentials or tokens. You can configure authorizers to authenticate users before allowing access to specific API methods.</li><li>API Gateway Custom Domain: To use your own domain name (e.g., api.example.com) instead of the default API Gateway URL, you’ll need to configure a custom domain. This involves setting up a domain name, SSL/TLS certificates, and linking it to your API Gateway stage.</li></ol><h4>AWS Lambda Function Resources:</h4><ol><li>Lambda Function: This is the serverless compute resource that executes your application code in response to API Gateway requests or other events. Each Lambda function has its own configuration, code, and runtime environment.</li><li>Lambda Execution Role: To give Lambda functions access to AWS services and resources, you need to create an IAM (Identity and Access Management) role and attach it to your Lambda function. This role defines what permissions the Lambda function has.</li><li>Deployment Package: Your Lambda function code and any dependencies should be packaged as a ZIP file or container image (for Lambda Container support). AWS Lambda retrieves this package and runs your code when triggered.</li><li>Environment Variables: You can set environment variables for your Lambda function to provide configuration settings, secrets, or other runtime parameters. These variables can be accessed within your code.</li><li>Triggers: For API Gateway integration, you’ll configure API Gateway as a trigger for your Lambda function. This tells Lambda to execute your code when specific API endpoints are accessed. Additionally, Lambda can be triggered by other AWS services like S3, SNS, or CloudWatch Events.</li></ol><p>6. VPC Configuration (Optional): If your Lambda function needs to access resources within a Virtual Private Cloud (VPC), you’ll need to configure the function to run within the VPC and specify appropriate security groups and subnets.</p><p>7. Dead Letter Queue (DLQ) (Optional): Amazon SQS supports <em>dead-letter queues</em> (DLQ), which other queues (<em>source queues</em>) can target for messages that can’t be processed (consumed) successfully. Dead-letter queues are useful for debugging your application or messaging system because they let you isolate unconsumed messages to determine why their processing didn’t succeed</p><p>These are the core resources and configurations needed to set up and operate AWS API Gateway and Lambda functions. Depending on your specific use case, you may require additional AWS services or resources, such as DynamoDB for database storage or AWS Cognito for user authentication and management.</p><p>Now lets have a look at the terraform code:</p><h4>Main.tf</h4><p>main.tf will contain the main set of configuration for your module</p><p>Bucket creation and ownership controls.S3 Object Ownership is an Amazon S3 bucket-level setting that you can use to control ownership of objects uploaded to your bucket and to disable or enable <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html">access control lists (ACLs)</a>. By default, Object Ownership is set to the Bucket owner enforced setting and all ACLs are disabled.</p><pre># Bucket creation and ownership controls<br>resource &quot;aws_s3_bucket&quot; &quot;lambda_bucket&quot; {<br>  bucket = random_pet.lambda_bucket_name.id<br>}<br>resource &quot;aws_s3_bucket_ownership_controls&quot; &quot;Lambda_Bucket_Ownership_Controls&quot; {<br>  bucket = aws_s3_bucket.lambda_bucket.id<br><br>  rule {<br>    object_ownership = &quot;BucketOwnerPreferred&quot;<br>  }<br>}</pre><p>This function takes an incoming event object from Lambda and logs it to the console.Then it returns an object which API Gateway will use to generate an HTTP response</p><pre># This function takes an incoming event object from Lambda and logs it to the console. <br># Then it returns an object which API Gateway will use to generate an HTTP response<br><br>resource &quot;aws_s3_object&quot; &quot;lambda_hello_world&quot; {<br>  bucket = aws_s3_bucket.lambda_bucket.id<br><br>  key    = &quot;hello-world.zip&quot;<br>  source = data.archive_file.lambda_hello_world.output_path<br><br>  etag = filemd5(data.archive_file.lambda_hello_world.output_path)<br>}</pre><p>The following code is used to define your Lambda function and related resources</p><pre>#The following code is used to define your Lambda function and related resources.<br>resource &quot;aws_lambda_function&quot; &quot;hello_world&quot; {<br>  function_name = &quot;HelloWorld&quot;<br><br>  s3_bucket = aws_s3_bucket.lambda_bucket.id<br>  s3_key    = aws_s3_object.lambda_hello_world.key<br><br>  runtime = &quot;nodejs18.x&quot; # Make sure its the latest version of nodejs run npm npm@latest -g to update in terminal<br>  handler = &quot;hello.handler&quot;<br><br>  source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256<br><br>  role = aws_iam_role.lambda_exec.arn<br>}<br><br>resource &quot;aws_cloudwatch_log_group&quot; &quot;hello_world&quot; {<br>  name = &quot;/aws/lambda/${aws_lambda_function.hello_world.function_name}&quot;<br><br>  retention_in_days = 30<br>}</pre><p>Create Iam role:An IAM <em>role</em> is an IAM identity that you can create in your account that has specific permissions. An IAM role is similar to an IAM user, in that it is an AWS identity with permission policies that determine what the identity can and cannot do in AWS</p><pre>resource &quot;aws_iam_role&quot; &quot;lambda_exec&quot; {<br>  name = &quot;serverless_lambda&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Action = &quot;sts:AssumeRole&quot;<br>      Effect = &quot;Allow&quot;<br>      Sid    = &quot;&quot;<br>      Principal = {<br>        Service = &quot;lambda.amazonaws.com&quot;<br>      }<br>      }<br>    ]<br>  })<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_policy&quot; {<br>  role       = aws_iam_role.lambda_exec.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole&quot;<br>}</pre><p>Creation of the API gateway</p><p>This is the core resource that acts as the front door to your APIs. It provides HTTP endpoints for clients to access your application or services</p><pre><br>#API Gateway is an AWS managed service that allows you to create and manage HTTP or WebSocket API It supports integration with AWS Lambda functions, <br>#allowing you to implement an HTTP API using Lambda functions to handle and respond to HTTP requests.<br>resource &quot;aws_apigatewayv2_api&quot; &quot;lambda&quot; {<br>  name          = &quot;serverless_lambda_gw&quot;<br>  protocol_type = &quot;HTTP&quot;<br>}<br><br>resource &quot;aws_apigatewayv2_stage&quot; &quot;lambda&quot; {<br>  api_id = aws_apigatewayv2_api.lambda.id<br><br>  name        = &quot;serverless_lambda_stage&quot;<br>  auto_deploy = true<br>#This displays the logs in cloudwatch<br>  access_log_settings {<br>    destination_arn = aws_cloudwatch_log_group.api_gw.arn<br><br>    format = jsonencode({<br>      requestId               = &quot;$context.requestId&quot;<br>      sourceIp                = &quot;$context.identity.sourceIp&quot;<br>      requestTime             = &quot;$context.requestTime&quot;<br>      protocol                = &quot;$context.protocol&quot;<br>      httpMethod              = &quot;$context.httpMethod&quot;<br>      resourcePath            = &quot;$context.resourcePath&quot;<br>      routeKey                = &quot;$context.routeKey&quot;<br>      status                  = &quot;$context.status&quot;<br>      responseLength          = &quot;$context.responseLength&quot;<br>      integrationErrorMessage = &quot;$context.integrationErrorMessage&quot;<br>      }<br>    )<br>  }<br>}</pre><p>To display the logs in the cloudwatch</p><p>Amazon CloudWatch collects and visualizes real-time logs, metrics, and event data in automated dashboards to streamline your infrastructure and application maintenance</p><pre>  access_log_settings {<br>    destination_arn = aws_cloudwatch_log_group.api_gw.arn<br><br>    format = jsonencode({<br>      requestId               = &quot;$context.requestId&quot;<br>      sourceIp                = &quot;$context.identity.sourceIp&quot;<br>      requestTime             = &quot;$context.requestTime&quot;<br>      protocol                = &quot;$context.protocol&quot;<br>      httpMethod              = &quot;$context.httpMethod&quot;<br>      resourcePath            = &quot;$context.resourcePath&quot;<br>      routeKey                = &quot;$context.routeKey&quot;<br>      status                  = &quot;$context.status&quot;<br>      responseLength          = &quot;$context.responseLength&quot;<br>      integrationErrorMessage = &quot;$context.integrationErrorMessage&quot;<br>      }<br>    )<br>  }</pre><p>The AWS::ApiGatewayV2::Integration resource creates an integration for an API.</p><pre>resource &quot;aws_apigatewayv2_integration&quot; &quot;hello_world&quot; {<br>  api_id = aws_apigatewayv2_api.lambda.id<br><br>  integration_uri    = aws_lambda_function.hello_world.invoke_arn<br>  integration_type   = &quot;AWS_PROXY&quot;<br>  integration_method = &quot;POST&quot;<br>}<br><br>resource &quot;aws_apigatewayv2_route&quot; &quot;hello_world&quot; {<br>  api_id = aws_apigatewayv2_api.lambda.id<br><br>  route_key = &quot;GET /hello&quot;<br>  target    = &quot;integrations/${aws_apigatewayv2_integration.hello_world.id}&quot;<br>}<br><br>resource &quot;aws_cloudwatch_log_group&quot; &quot;api_gw&quot; {<br>  name = &quot;/aws/api_gw/${aws_apigatewayv2_api.lambda.name}&quot;<br><br>  retention_in_days = 30<br>}</pre><p>The AWS::Lambda::Permission resource grants an AWS service or another account permission to use a function. You can apply the policy at the function level, or specify a qualifier to restrict access to a single version or alias</p><pre>resource &quot;aws_lambda_permission&quot; &quot;api_gw&quot; {<br>  statement_id  = &quot;AllowExecutionFromAPIGateway&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.hello_world.function_name<br>  principal     = &quot;apigateway.amazonaws.com&quot;<br><br>  source_arn = &quot;${aws_apigatewayv2_api.lambda.execution_arn}/*/*&quot;<br>}</pre><h4>Outputs: Output.tf</h4><p>Output values make information about your infrastructure available on the command line, and can expose information for other Terraform configurations to use. Output values are similar to return values in programming languages.</p><pre># Output value definitions<br>output &quot;lambda_bucket_name&quot; {<br>  description = &quot;Name of the S3 bucket used to store function code.&quot;<br><br>  value = aws_s3_bucket.lambda_bucket.id<br>}<br>#Used to define your Lambda function and related resources.<br>output &quot;function_name&quot; {<br>  description = &quot;Name of the Lambda function.&quot;<br><br>  value = aws_lambda_function.hello_world.function_name<br>}<br><br>#The API Gateway stage will publish your API to a URL managed by AWS<br>output &quot;base_url&quot; {<br>  description = &quot;Base URL for API Gateway stage.&quot;<br><br>  value = aws_apigatewayv2_stage.lambda.invoke_url<br>}<br><br></pre><h4>Provider.tf</h4><p>Providers allow Terraform to interact with cloud providers, SaaS providers, and other APIs.Used to establish connection between VS code terrafrom and Aws account</p><pre>#Used to establish connection between VS code terrafrom and Aws account<br>terraform {<br>    required_version = &quot;~&gt; 1.4.0&quot;<br>        required_providers {<br>            aws = {<br>                source  = &quot;hashicorp/aws&quot;<br>                version = &quot;~&gt; 5.1.0&quot;<br>            }<br>        }<br>}<br>provider &quot;aws&quot; {<br>    region = &quot;eu-west-1&quot;<br>    alias = &quot;NewAccount&quot;<br> assume_role {<br>        role_arn = &quot;&quot; #This is the deploy role in the account you are using to deploy the resources<br> }<br>    default_tags {<br>        tags = var.default_tags<br>    }<br>}</pre><h4>Variables.tf</h4><p>Input variables let you customize aspects of Terraform modules without altering the module’s own source code. This functionality allows you to share modules across different Terraform configurations, making your module composable and reusable</p><pre># Input variable definitions<br><br>variable &quot;aws_region&quot; {<br>  description = &quot;AWS region for all resources.&quot;<br><br>  type    = string<br>  default = &quot;us-east-1&quot;<br>}</pre><h4>Hello.js: Lamdba function</h4><p>Deploy the Node js Function to AWS Lambda. AWS Lambda is a serverless, event-driven compute service that lets you run code for virtually any type of application or backend service without provisioning or managing servers</p><pre>// Lambda function code in Javascript<br>//deploy the NodeJS function to AWS Lambda<br><br>module.exports.handler = async (event) =&gt; {<br>  console.log(&#39;Event: &#39;, event);<br>  let responseMessage = &#39;Hello, World!&#39;;<br>    if (event.queryStringParameters &amp;&amp; event.queryStringParameters[&#39;Name&#39;]) {<br>        responseMessage = &#39;Hello, &#39; + event.queryStringParameters[&#39;Name&#39;] + &#39;!&#39;;<br>      }<br><br>  return {<br>    statusCode: 200,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    },<br>    body: JSON.stringify({<br>      message: responseMessage,<br>    }),<br>  }<br>}</pre><h4>Data.tf</h4><p><em>Data sources</em> allow Terraform to use information defined outside of Terraform, defined by another separate Terraform configuration, or modified by functions.</p><pre>data &quot;archive_file&quot; &quot;lambda_hello_world&quot; {<br>  type = &quot;zip&quot;<br><br>  source_dir  = &quot;${path.module}/hello-world&quot;<br>  output_path = &quot;${path.module}/hello-world.zip&quot;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c44f5d5b4374" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-cloud-journal/aws-lambda-and-api-gateway-in-terraform-c44f5d5b4374">AWS lambda and API gateway in TERRAFORM.</a> was originally published in <a href="https://medium.com/the-cloud-journal">The Cloud Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>