<?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 Dieudonne Akuphe on Medium]]></title>
        <description><![CDATA[Stories by Dieudonne Akuphe on Medium]]></description>
        <link>https://medium.com/@akupheaws?source=rss-1e0d66a765bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lf2mNj63FB75MXLKAom_kA.jpeg</url>
            <title>Stories by Dieudonne Akuphe on Medium</title>
            <link>https://medium.com/@akupheaws?source=rss-1e0d66a765bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:20:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akupheaws/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[Monitoring, Alerting & Incident Response on AWS]]></title>
            <link>https://medium.com/@akupheaws/monitoring-alerting-incident-response-on-aws-c652b5858f2b?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c652b5858f2b</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 13:48:24 GMT</pubDate>
            <atom:updated>2026-12-01T13:48:24.764Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Jenkins to Amazon EKS with Prometheus, Grafana, and a rollback drill</h4><figure><img alt="Jenkins builds and deploys a GitHub change to Kubernetes. Prometheus feeds Grafana with metrics from Jenkins and the live website." src="https://cdn-images-1.medium.com/max/870/1*b8-RoA2I2FnsrfCBaUJz6g.png" /></figure><p>A Jira ticket asks for a new background color. Imagine Jenkins builds the change, Kubernetes accepts the rollout, and the deployment email arrives. Then a visitor opens the website and gets HTTP 503. I want to know which route is affected, what version was serving it, and what evidence will tell me that visitors can use it again.</p><p>The diagram gives me two places to look. Jenkins has the record of what passed, what failed, and what shipped. The deployed site needs a check that uses the same HTTPS path as a visitor. Prometheus collects metrics from both, and Grafana brings their timelines together. I use Amazon Elastic Kubernetes Service (Amazon EKS) for the Kubernetes deployment in this AWS reference design. The incident at the end is a staging exercise with expected signals and evidence to collect. <a href="https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html">Amazon EKS documentation</a></p><h3>Follow the change from Jira to Amazon EKS</h3><p>The Jira issue leads to a GitHub commit. Jenkins checks it out, runs the Maven compile and unit test stages, and evaluates the SonarQube quality gate. Trivy scans the source tree and later scans the container image. A failed test or a blocked gate should leave an identifiable result in the Jenkins build and stop the change before deployment. That leaves an operator with a specific stage and report to inspect when the pipeline fails.</p><p>Maven packages the application, and Jenkins publishes the artifact to Nexus Repository. Jenkins builds the Docker image, scans it with Trivy, and pushes the approved image to a registry. The Kubernetes Deployment then references the image by digest so the release points to the exact image that passed the scan. The diagram also shows a KubeAudit security check and an email after deployment. KubeAudit’s upstream project is archived. <a href="https://kubernetes.io/docs/concepts/containers/images/">Kubernetes image references</a> · <a href="https://github.com/Shopify/kubeaudit">KubeAudit project</a></p><p>I’d publish a deployment record containing the Jira issue, Git commit SHA, Jenkins build URL, image digest, environment, namespace, Kubernetes revision, and deployment time in UTC. The same record can supply a Grafana annotation and a link in the deployment email. If an alert arrives later, the responder can go from the dashboard to the exact build and then verify the revision serving traffic.</p><p>Kubernetes readiness answers whether a Pod can receive traffic according to its configured check. A ready Pod can still return an error on a particular page. The release verification step should therefore exercise a real visitor route and check the response it expects. That same route becomes the starting point for the external monitoring path. <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/">Kubernetes probe behavior</a></p><h3>Collect signals from Jenkins and the running website</h3><p><strong>Jenkins.</strong> Enable the Jenkins Prometheus Metrics plugin. Its default metrics endpoint is /prometheus/, including the trailing slash. Configure a Prometheus scrape job called jenkins and confirm the target appears in Prometheus Targets. Restrict the endpoint to authorized scrapers and use authenticated TLS across network boundaries. Use the exposed build metrics for job outcomes, build duration, and queue pressure where available. If queue wait rises, the build dashboard can help you decide whether to investigate agent capacity or a pipeline step before more releases pile up. <a href="https://plugins.jenkins.io/prometheus/">Jenkins Prometheus Metrics plugin</a></p><p>The Prometheus-generated up{job=&quot;jenkins&quot;} series is about the scrape. A value of 1 means Prometheus collected metrics. A value of 0 points to a problem reaching or reading the configured endpoint. A build can fail while up stays at 1. Confirm the build outcome and failed stage in Jenkins, where the console log and test reports give more context than a single metric. <a href="https://prometheus.io/docs/concepts/jobs_instances/">Prometheus scrape semantics</a></p><p><strong>Website.</strong> Place a Prometheus Blackbox Exporter probe outside the application cluster and point it at the visitor-facing HTTPS route. In Prometheus, give the scrape job the name website-probe, send requests to the exporter’s /probe endpoint, and pass the website URL as the target parameter. Put the original website URL in the instance label so the dashboard identifies which route was tested. Use an HTTP module that verifies TLS and expects a successful response. A stable text match can catch a maintenance page or a login redirect that still returns HTTP 200. <a href="https://prometheus.io/docs/guides/multi-target-exporter/">Prometheus exporter configuration guide</a></p><p>Graph probe_success, probe_duration_seconds, and, when there is an HTTP response, probe_http_status_code. If the exporter scrape succeeds and probe_success is 0, you have a failed website check to investigate. If the exporter scrape itself fails, check the exporter and its path from Prometheus. In a production design, place the alert evaluation and notification path outside the application’s failure domain where practical. An external probe has limited value if the same cluster outage also prevents anyone from receiving its alert.</p><p>For a service with real traffic, I’d add request rate, error rate, latency, and saturation to the website view. Request counts and errors describe the volume and impact. A duration histogram supports a p95 view that shows what slower requests experience. CPU throttling, queue depth, or resource pressure can point to a bottleneck once you know the user-facing symptom. Use bounded labels such as environment, route template, and status class. Keep request IDs and sanitized request paths in logs to control the number of metric time series. <a href="https://sre.google/sre-book/monitoring-distributed-systems/">Google SRE on monitoring signals</a> · <a href="https://prometheus.io/docs/practices/instrumentation/">Prometheus instrumentation practices</a></p><h3>Design dashboards around a responder’s first questions</h3><p>Connect Grafana to Prometheus through its built-in data source. The repeated icons describe two monitoring paths. One Prometheus and Grafana installation can cover both if Prometheus can reach both targets. The website dashboard starts with whether the page loads from the external probe. Directly below it, I’d put the HTTP status, probe time, request errors, and latest deployment marker. The Jenkins dashboard starts with controller scrape health, recent results for the deployment job, and queue or build duration. Both views should use the same environment filter and time range. A release annotation belongs at the deployment time and should link straight to the Jenkins build.</p><p>Read the two timelines together. A failed Maven stage and a healthy website suggest a delivery problem, with the previous version still a candidate for what is serving. A successful deployment followed by website 503s gives the responder a recent change to investigate. A timestamp makes the association visible. Confirm it against the active image, application logs, and routing before naming the cause. <a href="https://grafana.com/docs/grafana/latest/visualizations/dashboards/build-dashboards/annotate-visualizations/">Grafana dashboard annotations</a></p><p>For this investigation, useful application logs carry a UTC timestamp, route template, status, duration, request ID, and release version. Keep credentials and sensitive request data out of them. Start with Jenkins stage output, Kubernetes events, and the logs for the Pods serving the failed route. If a request crosses multiple separately deployed services, distributed traces under a shared trace ID can help find which dependency failed or slowed down. The synthetic check still supplies the timestamp and route for the initial investigation. <a href="https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/implement-observability.html">AWS Well-Architected observability guidance</a></p><h3>Set an availability objective that reflects user experience</h3><p>A service-level indicator, or SLI, measures behavior the user cares about. For this website, I’d count successful eligible GET requests to a named route and divide by all eligible GET requests to that route. In this example, a 2xx response counts as good. Exclude internal health checks and capture errors at the serving edge so an eligible request still counts when a gateway returns a 5xx before it reaches a Pod. The external probe covers a different gap because it can observe DNS and TLS failures before a request reaches the server.</p><p>An example service-level objective, or SLO, is 99.9% success over a rolling 30-day window. With 100,000 eligible requests, the 0.1% error budget permits 100 failures in that window. That is a design example. The real target should reflect what users expect and what the team can support. For a quiet lab, report the probe pass rate alongside completed and expected probe counts. A window with zero eligible requests leaves the request success ratio undefined, and missing probe samples should be visible as a coverage gap. <a href="https://sre.google/workbook/implementing-slos/">Google SRE on implementing SLOs</a></p><p>With enough traffic to measure the request SLI, alert on how quickly errors consume its budget. At a 99.9% target, a 3% error rate is 30 times the budgeted rate. An example fast-burn rule checks whether the rate exceeds 14.4 times the budget in both the preceding hour and the preceding five minutes. The longer window establishes sustained impact and the shorter one confirms it is still happening. Tune the policy against actual traffic and route low-volume failures using the external probe and a threshold appropriate to that route. <a href="https://sre.google/workbook/alerting-on-slos/">Google SRE on error-budget burn alerts</a></p><h3>Make every alert actionable</h3><p>In staging, I’d start with 30-second Prometheus scrapes, a 30-second Grafana evaluation interval, and a two-minute pending period to absorb short interruptions. Create Grafana-managed rules that query Prometheus. Each query below returns a value for the monitored target. Use an instant query and a threshold below 1. Start with one target per path so it’s easy to verify the expected notification and correlate it with the test.</p><ul><li><strong>Website unavailable.</strong> Query probe_success{job=&quot;website-probe&quot;}. Route to the application owner. Check the affected URL from a second client, then inspect the last deployment and the response code from the probe.</li><li><strong>Website probe scrape failed.</strong> Query up{job=&quot;website-probe&quot;}. Route to the monitoring owner. Check exporter health, DNS, network access, and the scrape target configuration.</li><li><strong>Jenkins metrics unreachable.</strong> Query up{job=&quot;jenkins&quot;}. Route to the CI owner. Verify controller reachability and the plugin endpoint, then check whether Prometheus can access it. Individual build failures can go to the change owner through the pipeline.</li></ul><p>Configure Grafana’s No Data and Error handling so missing series and evaluation failures reach the monitoring owner. Use a test email contact point for staging and configure SMTP when using self-hosted Grafana OSS. Include the affected route or target, environment, severity, first diagnostic step, and links to the dashboard and runbook. In production, a sustained user-facing outage should reach a staffed on-call schedule with an escalation path. The deployment email in the diagram records a release event. The alert email tells a named owner where to begin investigating. <a href="https://grafana.com/docs/grafana/latest/alerting/fundamentals/alert-rule-evaluation/nodata-and-error-states/">Grafana No Data and Error handling</a> · <a href="https://grafana.com/docs/grafana/latest/alerting/configure-notifications/manage-contact-points/integrations/configure-email/">Grafana email contact points</a></p><p>Test the rule and the delivery path as one exercise. A contact-point test verifies that the mailbox receives a message. A staged failure verifies that the right metric, rule, pending period, routing policy, and message work together. Record when the rule starts firing and when the message arrives. With a two-minute pending period, the actual alerting delay also includes scrape timing, rule evaluation, and notification delivery. <a href="https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/ops_event_response_process_per_alert.html">AWS Well-Architected guidance on responding to alerts</a></p><h3>Rehearse a failed release in staging</h3><p>Start with healthy probes and a verified working revision. Deploy a staging build that returns HTTP 503 on the monitored page while its readiness endpoint stays healthy. Give the exercise an owner and a rollback decision before deployment. The expected result is a completed Kubernetes rollout and a failed external probe. Keep the fault active through the alert’s pending period so you can validate notification delivery as well.</p><ol><li><strong>Confirm impact.</strong> Acknowledge the alert, open a Jira incident issue, and check the same URL from a second client. Record which route and environment are affected. If an incident spans teams, assign someone to coordinate the response and keep the incident record current while the technical owner investigates. <a href="https://sre.google/sre-book/managing-incidents/">Google SRE on incident roles</a></li><li><strong>Identify what is serving.</strong> Follow the deployment annotation to the Jenkins build. Confirm the current image digest and Kubernetes revision. Inspect Deployment status, Pod events, application logs, and the Service endpoints. Use the first failing probe’s timestamp to narrow the log window. For an HTTP 503, compare what the ingress or gateway returned with what the application logged. If the probe never received an HTTP response, check DNS, TLS, and routing from the probe’s location.</li><li><strong>Mitigate with a known-good revision.</strong> If the new revision caused the regression and the previous image can run against the current configuration and data, roll back. Check the Kubernetes context, namespace, and revision first. The example below uses a staging namespace, a Deployment named website, and a previously verified revision 7. <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rolling-back-a-deployment">Kubernetes Deployment rollbacks</a></li></ol><pre>kubectl -n staging rollout history deployment/website<br>kubectl -n staging rollout undo deployment/website --to-revision=7<br>kubectl -n staging rollout status deployment/website --timeout=120s</pre><p><strong>Verify recovery from the visitor path.</strong> Recheck the same URL and expected content from outside the cluster. Require three successive successful probes for this exercise. Confirm the prior known-good image is serving and the Grafana rule clears. If recovery notifications are enabled, confirm one reaches the same owner. Keep watching request errors when real traffic is available, since one healthy route or location may cover only part of the impact.</p><h3>Capture the evidence and improve the next release</h3><p>Keep one UTC timeline in the incident issue. Record the deployment, the first failed probe, the alert firing, the email arrival, acknowledgement, mitigation, and the first probe in the sustained recovery sequence. Attach the Jenkins build reference, the before-and-after image digests, and the Grafana time range. The interval from the first failing probe to email receipt measures alerting delay. The interval from the first failing probe to sustained recovery describes what the exercise observed from the external check. Record the probe interval alongside it so readers understand the measurement’s resolution.</p><p>Run two follow-up tests. Fail a unit test on a staging branch and verify the Jenkins stage catches it while the website keeps serving the previous image. Then make the staging Jenkins metrics endpoint unreachable from Prometheus for longer than the pending period. Expect a telemetry alert and healthy website probes. Restore endpoint access and verify the telemetry alert resolves. These tests help establish which problems the system can distinguish and where each notification should go.</p><p>Write a blameless follow-up with one or two changes, an owner, and a way to verify each change. In this scenario, I’d add the external URL and expected content to Jenkins’s post-deploy verification, then repeat the staged failure to check that the verification catches it. If the alert reached the wrong person or gave them too little context, update the routing or message and retest delivery. The evidence I’d want to show after the exercise is a failed visitor check, the release record that explained it, and a repeatable check that verified recovery. <a href="https://sre.google/sre-book/postmortem-culture/">Google SRE on blameless postmortems</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c652b5858f2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond CI/CD: Engineering an End-to-End DevSecOps Pipeline on AWS]]></title>
            <link>https://medium.com/@akupheaws/how-securetask-runs-a-devsecops-pipeline-on-aws-81a112c6668b?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/81a112c6668b</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 00:04:57 GMT</pubDate>
            <atom:updated>2026-12-01T12:38:53.210Z</atom:updated>
            <content:encoded><![CDATA[<h4>How SecureTask provisions with Terraform, tracks findings in DefectDojo, and promotes one ECR image digest.</h4><p>A production approval should identify the build the reviewer is approving. SecureTask does that with an Amazon Elastic Container Registry (ECR) image digest. GitHub Actions builds a Docker image once, screens it before publishing, and passes the same content-addressed image reference to staging and production.</p><p><em>This walkthrough was drafted with AI assistance. Its technical details come from the SecureTask repository at </em><a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/commit/a9d7c787da780134098771f38dff12ed1d9ba5a9"><em>commit a9d7c78</em></a><em>.</em></p><h3>A task manager gives staging real behavior to test</h3><p>SecureTask uses a React and TypeScript frontend, an Express API, and PostgreSQL. One container serves the compiled frontend and the API. The deployment smoke test checks readiness, registers a user, creates a project and a task, updates the task’s status, verifies comments, and signs out. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/smoke.py">Read the smoke test</a>.</p><p>On AWS, staging and production have separate public Application Load Balancers, private ECS Fargate services, and RDS PostgreSQL databases. They share a VPC, ECS cluster, and ECR repository in us-east-1. The lab workflow uses HTTP load balancer endpoints, one task per service, single-AZ databases, and one NAT gateway for private subnet egress. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/docs/assets/architecture/SecureTask-AWS-Runtime.png">See the AWS runtime diagram</a>.</p><h4>Follow a request through the VPC</h4><p>A request arrives at the load balancer for the selected environment. That load balancer forwards the request to the application on port 3000. The Fargate task runs in a private subnet without a public IP, and a security group rule allows the application tier to reach PostgreSQL on port 5432. The ECS execution role retrieves the database password from Secrets Manager when the task starts. The PostgreSQL client also verifies the database server’s certificate. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/infra/application/main.tf#L59-L90">Read the task definition</a> · <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/backend/db.ts">See the database connection</a></p><p>Process liveness and database readiness are checked separately. The ECS container check calls /health/live to see if the Node process responds. The load balancer target group asks for /health/ready, which queries PostgreSQL before returning a healthy status. The tasks send logs to a shared CloudWatch log group with a stream prefix for each environment, so a failed readiness check can be investigated against that environment’s application logs. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/backend/app.ts#L23-L27">Read the health endpoints</a> · <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/infra/platform/main.tf#L211-L233">See the target group health check</a></p><figure><img alt="Staging and production load balancers route to private ECS Fargate services and separate RDS PostgreSQL databases." src="https://cdn-images-1.medium.com/max/800/0*bZvr2lm0vnILY3vX.png" /><figcaption>AWS runtime architecture by Dieudonne Akuphe. Created in Lucidchart with AI assistance.</figcaption></figure><h3>Seven scanners at three points in the release</h3><p><strong>Source.</strong> The application build and tests run alongside a scan matrix. Semgrep checks source code, Gitleaks looks for secrets, OSV-Scanner checks dependencies, Checkov checks Terraform, and Hadolint checks the Dockerfile. Reports go to DefectDojo before the policy script runs. Once the required jobs pass, the protected security-review environment pauses for approval to build the image.</p><p><strong>Image.</strong> Docker builds the release image and Trivy scans it. The workflow saves that exact image as an artifact. Once the image policy passes, the publish job loads the artifact and pushes it to ECR. It then resolves the registry digest and emits the image reference for the deployment jobs.</p><p><strong>Staging.</strong> The reusable deployment workflow updates ECS with that digest, waits for the service to stabilize, and runs the smoke test. ZAP then runs a baseline scan against the staging endpoint. A reviewer can inspect staging and the findings before approving production, which receives the same digest. If the rollout or smoke test fails, the deployment script requests a return to the previous task definition.</p><h4>How the digest moves between jobs</h4><p>The build and publish jobs run on separate GitHub Actions runners. The build job exports the scanned image as a compressed artifact named release-image. The publish job loads that archive into Docker and pushes the image under an immutable ECR tag that includes the commit SHA, workflow run ID, and run attempt. It then asks ECR for the digest and emits an image reference of the form repository@sha256:…. The run-specific tag lets you trace how the artifact reached the registry. The digest is the content reference consumed by the deploy jobs. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/.github/workflows/release.yml#L137-L177">Follow the registry handoff</a></p><p>The first deployment also initializes the ECS service. The initialization script checks for an active service and applies the application Terraform root if it needs to create one. The root reads platform outputs such as subnets, target group ARNs, and database endpoints. For image rollouts, the deployment script starts from the current task definition and registers a revision with the selected image. Terraform’s service configuration ignores changes to the task definition, leaving that revision under the release workflow’s control. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/initialize-service.py">See service initialization</a> · <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/infra/application/main.tf#L92-L120">See the ECS service lifecycle</a></p><h4>What the reviewer can verify in staging</h4><p>ECS can report a stable service after rolling back. After waiting for stability, the deployment script checks that the service is using the requested task definition and inspects the rollout state for failures. Then it runs the application smoke test. Those checks let the workflow distinguish a service that is responding from a release that is running the intended revision. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/deploy.py#L50-L100">Read deployment verification and rollback</a></p><p>After the staging checks pass, the review helper verifies that the production environment has a required reviewer. The run summary shows the staging URL and immutable image reference. The reviewer can open that environment, create a project and task, change the status, add a comment, and check the result after reloading the app before deciding whether to approve production. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/release_review.py#L28-L80">See the staging review summary</a></p><p><a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/docs/assets/architecture/SecureTask-Secure-Release.png">Open the watermarked release diagram</a> · <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/.github/workflows/release.yml">Trace the jobs in the release workflow</a></p><h3>How the release keeps its evidence</h3><p>Reporting jobs normalize source, image, and runtime findings and import them into DefectDojo. The dashboard runs on a private EC2 instance. GitHub Actions retrieves its integration credential from Secrets Manager and reaches the API through an AWS Systems Manager port-forwarding session. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/report-via-ssm.py">See the reporting path</a>.</p><p>The policy script fails the gate on High or Critical findings, any Gitleaks finding, and missing or invalid scan evidence. This gives reviewers a place to inspect findings and puts enforcement in the workflow that controls what advances. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/policy.py">Read the policy evaluator</a>.</p><h4>What counts as scan evidence</h4><p>The policy script reads two files for each required scanner. The status file records whether the scanner completed. The normalized report contains a findings list that the evaluator can read consistently across tools. A clean scan has a completion record and a valid, empty findings list. If either file is missing or invalid, the gate records a failure that points to the evidence problem. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/policy.py#L10-L38">Read the report validation</a></p><p>The source matrix uses fail-fast: false, so its jobs can finish independently and upload their reports. The reporting job can still run after a scan failure to collect the available artifacts. The build depends on the test, scan, and reporting jobs, which gives reviewers an audit trail for a release attempt that stops before an image is built. The workflow retains source, image, and runtime scan artifacts for seven days. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/.github/workflows/release.yml#L36-L93">See the source matrix and artifact handling</a></p><h3>Terraform has its own approval path</h3><p>Provisioning starts with a Checkov preflight against the Terraform roots. After it passes, a protected job creates or reuses the encrypted, versioned S3 state bucket. Terraform uses S3 lockfiles for state operations. The workflow scans the resolved platform plan and applies that saved plan after a separate approval. The reviewed cleanup workflow uses GitHub OIDC to assume an existing AWS role and removes the state bucket last. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/docs/assets/architecture/SecureTask-Terraform-Lifecycle.png">See the Terraform lifecycle diagram</a>.</p><h4>How the Terraform roots fit together</h4><p>The bootstrap root owns the S3 state bucket and its versioning, AES-256 server-side encryption, and TLS-only bucket policy. The bootstrap helper can recover its state snapshot on a new GitHub runner after checking the bucket’s ownership. The platform root owns shared resources, including the VPC, load balancers, ECR repository, RDS instances, and DefectDojo host. The application root keeps separate state keys for staging and production, with a reference to the platform outputs. This lets each environment initialize its own service when an image digest is available. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/bootstrap_ci.py">Read state bootstrap</a> · <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/infra/application/main.tf#L49-L59">See the platform state reference</a></p><p>In the provisioning workflow, the plan job writes a binary Terraform plan and renders that same plan as JSON for Checkov. The apply job downloads the saved binary plan after approval, verifies the AWS account, and applies it against the same backend. The source preflight can stop the workflow before a bucket is created. The resolved-plan check can stop it after Terraform has calculated the proposed resource changes. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/.github/workflows/infrastructure.yml#L53-L123">Read the plan and apply jobs</a></p><p>At the reviewed commit, Terraform disables RDS storage encryption and the state bucket’s public-policy block. Both settings violate custom High-severity Checkov rules, so a fresh provisioning run is expected to stop at preflight before the S3 bootstrap job. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/infra/platform/main.tf#L136-L154">RDS configuration</a> · <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/infra/bootstrap/main.tf#L43-L52">S3 configuration</a></p><h3>Run the application locally</h3><p>Start the application and PostgreSQL with docker compose up --build -d. Open the app on localhost port 3000, create a project, and try the task updates the smoke test exercises. The repository includes the local setup steps and links to all three architecture diagrams. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS#architecture">Explore the SecureTask project on GitHub</a>.</p><h3>Read the evidence when a run stops</h3><p><strong>Provisioning stops before AWS changes.</strong> Start with the Checkov preflight artifact. It identifies the Terraform resource and the policy that blocked it. At the revision covered here, the RDS and S3 checks are expected to stop the run before bootstrap. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/.github/workflows/infrastructure.yml#L17-L29">Find the preflight artifact</a></p><p><strong>The release stops before publishing an image.</strong> Open the source or image gate that failed and check the reports from that workflow run. The per-tool status record shows whether the scanner completed, and the findings file identifies the issue that triggered the gate. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/policy.py#L10-L39">See what the gate reports</a></p><p><strong>The image reaches staging.</strong> Open the deployment summary and use its digest to identify the release under review. If the service cannot become ready, check the target health and that environment’s CloudWatch logs. If deployment and runtime checks pass, the staging URL gives the reviewer a chance to exercise the same application paths they saw locally before making the approval decision. <a href="https://github.com/akupheaws/End-to-End-DevSecOps-on-AWS/blob/a9d7c787da780134098771f38dff12ed1d9ba5a9/scripts/release_review.py#L65-L80">See the reviewer checklist</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81a112c6668b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Region Disaster Recovery, High Availability & Business Continuity on Azure]]></title>
            <link>https://medium.com/@akupheaws/multi-region-disaster-recovery-high-availability-business-continuity-on-azure-8c77b99a006c?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c77b99a006c</guid>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 23:20:43 GMT</pubDate>
            <atom:updated>2026-11-30T23:20:43.733Z</atom:updated>
            <content:encoded><![CDATA[<p>During a Black Friday sale, a shopper might still be able to browse the catalog while checkout is unavailable. When a checkout request times out, the shopper faces a second question. Did the original order already go through?</p><p>I built Northline Supply, a simulated desk-hardware storefront, to rehearse those failures in a two-region Azure lab. It uses synthetic inventory and orders. Each checkout response identifies the serving region and API instance, and each confirmed receipt gives me an order ID to check after recovery.</p><figure><img alt="Northline Supply architecture with East US 2 primary and Central US standby, private checkout APIs, and a shared Azure SQL failover listener." src="https://cdn-images-1.medium.com/max/1024/1*WIL9GSL1n8om4AMjvBCf0g.png" /></figure><p><em>Northline Supply’s Azure architecture. East US 2 is the primary region and Central US is the standby. Diagram by Dieudonne Akuphe.</em></p><h3>How a checkout request travels</h3><p>Shoppers use one public HTTPS hostname. Azure Traffic Manager answers the DNS query using priority routing. East US 2 has priority 1 and Central US has priority 2. The browser connects directly to the selected regional Web App. I configured a 30-second DNS TTL and an HTTPS probe at /traffic-ready. DNS caching and existing connections affect how quickly an individual shopper changes regions. <a href="https://learn.microsoft.com/en-us/azure/traffic-manager/traffic-manager-routing-methods">Traffic Manager priority routing</a></p><p>Each region runs a storefront on Azure App Service and a checkout API on a private Virtual Machine Scale Set. The storefront sends checkout requests through outbound VNet integration to a regional internal Standard Load Balancer. The scale set can lose an instance while the load balancer continues to route new connections to healthy instances.</p><p>Both checkout APIs use the same Azure SQL read/write listener. East US 2 starts as the writer and replicates asynchronously to Central US. The storefront serves its catalog locally, so browsing can continue during a writer interruption. Traffic Manager can switch the storefront region automatically, and an operator controls SQL writer promotion separately. <a href="https://learn.microsoft.com/en-us/azure/azure-sql/database/failover-group-configure-sql-db">Azure SQL failover groups</a></p><h3>Set up the lab</h3><h3>1. Organize the Azure subscription and check capacity</h3><p>Use a dedicated lab subscription or a designated lab scope. Create resource groups for East US 2, Central US, shared workload services, and CI. Put the regional VNets and compute in their respective groups. Put Traffic Manager, the private DNS zone, the workload Log Analytics workspace, and Azure Load Testing in the shared group. Keep state storage and deployment identities in the CI group.</p><p>Each region starts with two zone-redundant Linux P1v3 App Service workers and two Standard_D2s_v6 checkout VMs. Set both compute tiers to scale independently from two to four instances. The first deployment needs six Dsv6 vCPUs in East US 2, including the temporary SQL initialization VM, and four in Central US. After that VM is removed, allow eight Dsv6 vCPUs per region for checkout scale-out. Check both family and regional vCPU quotas, Encryption at Host availability, and the separate zone-redundant App Service quota. Validate the exact App Service plan against your subscription before applying. <a href="https://learn.microsoft.com/en-us/azure/virtual-machines/sizes/general-purpose/dsv6-series">Dsv6 specifications</a> · <a href="https://learn.microsoft.com/en-us/azure/app-service/configure-zone-redundancy">App Service zone redundancy</a> · <a href="https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/deploy-preflight">Azure deployment validation</a></p><h3>2. Build the regional storefront and checkout tiers</h3><p>Use non-overlapping VNets such as 10.41.0.0/16 and 10.42.0.0/16. In each VNet, create a delegated App Service integration subnet, a private checkout subnet, and a private endpoint subnet. Put the VM scale set behind a private load balancer on port 8080. Allow that port from the local App Service integration subnet and Azure Load Balancer probes. Use a NAT gateway for VM package downloads and keep the checkout VMs off the public internet.</p><p>Deploy the same Node.js storefront and checkout API to both regions. Give each storefront its own region label and set CHECKOUT_API_ORIGIN to the local private load balancer. Return the region and API instance in checkout responses so an external observer can identify the path. Use these endpoints to check distinct parts of the system.</p><ul><li><strong>/healthz on the API.</strong> The internal load balancer uses this endpoint to remove unhealthy checkout instances.</li><li><strong>/traffic-ready on the storefront.</strong> App Service and Traffic Manager use this endpoint to verify the storefront can reach its local private API.</li><li><strong>/api/status on the storefront.</strong> The checkoutReady field shows whether the API can reach a writable SQL database.</li><li><strong>/api/catalog and </strong><strong>/api/orders.</strong> Serve the catalog locally. Route test order creation and receipt lookup through the regional API to SQL.</li></ul><h3>3. Configure SQL replication and initialize checkout</h3><p>Place the SQL writer in East US 2 and its geo-replica in Central US. Create a failover group with manual writer promotion and put its read/write listener hostname in CHECKOUT_DB_HOST in both APIs. Create a private endpoint for each SQL server. Link both VNets to privatelink.database.windows.net and peer them so either API can reach whichever server is primary. Disable public SQL network access and use Microsoft Entra authentication. <a href="https://learn.microsoft.com/en-us/azure/azure-sql/database/private-endpoint-overview">Azure SQL Private Link</a></p><p>Use a temporary private VM in East US 2 to create the checkout schema and seed test inventory. Give each regional API a managed identity and grant it permission to execute the checkout procedures. Reserve the cart’s inventory and record the order in one SQL transaction. Use the order UUID as a unique key. If the client retries with the same ID and payload after a timeout, return the original receipt. Reject a different payload that reuses the same ID.</p><h3>4. Provision with Terraform and GitHub Actions</h3><p>Separate the CI bootstrap stack from the workload stack. Give the plan identity Reader on the workload groups and the apply identity Contributor on those groups. Give both identities Storage Blob Data Contributor on the private tfstate and tfplans containers so they can lock state and hand off saved plans. To bootstrap from Actions, first create the azure-lab-bootstrap environment and a separate private bootstrap-state container. Give the bootstrap identity blob access to that container. Scope its role assignment delegation to Reader, Contributor, and Storage Blob Data Contributor for service principals. Run the bootstrap plan and apply before provisioning the workload. <a href="https://learn.microsoft.com/en-us/azure/role-based-access-control/delegate-role-assignments-portal">Azure role assignment delegation</a></p><p>Create azure-lab-plan and azure-lab GitHub environments. Restrict deployments to your protected main branch and configure a reviewer for apply. Set AZURE_CLIENT_ID per environment and set the repository variables AZURE_SUBSCRIPTION_ID, AZURE_TENANT_ID, AZURE_STATE_ACCOUNT, and LAB_PREFIX. Use a unique prefix of 5–18 lowercase letters and digits that starts with a letter. The Azure login jobs need id-token: write. Configure the Entra federated credential with issuer https://token.actions.githubusercontent.com, audience api://AzureADTokenExchange, and the exact repository and environment subject for your workflow. <a href="https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-azure">GitHub Actions OIDC for Azure</a></p><p>Set the full RSA public key line as LAB_SSH_PUBLIC_KEY. Use a generated access code for synthetic orders. Store the code in the LAB_WRITE_KEY environment secret and its one-line digest in LAB_WRITE_KEY_SHA256.</p><pre>export LAB_WRITE_KEY=&quot;$(openssl rand -hex 24)&quot;<br>printf &#39;%s&#39; &quot;$LAB_WRITE_KEY&quot; | openssl dgst -sha256 | awk &#39;{print $NF}&#39;</pre><p>For the first run, set bootstrap_sql=true. Review the Terraform plan before approval. The apply job downloads the same saved plan, checks its SHA-256 digest, and applies it. Confirm SQL initialization, deploy Central US first and then East US 2, and place an order via each direct App Service hostname. Run a second plan with bootstrap_sql=false to remove the initialization VM before load testing.</p><h3>5. Bind one HTTPS hostname to both regions</h3><p>Point a subdomain you control, such as shop.example.com, to the Traffic Manager hostname with a CNAME. Publish the App Service domain verification TXT values and bind the same hostname and a valid SNI certificate on both regional Web Apps. Test the certificate and /api/status against each origin using the shared hostname, then test the public DNS path. This catches a missing standby certificate before a failover. <a href="https://learn.microsoft.com/en-us/azure/app-service/web-sites-traffic-manager-custom-domain-name">Traffic Manager custom domain setup</a></p><h3>Recovery runbook</h3><h3>Record a healthy baseline</h3><p>Verify that East US 2 serves the shared hostname, Central US can place a test order directly, and East US 2 is the SQL writer. Run the following from a machine outside either region. Substitute your own hostname and use the access code created during setup. Repeat the order request with the same UUID to test idempotency.</p><pre>SHOP_HOST=shop.example.com<br>ORDER_ID=$(uuidgen | tr &#39;[:upper:]&#39; &#39;[:lower:]&#39;)<br>curl -fsS &quot;https://$SHOP_HOST/api/status&quot;<br>curl -isS &quot;https://$SHOP_HOST/api/orders&quot; \<br>  -H &quot;x-lab-key: $LAB_WRITE_KEY&quot; \<br>  -H &#39;content-type: application/json&#39; \<br>  --data &quot;{\&quot;id\&quot;:\&quot;$ORDER_ID\&quot;,\&quot;sku\&quot;:\&quot;arc-mouse\&quot;,\&quot;quantity\&quot;:1}&quot;</pre><p>Build a short list of acknowledged receipts. Record UTC time, the DNS answer, x-storefront-region, x-api-instance, the response code, and the order ID. If you add load, start at a small volume with Azure Load Testing and record throughput, p95 latency, and both tiers’ instance counts.</p><h3>Run one failure at a time</h3><ol><li><strong>One checkout instance fails.</strong> In the lab scale set’s Instances view, stop one East US 2 instance. Wait for its health probe to fail and confirm new orders stay in East US 2 while the API instance changes. Start the instance and wait for a healthy baseline.</li><li><strong>The primary checkout tier fails.</strong> After verifying the standby, stop the running instances in the East US 2 lab checkout scale set. Confirm the primary storefront’s /traffic-ready fails, observe the DNS change, and record the first confirmed checkout through Central US. Leave the SQL writer running in East US 2 to isolate the routing test. Hold the East US 2 Traffic Manager endpoint disabled before starting its instances again.</li><li><strong>The SQL writer switches.</strong> Keep storefront routing steady to isolate the database test. With both replicas healthy, run a planned failover to the Central US SQL server. Confirm the writer role moved and the API can place an order through the same read/write listener. Look up earlier receipts at /api/orders/&lt;order-id&gt; and reconcile them against the acknowledgment list. <a href="https://learn.microsoft.com/en-us/cli/azure/sql/failover-group#az-sql-failover-group-set-primary">Azure CLI SQL promotion</a></li></ol><pre>az sql failover-group set-primary \<br>  --resource-group &quot;$CENTRAL_RG&quot; \<br>  --server &quot;$CENTRAL_SQL_SERVER&quot; \<br>  --name &quot;$FAILOVER_GROUP&quot;</pre><p>Use your Central US resource group, Central US SQL server name, and failover group name in the command. A planned switch synchronizes replicas first. An unplanned promotion can lose recent acknowledgments because geo-replication is asynchronous. Record missing receipts separately from lookups that failed to return a definitive result.</p><h3>Fail back and decommission</h3><p>Hold the East US 2 Traffic Manager endpoint disabled during a controlled failback. Restore its API instances and verify a test order directly. Check SQL replication, perform a planned switch back to the original East US 2 writer, and test checkout again. Re-enable the East US 2 endpoint and verify both the public DNS path and a new receipt.</p><p>Measure catalog and checkout recovery separately. Start checkout RTO at the fault timestamp and stop it at the first confirmed checkout through the expected recovery path. Assess RPO by comparing the previously acknowledged order IDs with receipts on the recovered writer. Use two minutes for browsing and five minutes for checkout as lab targets, then record the actual results for each drill.</p><p>When the exercise is over, remove the lab’s public CNAME and review a Terraform destroy plan for the workload state. Apply the reviewed plan and verify that the regional and shared groups are empty. In my teardown, a partial apply had left incomplete Terraform outputs. Reading the deployed resources from state let the workflow clean up the workload, and I verified the three workload groups in Azure afterward.</p><p><a href="https://github.com/akupheaws/azure-multi-region-disaster-recovery">Northline Supply project on GitHub</a> · <a href="https://www.linkedin.com/in/akuphe-aws/">Connect with me on LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c77b99a006c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Region Disaster Recovery, High Availability & Business Continuity on AWS]]></title>
            <link>https://medium.com/@akupheaws/multi-region-disaster-recovery-high-availability-business-continuity-on-aws-2ced88ca52d0?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ced88ca52d0</guid>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 23:13:47 GMT</pubDate>
            <atom:updated>2026-11-30T23:13:47.612Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Black Friday storefront on ECS Fargate and Aurora, with deployment and recovery drills in GitHub Actions.</em></p><p>A shopper clicks <strong>Place order</strong>. The request reaches the database, but the connection drops before the receipt comes back. They try again. By then, the store is answering from a different AWS Region. Can the new Region tell whether to create an order or return the receipt for the one it already accepted?</p><p>That’s the problem behind <strong>Northline Supply</strong>, my disaster recovery lab. I designed it to serve shop.akuphecloud.com from application stacks in N. Virginia and Oregon. During a failure, I want to measure when a shopper can browse again and when checkout can take a new order. I also want to look up the orders shoppers already saw confirmed.</p><h3>The architecture</h3><figure><img alt="Northline Supply AWS architecture. Route 53 directs traffic to the N. Virginia storefront or the Oregon standby. Each region runs ECS Fargate services, and Aurora replicates the order database between regions." src="https://cdn-images-1.medium.com/max/1024/1*29X6I1D5n-cd92Sxh0UhmQ.png" /></figure><p><em>Northline Supply reference topology shown with an example hostname. Architecture by Dieudonne Akuphe.</em></p><ul><li><strong>N. Virginia (</strong><strong>us-east-1)</strong> serves the shared hostname at baseline and runs the Aurora PostgreSQL writer.</li><li><strong>Oregon (</strong><strong>us-west-2)</strong> runs the same storefront and checkout services and holds an Aurora Global Database secondary. A Lambda observer there evaluates the conditions for promoting it.</li></ul><p>Route 53 answers DNS for the shared shop address. It checks each regional hostname separately. A regional probe hits /traffic-ready, where the storefront checks that it can reach its local checkout API. That gives Route 53 a signal about the application path. The shop checks writer readiness separately, so I can tell when browsing is available while checkout is still recovering. <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 health checks and failover</a></p><p>Inside each Region, the public load balancer terminates HTTPS using an AWS Certificate Manager certificate. It forwards requests to the storefront on Amazon ECS with Fargate. The storefront calls an internal load balancer for checkout. The two services have tasks across two Availability Zones and can scale independently. This lets the regional load balancers keep using healthy tasks when an individual task fails.</p><p>The checkout APIs connect over TLS to the <strong>Aurora global writer endpoint</strong>. VPC peering gives either Region a private route to the writer. Oregon can therefore take orders while Virginia still owns the database writes. If Aurora promotes Oregon, the writer endpoint follows the new primary and the checkout service reconnects using the same hostname. <a href="https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database-connecting.html">Aurora global writer endpoint</a></p><h3>A retry keeps the original order ID</h3><p>The browser creates a UUID when checkout starts and saves it with the pending cart. If the request times out, the next attempt carries the same ID and items. Serving both Regions under the same HTTPS hostname keeps that browser storage available after the switch.</p><p>PostgreSQL uses the UUID as the order’s primary key. It serializes attempts for that ID, then reserves inventory and records the receipt in one transaction. The first successful request returns HTTP 201. A retry with the same cart returns HTTP 200 and the saved receipt. Reusing the ID with different items returns a conflict.</p><p>This gives me a concrete check after a regional recovery. I can look up the same UUID in the recovered database. During an unplanned promotion, that lookup depends on whether the order replicated to Oregon. The UUID identifies the order. The receipt ledger shows which confirmed orders the recovered store actually has. <a href="https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database-disaster-recovery.html">Aurora planned switchover and unplanned failover</a></p><h3>Runbook</h3><h3>1. Delegate the shop’s DNS</h3><p>I registered akuphecloud.com with Namecheap. Its public nameservers are managed by Vercel, so the delegation goes in Vercel’s DNS dashboard.</p><ol><li>In the AWS sandbox, open <strong>Route 53 → Hosted zones</strong>. Create a public hosted zone for shop.akuphecloud.com. Copy the hosted-zone ID and the four name servers in its NS record.</li><li>In <strong>Vercel → Domains → akuphecloud.com → DNS Records</strong>, check any existing records or project assignment for shop.</li><li>Add one <strong>NS</strong> record for each Route 53 nameserver. Use shop as the <strong>Name</strong> and one of the four AWS nameservers as the <strong>Value</strong>. This delegates the shop and its regional names to Route 53.</li></ol><p>The provisioning job verifies that public DNS returns the nameservers from the selected Route 53 zone. Because shop.akuphecloud.com is the zone apex, the two failover records are <strong>A aliases</strong> to the regional load balancers. The probe URLs are east.shop.akuphecloud.com and west.shop.akuphecloud.com. Terraform creates those records and the DNS validation records for the HTTPS certificates in both Regions. <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingNewSubdomain.html">Route 53 subdomain delegation</a> · <a href="https://vercel.com/docs/domains/managing-dns-records">Vercel DNS records</a> · <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-values-failover-alias.html">Route 53 failover aliases</a></p><h3>2. Create one IAM role by hand</h3><p>The first infrastructure workflow needs AWS permissions to run Terraform. I use the IAM console for that initial identity. Terraform creates the application deployment and game-day roles once the provisioning workflow can sign in.</p><p>In a GitHub repository containing the lab files, run <strong>Prepare AWS IAM setup</strong> from main. Enter the sandbox account ID, Route 53 hosted-zone ID, and shop hostname. The default prefix is northline-aws. The workflow generates four JSON files in the <strong>northline-iam-setup</strong> artifact using the repository’s own OIDC identity.</p><ul><li><strong>workload-boundary.json</strong> goes in <strong>IAM → Policies → Create policy → JSON</strong>. Name it northline-aws-workload-boundary. Terraform applies it to the roles it creates.</li><li><strong>provision-role-trust.json</strong> goes in <strong>IAM → Roles → Create role → Custom trust policy</strong>. Name the role northline-aws-github-infra.</li><li><strong>provision-role-permissions.json</strong> goes on that role under <strong>Permissions → Add permissions → Create inline policy → JSON</strong>.</li><li><strong>AWS_LAB_SETTINGS.json</strong> supplies the value for the GitHub repository variable AWS_LAB_SETTINGS.</li></ul><p>Before creating the role, open <strong>IAM → Identity providers</strong> and add or reuse the OpenID Connect provider with URL https://token.actions.githubusercontent.com and audience sts.amazonaws.com. In the provisioning role’s <strong>Summary → Edit</strong>, set the maximum session duration to <strong>2 hours</strong>. The policy gives Terraform authority to manage the lab services in the two Regions. Role trust is scoped to the repository’s aws-infra environment. <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html">IAM OIDC setup</a> · <a href="https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws">GitHub OIDC for AWS</a></p><p>An immutable GitHub trust subject has this shape. The workflow fills in the repository and owner IDs for the repository where it runs.</p><pre>repo:OWNER@OWNER_ID/REPO@REPO_ID:environment:aws-infra</pre><p>In GitHub <strong>Settings → Environments</strong>, create aws-infra, aws-deploy, and aws-game-day. Allow deployments from main in each environment. Set AWS_LAB_SETTINGS under <strong>Settings → Secrets and variables → Actions → Variables</strong>. The privileged workflows use OIDC to get temporary credentials. They read the lab’s checkout code from AWS Secrets Manager. <a href="https://docs.github.com/en/actions/reference/security/oidc#immutable-subject-claims">GitHub OIDC subject format</a> · <a href="https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments">GitHub deployment environments</a></p><h3>3. Provision and deploy from GitHub Actions</h3><ol><li>Open <strong>Validate AWS lab</strong> and check the application, PostgreSQL, Terraform, and container tests. The container test runs both images with read-only filesystems and exercises a UUID replay.</li><li>Run <strong>Provision AWS lab</strong> with <strong>plan</strong>. The job checks the DNS delegation and Aurora support in both Regions. On its first run, it prepares the encrypted, versioned S3 state bucket and generates the database and synthetic checkout secrets. Review the workload changes in the Actions log.</li><li>Run <strong>Provision AWS lab</strong> again with <strong>apply</strong>. It plans and applies the infrastructure, then publishes non-secret deployment settings to Systems Manager Parameter Store. Review the plan and choose your recording window before creating the capacity. <a href="https://calculator.aws/">AWS Pricing Calculator</a></li><li>Run <strong>Deploy AWS storefront and checkout</strong> with <strong>Initialize or migrate the PostgreSQL schema</strong> selected. The workflow builds both Docker images, scans them with Trivy, and stops if either image has a high or critical finding with a published fix. After the checks pass, OIDC allows the job to publish those images to ECR in both Regions. ECS task definitions reference the published digests. The workflow releases Oregon first, then Virginia.</li><li>Confirm three receipts in the deployment log, one for each regional hostname and one through the shared shop URL. When using the browser, get the synthetic checkout code from northline-aws/checkout-code in Secrets Manager in N. Virginia.</li></ol><p>The scan caught fixable findings in the original images. I updated the Debian packages and kept npm in the build stage. Both rebuilt images passed the release policy and the container test returned the same receipt for a replayed UUID. Keep the <strong>container-scans</strong> artifact when recording the pipeline. It contains each image’s JSON report. <a href="https://trivy.dev/docs/latest/guide/target/container_image/">Trivy container-image scanning</a></p><h3>4. Run the failover drills</h3><p>Open <strong>AWS failover game day</strong> and run each scenario from a baseline where Virginia is the writer and serves the shared hostname. The GitHub runner observes the shop from outside the lab.</p><ul><li><strong>single-task</strong> stops one Virginia checkout task. Look for an ECS replacement and a new receipt from Virginia.</li><li><strong>regional-checkout</strong> makes Virginia’s internal load balancer return HTTP 503. Verify that the shared URL serves from Oregon and that checkout can confirm an order while Aurora still writes in Virginia.</li><li><strong>planned-writer</strong> moves the Aurora writer while both clusters are healthy. The storefront stays in Virginia and checkout reconnects to Oregon through the existing writer hostname.</li><li><strong>full-region</strong> makes the Virginia public listener return HTTP 503 and blocks client access to PostgreSQL in that Region. Look for the Oregon catalog, the ARC promotion, and the first confirmed Oregon order.</li></ul><p>The full-region scenario needs the <strong>Allow the full-region drill to force-promote the synthetic database</strong> option. An observer in Oregon checks that Virginia’s storefront and database paths fail, Oregon’s paths are reachable, and its replica is eligible for promotion. Two qualifying one-minute CloudWatch periods trigger an Amazon Application Recovery Controller Region switch plan. Its Aurora failover step promotes Oregon. The client-side fault can leave Aurora’s storage replication running, which matters when interpreting receipt counts. <a href="https://docs.aws.amazon.com/r53recovery/latest/dg/working-with-rs-triggers.html">ARC alarm triggers</a> · <a href="https://docs.aws.amazon.com/r53recovery/latest/dg/aurora-global-database-block.html">ARC Aurora execution block</a></p><h3>5. Read the evidence and return to baseline</h3><p>I start the timer at fault injection. The browsing measurement ends at the first successful Oregon catalog response. The checkout measurement ends at the first qualifying new Oregon receipt after the workflow observes the Oregon writer. I compare them with separate recovery time objectives.</p><ul><li><strong>Browsing target.</strong> Get a successful response from the Oregon catalog within <strong>120 seconds</strong>.</li><li><strong>Checkout target.</strong> Confirm a new order in Oregon within <strong>300 seconds</strong>.</li><li><strong>Data recovery.</strong> Look up acknowledged UUIDs in the recovered database and capture the ARC execution and writer identity.</li></ul><p>Download the game-day artifact. result.json has the timestamps and observed recovery times. receipt-after.json holds a confirmed order and the replay result. reconciliation.json records recovered, missing, and unknown receipts. I use the acknowledgement timestamps and Aurora’s replication lag to interpret the data loss, if any. A failed lookup stays unverified until it can be resolved. These are the measurements to collect during the live drill.</p><p>The workflow restores the Virginia database path, waits for the clusters to be ready, switches the writer back, and restores the Virginia listener. If a drill is interrupted, let any ARC operation settle and run <strong>restore</strong>. Once the baseline is healthy, choose <strong>load-test</strong> to run Locust with 20 simulated users over three minutes. The Actions artifact contains the HTML and CSV results. Compare checkout success and p95 latency with ECS task counts and CPU. This gives you capacity evidence for the load you sent.</p><h3>6. Tear down the lab</h3><p>Save the evidence and confirm that Virginia is the writer. Run <strong>Provision AWS lab → destroy</strong> and select <strong>Confirm removal of the synthetic lab workload</strong>. Verify the lab’s ECS services, Aurora clusters, load balancers, NAT gateways, and ARC plan are gone. The lab database uses synthetic orders and skips final snapshots.</p><p>If you are finished with the setup, remove the lab’s child-zone delegation and hosted zone, then remove the manually created provisioning role and workload boundary. Review the retained S3 state and Secrets Manager values before deleting them.</p><h3>What counts as a recovery</h3><p>I want to show an operator the first new receipt from the recovery Region and how long it took to earn it. For a shopper who clicked Retry, I want to look up the UUID and give them the original receipt, or hand the operations team a specific order to investigate. Those are the outcomes I would report after a sale outage. The Region badge tells me where the request landed. The receipt and the ledger tell me what happened to the order.</p><h3>Project links</h3><p><a href="https://github.com/akupheaws/Multi-Region-Disaster-Recovery-on-AWS">Northline Supply AWS source code on GitHub</a> · <a href="https://www.linkedin.com/in/akuphe-aws/">Dieudonne Akuphe on LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ced88ca52d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a 3-tier web app on Azure with App Service and Azure SQL]]></title>
            <link>https://medium.com/@akupheaws/deploy-a-3-tier-web-app-on-azure-with-app-service-and-azure-sql-e3c89fbc8175?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3c89fbc8175</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 22:11:43 GMT</pubDate>
            <atom:updated>2026-07-30T22:11:43.501Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-cHlyGxWj1G3QZIMxqF4w.png" /></figure><h3>Building a Three Tier Travel Itinerary Application on Microsoft Azure</h3><h3>1. Introduction</h3><p>Modern travelers often use multiple applications to manage destinations, activities, schedules, and travel details. This creates a fragmented experience and makes trip planning difficult to organize.</p><p>This project demonstrates how a three tier web application can be designed and deployed on Microsoft Azure to provide users with a centralized platform for planning and managing their trips.</p><p>The main objective of the project is to showcase a scalable cloud architecture using Azure App Service, Node.js, and Azure SQL Database.</p><h3>2. Business Challenge</h3><p>A growing travel company wants to build a web application that allows users to manage their travel plans from one platform.</p><p>The application should allow users to:</p><ol><li>Create and manage trips</li><li>Add destinations and activities</li><li>Organize activities by date and time</li><li>View a complete travel itinerary</li><li>Update or remove trip information</li></ol><p>As the platform grows, the company expects an increase in users, application traffic, and stored travel data.</p><p>The company needs a solution that is scalable, secure, reliable, and easy to maintain.</p><h3>3. Project Objectives</h3><p>The main objectives of this project are to:</p><ol><li>Build a structured three tier web application</li><li>Separate the frontend, backend, and database layers</li><li>Deploy the application using managed Azure services</li><li>Provide secure communication between the application components</li><li>Create an architecture that can support future growth</li><li>Demonstrate practical cloud deployment skills</li></ol><h3>4. Solution Architecture</h3><p>The solution follows a three tier architecture consisting of the presentation layer, application layer, and data layer.</p><h3>Presentation Layer</h3><p>The presentation layer provides the user interface that allows users to interact with the application.</p><p>Users can create trips, add activities, view their itineraries, and update travel information through the frontend application.</p><p>The frontend is hosted using Azure App Service.</p><h3>Application Layer</h3><p>The application layer contains the business logic of the system.</p><p>A Node.js backend API receives requests from the frontend, processes application logic, validates data, and communicates with the database.</p><p>The backend API is also hosted using Azure App Service.</p><h3>Data Layer</h3><p>The data layer stores user, trip, and activity information.</p><p>Azure SQL Database is used to provide reliable and persistent data storage.</p><p>The backend API communicates with the database using a secure database connection.</p><h3>Services and Technologies Used 🛠️</h3><p>The application is built using a combination of Microsoft Azure services and modern web development technologies.</p><h3>Azure App Service</h3><p>Azure App Service is used to host the backend API. It provides a managed environment for running the Node.js application without requiring direct server management.</p><h3>Azure Static Web Apps</h3><p>Azure Static Web Apps hosts the frontend application. It provides a reliable platform for deploying the React application and delivering content to users.</p><h3>Azure SQL Database</h3><p>Azure SQL Database stores the application data, including trip details, activities, and other information created by users.</p><h3>React and Tailwind CSS</h3><p>React is used to build the user interface and manage frontend interactions.</p><p>Tailwind CSS is used to style the application and create a clean, responsive design.</p><h3>Node.js and Express</h3><p>Node.js provides the runtime environment for the backend application.</p><p>Express is used to build the API, process requests, manage application routes, and handle the business logic.</p><h3>4.2 Get the Project Code</h3><p>Before deploying the application to Microsoft Azure, you need access to the project source code.</p><p>In this section, you will:</p><ol><li>Access the complete project repository on GitHub</li><li>Create your own copy of the repository</li><li>Download the project files to your local computer</li></ol><p>Once these steps are complete, you will have everything required to begin the deployment process.</p><h3>Step 1: Fork the Repository</h3><p>The first step is to create your own copy of the project repository.</p><p>Forking the repository allows you to make changes, update the code, and manage the project from your own GitHub account without affecting the original repository.</p><p>Open the project repository using the link provided below:</p><pre>&lt;https://github.com/akupheaws/travel-planner-app.git&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDDQ2nSc2kDZ3HDpZAVkWA.png" /></figure><p>On the repository page, select <strong>Fork</strong> in the upper right corner.</p><p>Choose your GitHub account as the destination and complete the process.</p><p>After the repository has been forked successfully, GitHub will create a copy under your account.</p><h3>Step 2: Clone the Repository</h3><p>After creating your own copy of the repository, the next step is to download the project files to your local computer.</p><p>Open the forked repository from your GitHub account.</p><p>Select <strong>Code</strong>, choose <strong>HTTPS</strong>, and copy the repository URL.</p><p>Open a terminal and run the following command:</p><pre>git clone https://github.com/akupheaws/travel-planner-app</pre><p>Replace YOUR_REPOSITORY_URL with the HTTPS URL you copied from GitHub.</p><p>For example:</p><pre>git clone https://github.com/yourusername/travel-planner.git</pre><p>After the repository has been downloaded, navigate into the project directory:</p><pre>cd travel-planner-app</pre><p>You now have a local copy of the project and can begin reviewing, configuring, and deploying the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFk4MdpqWLBMUTq0wA1mtw.png" /></figure><h3>4.2.3 Understand the Project Structure</h3><p>Before moving to the Azure configuration, take a moment to understand how the project files are organized.</p><p>Inside the main project folder, you will find three important directories.</p><p><strong>backend</strong></p><p>This folder contains the Node.js and Express application. It handles API requests, processes application logic, and communicates with the database.</p><p><strong>frontend</strong></p><p>This folder contains the React application. It provides the user interface that allows users to create trips, manage activities, and view their travel itinerary.</p><p><strong>database</strong></p><p>This folder contains the SQL schema required to create the database tables and define how the application data is stored.</p><p>You do not need to make any changes to the project files at this stage. The application settings, database connection details, and deployment configuration will be completed in Microsoft Azure.</p><p>At this point, you have successfully created your own copy of the repository, downloaded the project, and reviewed its structure.</p><p>Next, we will move to:</p><h3>4.3 Create and Configure Azure SQL Database</h3><p>Before deploying the backend application, we need to create a database where the application data will be stored.</p><p>In this section, you will:</p><ol><li>Create an Azure SQL Database</li><li>Configure access to the database server</li><li>Prepare the database connection for the backend application</li></ol><p>Once the configuration is complete, the database will be ready to store trip and activity information.</p><h3>4.3.1 Create the Azure SQL Database</h3><p>We will use Azure SQL Database, a managed relational database service provided by Microsoft Azure.</p><p>Follow these steps:</p><ol><li>Sign in to the <strong>Azure Portal</strong></li><li>Enter <strong>SQL databases</strong> in the search bar</li><li>Select <strong>SQL databases</strong> from the search results</li><li>Select <strong>Create</strong></li></ol><h3>Basic Configuration</h3><p>Complete the following fields:</p><p><strong>Subscription</strong></p><p>Select the Azure subscription you want to use for the project.</p><p><strong>Resource Group</strong></p><p>Select <strong>Create new</strong>.</p><p>Enter the following resource group name:</p><pre>travel-planner-rg</pre><p>Select <strong>OK</strong> to create the resource group.</p><p>This resource group will contain the Azure resources used throughout the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7uZ31zk8ELTG0T9apqkYEA.png" /></figure><h3>Database Configuration</h3><p>Complete the following field:</p><p><strong>Database Name</strong></p><p>Enter the following database name:</p><pre>TravelPlannerDB</pre><h3>Server Configuration</h3><p>Under the <strong>Server</strong> field, select <strong>Create new</strong>.</p><p>Complete the server configuration using the following information:</p><p><strong>Server Name</strong></p><p>Enter a unique server name:</p><pre>travel-planner-sql</pre><p>Azure SQL server names must be globally unique. If this name is unavailable, add a unique number or identifier.</p><p>Example:</p><pre>travel-planner-sql-2026</pre><p><strong>Location</strong></p><p>Select the Azure region closest to your users or application resources.</p><p>For better performance, use the same region for the database and backend application whenever possible.</p><p><strong>Authentication Method</strong></p><p>Select <strong>SQL authentication</strong>.</p><p><strong>Server Administrator Login</strong></p><p>Enter the following administrator username:</p><pre>sqladmin</pre><p><strong>Password</strong></p><p>Create a strong password that meets the Azure password requirements.</p><p>Store the username and password securely because they will be required when configuring the backend database connection.</p><p>Confirm the password and select <strong>OK</strong> to create the SQL server.</p><blockquote><em>Save these credentials. You’ll need them when connecting your backend.</em></blockquote><h3>Compute and Storage Configuration</h3><p>In the <strong>Compute and storage</strong> section, set the <strong>Workload environment</strong> to <strong>Development</strong>.</p><p>The development configuration is suitable for testing and demonstration purposes. Keep the remaining options unchanged unless your project requires a different capacity or performance level.</p><h3>Complete the Database Deployment</h3><p>After confirming all the database settings, select <strong>Review + create</strong>.</p><p>Azure will check the configuration and notify you when validation is complete. Review the selected subscription, resource group, database name, server details, region, and estimated cost.</p><p>Once the information is correct, select <strong>Create</strong> to begin provisioning the Azure SQL Database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3v9qzC1hsUV6HHgZ9jxCA.png" /></figure><p>⏳ Wait for deployment to complete (1–2 minutes).</p><h3>4.3.2 Configure Database Network Access</h3><p>Azure SQL Database does not automatically accept connections from every network. To allow the application and your local computer to communicate with the database, the server network settings must be updated.</p><p>Open the Azure SQL Database resource that you created.</p><p>From the database menu, select <strong>Set server firewall</strong>.</p><p>Under <strong>Public network access</strong>, choose <strong>Selected networks</strong>.</p><p>This option allows you to control which networks and IP addresses can connect to the database server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyEWHX_l5SEboWRMl9TInQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhDCgYQLglbEGrog86QI1g.png" /></figure><p>Click <strong>Save.</strong></p><h3>Step 3: Get Connection Details</h3><p>Now we’ll collect the details needed for the backend.</p><ul><li>Go to your <strong>SQL Database.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2anP91Rgdhi-mLhIzLTgA.png" /></figure><ul><li>Scroll down and click <strong>See</strong> <strong>Connection strings.</strong></li><li>You’ll see something like:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTrSonKrqdS1SIB4S1AR3g.png" /></figure><h3>4.3.3 Collect the Database Connection Details</h3><p>The backend application will need specific information to establish a connection with Azure SQL Database.</p><p>Open the SQL Database resource you created in the Azure Portal.</p><p>From the database overview page, locate the server name, database name, and connection information. These values will be used later when configuring the backend application.</p><p>Keep the following details available:</p><ol><li>Database name</li><li>SQL server name</li><li>Server administrator username</li><li>Server administrator password</li><li>Database connection string</li></ol><p>Store this information securely because it will be required during the backend deployment and configuration process.</p><pre>DB_SERVER=travel-planner-sql.database.windows.net<br>DB_USER=sqladmin<br>DB_PASSWORD=your-password<br>DB_NAME=TravelPlannerDB<br>DB_PORT=1433</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDDQ2nSc2kDZ3HDpZAVkWA.png" /></figure><blockquote><strong><em>Important:</em></strong></blockquote><ul><li>Do not copy the entire connection string.</li><li>Only use the individual values shown above.</li><li>Make sure there is <strong>no </strong><strong>tcp: prefix</strong> in DB_SERVER.</li></ul><h3>4.3.4 Create the Database Tables</h3><p>The Azure SQL Database is now available, but it still needs the tables required by the application.</p><p>The backend will use two main tables:</p><ol><li><strong>Trips</strong></li><li><strong>Activities</strong></li></ol><p>These tables will store trip information and the activities associated with each trip.</p><h3>Open the Query Editor</h3><p>Open your SQL Database resource in the Azure Portal.</p><p>From the database menu, select <strong>Query editor</strong>.</p><p>The Query Editor allows you to run SQL commands directly against the database without installing a separate database management tool.</p><p>Sign in using the SQL administrator username and password created during the server configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9BcYASRZ7Ka__YUN6xoVw.png" /></figure><ul><li><strong>SQL authentication</strong> &gt; Login using:</li><li><strong>Username:</strong> sqladmin</li><li><strong>Password:</strong> the one you created earlier.</li><li>If you receive an error while connecting, just click Allow, and it’ll add your IP address to firewall rules.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtePvXwl9fFVkqqb4Jy3Nw.png" /></figure><h3>Create Tables</h3><ul><li>Click <strong>Create Query.</strong></li><li>Copy and run the following SQL script:</li></ul><pre>-- Trips Table (matches your API)<br>CREATE TABLE Trips (<br>    id INT IDENTITY(1,1) PRIMARY KEY,<br>    destination NVARCHAR(255) NOT NULL,<br>    startDate DATE NOT NULL,<br>    endDate DATE NOT NULL,<br>    createdAt DATETIME DEFAULT GETDATE()<br>);<br><br>-- Activities Table<br>CREATE TABLE Activities (<br>    id INT IDENTITY(1,1) PRIMARY KEY,<br>    tripId INT NOT NULL,<br>    title NVARCHAR(255) NOT NULL,<br>    activityDate DATE NOT NULL,<br>    notes NVARCHAR(MAX),<br>    createdAt DATETIME DEFAULT GETDATE(),<br><br>    FOREIGN KEY (tripId) REFERENCES Trips(id) ON DELETE CASCADE<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1VP70YU7Oe7ffwWpedNzQ.png" /></figure><h3>Verify Tables</h3><p>Run:</p><pre>SELECT * FROM INFORMATION_SCHEMA.TABLES;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vQ8Pz4w9AaYoFfaB4Io6w.png" /></figure><p>You should see both:</p><ul><li>Trips</li><li>Activities</li></ul><h3>Step 5.3.5 Test Your Backend</h3><ul><li>Open your backend API in the browser:</li></ul><pre>YOUR_API_URL/trips</pre><h3>4.4 Deploy the Backend to Azure App Service</h3><p>With the database prepared, the next stage is to publish the backend API and configure it to communicate with Azure SQL Database.</p><p>During this section, you will:</p><ol><li>Create an Azure App Service for the backend</li><li>Add the required application settings</li><li>Configure the database connection</li><li>Deploy the Node.js API</li><li>Confirm that the backend is running successfully</li></ol><p>After completing these steps, the API will be available online and ready to receive requests from the frontend application.</p><h3>4.4.1 Create the Backend Web App</h3><p>The Node.js backend will be hosted using Azure App Service, which provides a managed environment for running web applications and APIs.</p><p>Open the <strong>Azure Portal</strong>.</p><p>Enter <strong>App Services</strong> in the search bar and select it from the results.</p><p>Select <strong>Create</strong>, then choose <strong>Web App</strong>.</p><p>This will open the configuration page where you can define the hosting settings for the backend application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lIfAzGGc6avIqYbpN5O5pA.png" /></figure><h3>Configure the Web App Basics</h3><p>On the <strong>Basics</strong> tab, provide the information required to create the backend hosting environment.</p><p><strong>Subscription</strong></p><p>Choose the Azure subscription being used for this project.</p><p><strong>Resource Group</strong></p><p>Select the resource group created earlier:</p><pre>travel-planner-rg</pre><p><strong>Web App Name</strong></p><p>Enter a name for the backend application:</p><pre>travel-planner-api</pre><p>The Web App name must be unique across Azure. If the name is already in use, include a number or another identifier.</p><p>Example:</p><pre>travel-planner-api-2026</pre><p>The name selected here will become part of the public address used to access the backend API.</p><p><strong>Runtime Stack</strong></p><p>Choose the latest supported <strong>Node.js LTS</strong> version.</p><p>This provides the runtime environment required to execute the Node.js and Express backend application.</p><p><strong>Region</strong></p><p>Select the same Azure region used for the SQL Database.</p><p>Placing the backend and database in the same region can help improve communication speed and reduce unnecessary network latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*670xqOhosI8k1qlesmNRog.png" /></figure><blockquote><em>Using the same region improves performance and avoids latency issues.</em></blockquote><ul><li><strong>App Service Plan:</strong> Select free tier <strong>F1.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMj2KffdB9WApTdhXa_rGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3DQeUJTFE0yxm-G0CkRSQ.png" /></figure><h3>Review and Create</h3><ul><li>Click <strong>Review + Create.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EHUivwcYdIAABMxvMx4pQ.png" /></figure><ul><li>Click <strong>Create.</strong></li></ul><p>⏳ Wait for deployment to complete.</p><h3>4.4.2 Configure the Backend Environment Variables</h3><p>The backend application needs configuration values that allow it to connect securely to Azure SQL Database.</p><p>Open the Web App created for the backend API.</p><p>From the Web App menu, go to <strong>Settings</strong> and select <strong>Environment variables</strong>.</p><p>Under <strong>App settings</strong>, select <strong>Add</strong> to create a new environment variable.</p><p>Enter each required setting separately using the variable name and its corresponding value.</p><p>These settings will provide the backend with the database server name, database name, administrator credentials, and any other configuration values required by the application.</p><pre>DB_SERVER=travel-planner-sql.database.windows.net<br>DB_USER=sqladmin<br>DB_PASSWORD=your-password<br>DB_NAME=TravelPlannerDB<br>DB_PORT=1433<br>PORT=5000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIIMnovul7g91-zVlT-fUQ.png" /></figure><ul><li>Click <strong>Apply → Confirm.</strong></li></ul><p><strong>Important:</strong></p><ul><li>Use the exact values from the previous step.</li><li>Do not add tcp: in the server name.</li><li>Keep values consistent.</li></ul><h3>4.4.3 Deploy the Backend from GitHub</h3><p>The next step is to connect the Azure Web App to your GitHub repository so that Azure can build and publish the backend code.</p><p>Open the backend Web App in the Azure Portal.</p><p>From the resource menu, select <strong>Deployment</strong>, then open <strong>Deployment Center</strong>.</p><p>Under the source configuration, choose <strong>GitHub</strong>.</p><p>Select <strong>Authorize</strong> and sign in to the GitHub account that contains your forked project repository.</p><p>After the connection is approved, complete the deployment settings.</p><p><strong>Repository</strong></p><p>Choose the forked repository that contains the application code.</p><p><strong>Branch</strong></p><p>Select:</p><pre>main</pre><p><strong>Workflow Option</strong></p><p>Choose <strong>Add a workflow</strong>.</p><p>Azure will create a GitHub Actions workflow that builds and deploys the backend whenever changes are pushed to the selected branch.</p><p>Review the settings and save the configuration to begin the deployment process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qECzpqR_6jqFYsniyqZtxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeRanx2loYnGkfknAG3aLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nqd2A37UCtiCQ7gEoBf6Vw.png" /></figure><ul><li>Authentication type: <strong>User-assigned identity.</strong></li><li>Click <strong>Save.</strong></li></ul><blockquote><strong><em>What Happens Next?</em></strong></blockquote><ul><li>Azure will automatically:</li><li>Pull your code,</li><li>Install dependencies,</li><li>Deploy your backend.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRLshixSCkXyvRxm0STnkw.png" /></figure><h3>4.4.4 Resolve Backend Deployment Folder Issues</h3><p>In some situations, the first deployment may not complete successfully because Azure attempts to build the application from the root of the repository instead of the backend directory.</p><p>When this happens, the deployment logs may display an error indicating that Azure cannot locate the backend application files, the package.json file, or the required build configuration.</p><p>An example error may look similar to the following:</p><pre>Could not read package.json</pre><p>This issue occurs because the repository contains multiple folders, while the backend application is located inside the backend directory.</p><p>To resolve the problem, the GitHub Actions workflow must be updated so that the build and deployment process runs from the correct folder</p><p>This happens because Azure tries to run the application from the root folder, while our backend code is inside the backend/ folder.</p><h3>Update GitHub Actions Workflow</h3><p>We need to tell Azure to run the app from the correct folder.</p><ul><li>Go to your GitHub repository.</li><li>Click on the <strong>Actions</strong> tab.</li><li>Open the latest failed workflow.</li><li>Click <strong>Edit workflow</strong> (top right).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWTq4zJVjTRn9daLgzPGZQ.png" /></figure><ul><li>Replace it with:</li></ul><pre># Docs for the Azure Web Apps Deploy action: &lt;https://github.com/Azure/webapps-deploy&gt;<br><br>name: Build and deploy Node.js app to Azure Web App - travel-planner-api<br><br>on:<br>  push:<br>    branches:<br>      - main<br>  workflow_dispatch:<br><br>jobs:<br>  build-and-deploy:<br>    runs-on: ubuntu-latest<br><br>    permissions:<br>      id-token: write<br>      contents: read<br><br>    steps:<br>      # Checkout code<br>      - uses: actions/checkout@v4<br><br>      # Setup Node.js<br>      - name: Set up Node.js<br>        uses: actions/setup-node@v3<br>        with:<br>          node-version: &#39;18.x&#39;<br><br>      # Install dependencies (inside backend)<br>      - name: Install dependencies<br>        run: |<br>          cd backend<br>          npm install<br><br>      # Optional build step<br>      - name: Build app (if present)<br>        run: |<br>          cd backend<br>          npm run build --if-present<br><br>      # Login to Azure<br>      - name: Login to Azure<br>        uses: azure/login@v2<br>        with:<br>          client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_494EF3608DDF459F83B62772C92F5D8D }}<br>          tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_E2649882564542B0A8EFDB6CE121D946 }}<br>          subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_B241A06BD6764D5BAA65C3E85341AAB7 }}<br><br>      # Deploy ONLY backend folder<br>      - name: Deploy to Azure Web App<br>        uses: azure/webapps-deploy@v3<br>        with:<br>          app-name: &#39;travel-planner-api&#39;<br>          slot-name: &#39;Production&#39;<br>          package: backend</pre><h3>Save and Redeploy</h3><ul><li>Click <strong>Commit changes.</strong></li><li>Go back to the <strong>Actions</strong> tab.</li><li>A new deployment will automatically start.</li></ul><blockquote><em>⏳ Wait for it to complete.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4NhjETSgbop_8_46NQrdQ.png" /></figure><h4>Why This Configuration Is Required</h4><p>Azure normally looks for the application files in the main repository directory.</p><p>In this project, the Node.js API is stored inside the backend folder. Without additional configuration, the deployment process may search the wrong location and fail to find important files such as package.json.</p><p>Updating the workflow directs GitHub Actions to build and deploy the application from the correct directory.</p><h4>Expected Result</h4><p>After the workflow has been corrected:</p><ol><li>The GitHub Actions deployment should complete successfully</li><li>Azure App Service should start the backend application without folder related errors</li><li>The API should become accessible through the Web App address</li><li>Future changes pushed to the selected branch should automatically trigger a new deployment</li></ol><blockquote><em>💡 </em><strong><em>Note:</em></strong><em> If your deployment worked without this step, you can skip it.</em></blockquote><h3>Verify Deployment</h3><ul><li>Go to your Web App URL:</li></ul><pre>&lt;https://your-app-name.azurewebsites.net&gt;</pre><ul><li>You should see a basic response or an API route working (Ignore the error for now, it’ll be handled in later parts as we progress).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mEWU5p111eMEZbtFtjSow.png" /></figure><p>Your backend is now live and connected to Azure SQL.</p><p>Next, we’ll deploy the frontend, connect it to this backend API, and complete the full application.</p><h3>4.5 Deploy the Frontend with Azure Static Web Apps</h3><p>Now that the backend API is running successfully, the next stage is to publish the frontend and establish communication between both application layers.</p><p>In this section, you will:</p><ol><li>Prepare the React application for deployment</li><li>Configure the backend API address</li><li>Publish the frontend using Azure Static Web Apps</li><li>Verify that the complete application is working online</li></ol><p>Once this section is complete, users will be able to access the application through a public web address.</p><h3>4.5.1 Prepare the Frontend Application</h3><p>Before creating the Azure Static Web App, confirm that the frontend is configured to send requests to the deployed backend API.</p><p>Open the frontend folder in your code editor and locate the .env file.</p><p>Replace the existing API address with the public URL of your Azure App Service backend.</p><p>For example:</p><pre>VITE_API_URL=https://your-backend-app.azurewebsites.net</pre><p>Replace your-backend-app with the actual name assigned to your backend Web App.</p><p>Do not add a forward slash at the end of the URL unless the application configuration requires one.</p><p>Save the file after updating the value.</p><p>This setting ensures that requests from the React application are directed to the live backend API instead of a local development server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YF0Mc9Nc0cgTUsDULyLEkQ.png" /></figure><ul><li>With your deployed backend URL:</li></ul><pre>&lt;https://travel-planner-api-eugnhrbxejf7c6fa.centralus-01.azurewebsites.net&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*km8gd_JmLUYsBXgpij9uTQ.png" /></figure><blockquote>💡 This ensures your frontend talks to your live backend.</blockquote><h3>4.5.2 Create the Azure Static Web App</h3><p>The frontend will be hosted using Azure Static Web Apps, which provides managed hosting for React applications.</p><p>Open the <strong>Azure Portal</strong>.</p><p>Enter <strong>Static Web Apps</strong> in the search bar and select it from the results.</p><p>Select <strong>Create</strong> to begin setting up the frontend hosting service.</p><h3>Basic Configuration</h3><p>Complete the required fields using the following information:</p><p><strong>Subscription</strong></p><p>Select the Azure subscription being used for the project.</p><p><strong>Resource Group</strong></p><p>Choose the resource group created earlier:</p><pre>travel-planner-rg</pre><p><strong>Static Web App Name</strong></p><p>Enter a name for the frontend resource:</p><pre>travel-planner-frontend</pre><p>The name must be unique. Add a number or another identifier if the name is unavailable.</p><p>Example:</p><pre>travel-planner-frontend-2026</pre><p><strong>Region</strong></p><p>Choose the Azure region closest to your users or project resources.</p><p><strong>Plan Type</strong></p><p>Select the <strong>Free</strong> plan.</p><p>The Free plan provides the features required to host and test the frontend application for this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bbbF4JNOPLrveL_QQpKkA.png" /></figure><h3>Deployment Configuration</h3><p>Under <strong>Deployment details</strong>, choose <strong>GitHub</strong> as the source.</p><p>Select <strong>Sign in with GitHub</strong>, then authorize Azure to access your GitHub account.</p><p>After the connection is complete, provide the following information:</p><p><strong>Repository</strong></p><p>Select the repository that contains the frontend application.</p><p><strong>Branch</strong></p><p>Choose:</p><pre>main</pre><h3>Build Configuration</h3><p>Azure needs to know where the React application is located and where the completed build files will be generated.</p><p>Enter the following values:</p><p><strong>App Location</strong></p><pre>./frontend</pre><p>This tells Azure that the frontend source code is stored inside the frontend folder.</p><p><strong>Output Location</strong></p><pre>dist</pre><p>The dist folder contains the production files created when the React application is built.</p><p>Review the configuration carefully before continuing to the deployment stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrIb-DtwjbFcpfNPYuFpZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZt6vBTXyjezlHFXUQOaKA.png" /></figure><ul><li>Leave other settings as the default.</li><li>Click <strong>Review + Create.</strong></li><li>Click <strong>Create.</strong></li></ul><blockquote>⏳ Azure will create the Static Web App, set up GitHub Actions, and build and deploy your frontend.</blockquote><h3>4.5.3 Monitor the Frontend Deployment</h3><p>After creating the Azure Static Web App, Azure automatically adds a GitHub Actions workflow to the selected repository.</p><p>Open your GitHub repository and select the <strong>Actions</strong> tab.</p><p>Locate the workflow created for the Azure Static Web App.</p><p>Open the most recent workflow run to monitor the deployment process.</p><p>The workflow will install the frontend dependencies, build the React application, and publish the generated files to Azure.</p><p>Wait until every stage displays a successful status.</p><p>Once the workflow is complete, return to the Static Web App resource in the Azure Portal and open the application URL to confirm that the frontend is available online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SuJR0pERMa2MhPfsdnCYVw.png" /></figure><blockquote>⏳ This may take a few minutes.</blockquote><h3>4.5.4 Access the Published Frontend</h3><p>After the GitHub Actions workflow finishes successfully, the frontend application will be available through the public address assigned by Azure.</p><p>Open the Static Web App resource in the Azure Portal.</p><p>From the overview page, locate the application URL and copy it.</p><p>Paste the address into your web browser to open the deployed frontend.</p><p>Confirm that the application loads correctly and that the main interface is visible.</p><p>At this stage, the frontend is publicly accessible and ready to communicate with the deployed backend API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBixh2e61rQIt5X-qplm0g.png" /></figure><blockquote>🎉 Your frontend should now be live!</blockquote><h3>4.5.5 Verify Communication Between the Frontend and Backend</h3><p>The final step is to confirm that the deployed frontend can successfully send requests to the backend API.</p><p>Open the public URL assigned to the Azure Static Web App.</p><p>Use the application to complete the following actions:</p><ol><li>Create a new trip</li><li>Confirm that the trip appears in the trip list</li><li>Open the trip and add one or more activities</li><li>Verify that the activities are displayed correctly</li><li>Delete an activity and confirm that it is removed</li><li>Delete a trip and confirm that it no longer appears</li></ol><p>If each action works successfully, the frontend, backend, and database are communicating correctly.</p><p>The complete application is now deployed and available online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6-dQOcgPAj9qjV-lv5SJQ.png" /></figure><h3>Conclusion</h3><p>This project demonstrates the successful design, configuration, and deployment of a complete three tier cloud application on Microsoft Azure. Rather than treating the solution as a basic web deployment, the project applies architectural principles commonly used in modern enterprise and software as a service environments. The presentation layer, application layer, and data layer were separated into independent components, allowing each part of the system to be developed, deployed, maintained, and scaled according to its individual requirements.</p><p>The React frontend was deployed through Azure Static Web Apps, while the Node.js and Express backend API was hosted using Azure App Service. Azure SQL Database provided a managed relational data layer for storing and retrieving trip and activity records. Secure communication between the application layers was established through environment based configuration, controlled network access, database authentication, API routing, and cross origin access policies.</p><p>The project also incorporated automated deployment workflows through GitHub Actions. This introduced continuous integration and continuous deployment practices, enabling application changes to be built and published through a repeatable process. Deployment challenges involving repository structure, environment variables, database connectivity, firewall permissions, application routing, and frontend to backend communication were identified and resolved through systematic troubleshooting.</p><p>From an engineering perspective, this implementation demonstrates practical competence in cloud architecture, full stack application deployment, managed database integration, configuration management, API connectivity, source control, and deployment automation. It also highlights the ability to translate a business requirement into a functional technical solution using appropriate Azure services.</p><p>The completed application provides more than a working travel planning platform. It represents a reusable architectural foundation that can support future capabilities such as identity management, role based access control, secret management, centralized monitoring, automated testing, private networking, disaster recovery, and independent service scaling.</p><p>Overall, this project reflects the end to end delivery of a professionally structured cloud solution. It demonstrates an understanding of how modern applications are designed, integrated, deployed, validated, and prepared for continued growth within a cloud environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c89fbc8175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Enterprise Cloud Security Governance Platform with Policy-as-Code (OPA, Terraform, AWS)]]></title>
            <link>https://medium.com/@akupheaws/building-an-enterprise-cloud-security-governance-platform-with-policy-as-code-opa-terraform-aws-446bff75179b?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/446bff75179b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 02:33:23 GMT</pubDate>
            <atom:updated>2026-07-07T14:21:20.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wnwp5SsiueHSMOhRyQo_A.jpeg" /></figure><p>The core idea is to shift security left without slowing teams down. I use OPA/Rego to encode controls as testable policies and Conftest to evaluate the Terraform plan (the rendered intent) before anything is applied. If a change would introduce risk such as a public <a href="https://www.cloudforgeconsult.com/">S3 bucket</a>, disabled versioning, or missing governance tags the pipeline fails early, with clear messages developers can act on. Because this governance is code, policies are versioned, peer-reviewed, and easy to evolve as standards change.</p><p>In runtime, the platform relies on AWS-native detective controls for continuous compliance. It initializes AWS Config correctly with a service-linked role, configuration recorder, and a delivery channel that writes securely to a dedicated, encrypted S3 bucket. Managed rules and a CIS-aligned Conformance Pack provide comprehensive coverage and centralized reporting, while Security Hub aggregates findings across services. I subscribe the account to the region-qualified CIS AWS Foundations Benchmark (v1.4.0 by default) for standardized posture visibility.</p><p><a href="https://www.cloudforgeconsult.com/">Infrastructure</a> is delivered through modular Terraform to support multi-account scale and clear ownership boundaries. The VPC module provisions a highly available network across four Availability Zones with eight public and eight private subnets. The S3 module creates five hardened buckets with public access blocks and versioning enabled by default. The EC2 module deploys four instances distributed across subnets. Governance tags such as a required CostCenter — are enforced consistently across resources to aid FinOps, chargeback, and audit traceability. Optional Service Control Policies can be enabled when the account participates in AWS Organizations to provide preventative, organization-wide guardrails.</p><p>The <a href="https://www.cloudforgeconsult.com/">CI/CD workflow</a> is split into multiple jobs for clarity and control: OPA unit tests validate policy logic, Terraform generates a plan and exports it as JSON, Conftest evaluates the plan against the policy set, and an apply job deploys only the previously validated plan on the main branch. This ensures the artifact reviewed and approved is exactly what gets deployed, preventing drift between policy evaluation and execution. Remote Terraform state lives in S3, and the design supports DynamoDB-based state locking for team concurrency.</p><p>For the business, the outcomes are tangible. Risk is reduced because non-compliant changes never reach production. Audit readiness improves thanks to continuous signals from Config, Conformance Packs, and Security Hub. Developer velocity is preserved because guardrails are automated and predictable, meeting teams where they already work. Governance scales through modules and reusable policies, so adding accounts or expanding controls becomes routine rather than disruptive.</p><p>The repository includes Terraform modules for networking, storage, and compute; governance resources for AWS Config, Conformance Packs, and Security Hub; a multi-job GitHub Actions workflow that gates deployments on policy compliance; OPA/Rego policies with unit tests; and plan-aware rules that evaluate tfplan.json during CI. Documentation covers setup, troubleshooting, and cleanup, with optional SCP templates that can be toggled on in organizational contexts.</p><p>Building this taught a few important lessons. Policy-as-Code beats manual checklists because policies are executable, tested, and enforced uniformly. AWS Config prerequisites matter a recorder and properly permissioned delivery channel are essential. Region-qualified ARNs and supported versions are critical for services like Security Hub. Above all, gating on the plan artifact ensures the thing you validated is the thing you deploy, which is where many pipelines fall short.</p><p>Next, I’m adding OIDC-based authentication from GitHub to AWS to eliminate long-lived access keys, authoring SSM and EventBridge runbooks for auto-remediation of high-confidence findings, and enabling organization-wide aggregation for Security Hub and Config to centralize visibility. I’m also expanding controls to include GuardDuty findings, organization-level CloudTrail, and data-perimeter guardrails.</p><p>Open-source repository: <a href="https://github.com/akupheaws/Enterprise-Cloud-Security-Governance-with-Policy-as-Code">https://github.com/akupheaws/Enterprise-Cloud-Security-Governance-with-Policy-as-Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=446bff75179b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Cloud Weather Tracker App with Disaster Recovery using Terraform]]></title>
            <link>https://medium.com/@akupheaws/multi-cloud-weather-tracker-app-with-disaster-recovery-using-terraform-496ce5f3dec0?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/496ce5f3dec0</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 00:11:07 GMT</pubDate>
            <atom:updated>2025-08-18T00:11:07.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PR0Fc6kbbYdKfvyFEVzDFw.png" /></figure><p>This project involves deploying a weather tracker application across <strong>AWS and Azure</strong>, incorporating <strong>disaster recovery</strong> capabilities. The app’s front-end (HTML, CSS, JS) is hosted statically on <strong>AWS S3</strong> (with CloudFront for CDN) and Azure Blob Storage.</p><p>The entire infrastructure is managed using Terraform, automating deployments on both cloud platforms.</p><p>This project focuses on building a highly available and resilient weather application by leveraging a multi-cloud deployment strategy. The key tasks include hosting the application on both AWS S3 and Azure Blob Storage to ensure redundancy and scalability. A custom domain will be registered through Namecheap and configured for DNS management, while disaster recovery will be achieved using Route 53 DNS failover to seamlessly route traffic between AWS and Azure endpoints in case of outages. To streamline the entire setup, Terraform will be used to automate infrastructure provisioning and configuration, ensuring consistency, repeatability, and efficient resource management.</p><h3>Steps to be performed</h3><p>1. Prerequisites (Install Terraform, Configure AWS, Azure CLI)</p><p>2. Define AWS Resources on Terraform</p><p>3. Define Azure Resources using Terraform</p><p>4. Implement Disaster Recovery with Route 53 DNS Failover</p><h3>Services Used 🛠</h3><ul><li><strong>AWS S3: </strong>Host the weather app statically. [<strong>Hosting</strong>]</li><li><strong>AWS CloudFront</strong>: Distribute content globally. [<strong>CDN</strong>]</li><li><strong>Route 53: </strong>Automate failover between AWS and Azure functions. [<strong>DNS Failover]</strong></li><li><strong>Terraform: </strong>Automate multi-cloud infrastructure provisioning. <strong>[Infrastructure as Code]</strong></li></ul><h3>5.2 Prerequisites</h3><p>STEPS TO BE PERFORMED:</p><p>1. Install Terraform</p><p>2. Setup Azure and AWS Accounts</p><p>3. Configure Access for Terraform</p><p>4. Create a Terraform Project Structure</p><p>5. Secure Sensitive Information</p><p>6. Initialize Terraform</p><p>7. Validate and Plan the Setup</p><h3>1. Install Terraform</h3><p>Terraform is an open-source Infrastructure as Code (IaC) tool that simplifies cloud infrastructure provisioning. Follow these steps to install it on your system:</p><p><strong>1. Download Terraform:</strong></p><ul><li>Visit the [Terraform Downloads page](https://www.terraform.io/downloads) and select your operating system (Windows, macOS, or Linux).</li></ul><p><strong>2. Install Terraform:</strong></p><ul><li><strong>Windows</strong>: Extract the ZIP file and add the executable to your `PATH`.</li><li><strong>macOS</strong>: Use Homebrew:</li></ul><pre>brew install terraform</pre><ul><li><strong>Linux</strong>: Extract the binary and move it to `<strong><em>/usr/local/bin`.</em></strong></li></ul><p>3. Verify Installation:</p><ul><li>Open a terminal and <strong>run</strong>:</li></ul><pre>terraform --version</pre><ul><li>Ensure the version number is displayed correctly.</li></ul><h3>2. Setup Azure and AWS Accounts</h3><p>You need accounts on Azure and AWS to deploy resources. If you don’t have them yet, create free-tier accounts for both platforms:</p><ul><li><strong>Azure:</strong><a href="https://azure.microsoft.com/free/"> Sign up for a free Azure accoun</a>t, which includes $200 in credits for 30 days.</li><li><strong>AWS: </strong><a href="https://aws.amazon.com/free/">Sign up for AWS Free Tier</a>, which includes free services like EC2 and S3 for a year.</li></ul><h3>3. Configure Access for Terraform</h3><p><strong>Azure</strong>:</p><p>1. Install <strong>Azure CLI:</strong></p><p>- [Azure CLI Installation](https://learn.microsoft.com/cli/azure/install-azure-cli).</p><p>- Follow the instructions for your operating system (Windows, macOS, or Linux).</p><p>2. <strong>Log in:</strong></p><ul><li>In your terminal type the following command</li></ul><pre>az login</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJSBEV7ERiF6k231xtgfeg.png" /></figure><ul><li>This opens a browser for authentication. After login, retrieve your subscription details:</li></ul><pre>az account show</pre><p>3. <strong>Create a Service Principal:</strong></p><ul><li>Register an application in Azure Active Directory:</li></ul><pre>az ad sp create-for-rbac --role=&quot;Contributor&quot; --scopes=&quot;/subscriptions/&lt;subscription-id&gt;&quot;</pre><ul><li>Change the `<strong>&lt;subscription-id&gt;</strong>` to the one you received after performing the last terminal command.</li><li>Note the `<strong>appId</strong>` (Client ID), `<strong>password</strong>` (Client Secret), and `<strong>tenant</strong>` (Tenant ID).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wv-gbgJL5wgCXRPdULZ90w.png" /></figure><p><strong>AWS</strong>:</p><p><strong>1. Install AWS CLI: </strong><a href="https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html">AWS CLI Installation</a></p><p><strong>2. Configure AWS CLI:</strong></p><ul><li>In the terminal type the command given below</li></ul><pre>aws configureProvide your Access Key ID, Secret Access Key, and default region.</pre><p>Provide your<strong> Access Key ID, Secret Access Key, </strong>and<strong> default region.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s0N7T3wyta6hHj9QPfp7EQ.png" /></figure><h3>4. Create a Terraform Project Structure</h3><ol><li>Create a directory for your Terraform files:</li></ol><pre>mkdir multi-cloud-weather-tracker<br>cd multi-cloud-weather-tracker</pre><p>2. Create the following files:</p><ul><li><strong><em>`main.tf`:</em></strong> To define providers and resources.</li><li><strong><em>`variables.tf`:</em></strong> To declare input variables.</li><li><strong><em>`aws_credentials.tfvars`</em></strong>: To securely store AWS credentials.</li><li>`<strong><em>azure_credentials.tfvars`</em></strong>: To securely store Azure credentials.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmT08NgFEUZiJowD4OHmJQ.png" /></figure><h4>Sample File Structure:</h4><ul><li><strong>variables.tf :</strong></li></ul><pre># AWS credentials<br>variable &quot;aws_access_key&quot; {}<br>variable &quot;aws_secret_key&quot; {}<br><br># Azure credentials<br>variable &quot;azure_client_id&quot; {}<br>variable &quot;azure_client_secret&quot; {}<br>variable &quot;azure_subscription_id&quot; {}<br>variable &quot;azure_tenant_id&quot; {}</pre><ul><li><strong>main.tf:</strong></li></ul><pre># AWS provider<br>provider &quot;aws&quot; {<br>  access_key = var.aws_access_key<br>  secret_key = var.aws_secret_key<br>  region     = &quot;us-east-1&quot;<br>}<br><br># Azure provider<br>provider &quot;azurerm&quot; {<br>  client_id       = var.azure_client_id<br>  client_secret   = var.azure_client_secret<br>  subscription_id = var.azure_subscription_id<br>  tenant_id       = var.azure_tenant_id<br>}</pre><ul><li><strong>aws_credentials.tfvars:</strong></li></ul><pre>aws_access_key = &quot;your-aws-access-key&quot;<br>aws_secret_key = &quot;your-aws-secret-key&quot;</pre><ul><li><strong>azure_credentials.tfvars:</strong></li></ul><pre>azure_client_id       = &quot;your-azure-client-id&quot;<br>azure_client_secret   = &quot;your-azure-client-secret&quot;<br>azure_subscription_id = &quot;your-azure-subscription-id&quot;<br>azure_tenant_id       = &quot;your-azure-tenant-id&quot;</pre><p>5. Train the Model</p><ul><li>Create a filed named .<strong>gitignore.</strong> Add sensitive files to<strong> .gitignore</strong> to prevent them from being pushed to version control, you can do this by adding the following line in the file:</li></ul><pre>*.tfvars</pre><p>6. Initialize Terraform</p><ul><li>Run the following command to initialize the project and download the required provider plugins:</li></ul><pre>terraform init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0JOf9pb8BfoKnzB5559bg.png" /></figure><p>7. Validate and Plan the Setup</p><ul><li>Validate Configuration Files:</li></ul><pre>terraform validate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7vwC25x9TuSI3iv-YoD2w.png" /></figure><h3>5.3 Define AWS Resources on Terraform</h3><h3>STEPS TO BE PERFORMED:</h3><p>1. Get the Website Code on S3 and Enable Static Hosting Using Terraform</p><p>2. Set Up CloudFront Using Terraform</p><h3>1. Get the Website Code on S3 and Enable Static Hosting Using Terraform</h3><p>The first step in creating your multi-cloud weather tracker is to host the static content (HTML, CSS, JS, and assets) on an AWS S3 bucket with static website hosting enabled. Below is the detailed breakdown:</p><h3>1. Prepare Your Website Code</h3><ul><li>You can clone the website code from the link given <a href="https://github.com/akupheaws/Multi-Cloud-Weather-Tracker-App-with-Disaster-Recovery-using-Terraform.git">here</a></li><li>To download the website code, click on the<strong> green color button dropdown- </strong>Code, and click on Download Zip.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UI2rn0tHEsk6hDala3h-QQ.png" /></figure><p>Once the zip is downloaded, extract the zip and place the<strong><em> weather-tracker-app-main </em></strong>folder and place it in the root director of your created project- weather-tracker-app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NITzfE02XbRoVRblgs_NbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8wMNpSzelepsajiRF1HYQ.png" /></figure><ul><li>Make sure to rename the `<strong><em>weather-tracker-app-main</em></strong>` folder to `<strong><em>website</em></strong>`.</li><li>Organize your website files (e.g.,<strong><em> `index.html`, `styles.css`, `script.js`</em></strong>) along with an `<strong><em>assets/</em></strong>` folder containing images or other static content.</li><li>Ensure the directory structure:</li></ul><pre>weather-tracker-app/<br>├── website/<br>│   ├── index.html<br>│   ├── styles.css<br>│   ├── script.js<br>│   └── assets/<br>│       ├── image1.jpg<br>│       ├── image2.png<br>├── main.tf                 # Terraform configuration for AWS and Azure<br>├── variables.tf            # Input variables for AWS and Azure<br>├── aws_credentials.tfvars  # AWS credentials (securely stored)<br>├── azure_credentials.tfvars # Azure credentials (securely stored)<br>└── terraform.tfstate       # Terraform state file (auto-created)</pre><p>2. Define the S3 Bucket and Upload Files</p><p>Below is the Terraform code to configure the S3 bucket and upload files.</p><p><strong>Terraform Code (main.tf):</strong></p><pre># Define an S3 bucket for static website hosting<br>resource &quot;aws_s3_bucket&quot; &quot;weather_app&quot; {<br>  bucket = &quot;weather-tracker-app-bucket-345382&quot;  # Use a globally unique name<br><br>  website {<br>    index_document = &quot;index.html&quot;<br>    error_document = &quot;error.html&quot;<br>  }<br><br>  # Set bucket ownership controls<br>  lifecycle {<br>    prevent_destroy = true  # Prevent accidental deletion<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;public_access&quot; {<br>  bucket                  = aws_s3_bucket.weather_app.id<br>  block_public_acls       = false<br>  block_public_policy     = false<br>  ignore_public_acls      = false<br>  restrict_public_buckets = false<br>}<br><br># Upload website files to the S3 bucket<br>resource &quot;aws_s3_object&quot; &quot;website_index&quot; {<br>  bucket = aws_s3_bucket.weather_app.id<br>  key    = &quot;index.html&quot;<br>  source = &quot;website/index.html&quot;<br>  content_type = &quot;text/html&quot;<br>}<br><br>resource &quot;aws_s3_object&quot; &quot;website_style&quot; {<br>  bucket = aws_s3_bucket.weather_app.id<br>  key    = &quot;styles.css&quot;<br>  source = &quot;website/styles.css&quot;<br>  content_type = &quot;text/css&quot;<br>}<br><br>resource &quot;aws_s3_object&quot; &quot;website_script&quot; {<br>  bucket = aws_s3_bucket.weather_app.id<br>  key    = &quot;script.js&quot;<br>  source = &quot;website/script.js&quot;<br>  content_type = &quot;application/javascript&quot;<br>}<br><br># Upload assets (images) to the S3 bucket<br>resource &quot;aws_s3_object&quot; &quot;website_assets&quot; {<br>  for_each = fileset(&quot;website/assets&quot;, &quot;*&quot;)<br>  bucket   = aws_s3_bucket.weather_app.id<br>  key      = &quot;assets/${each.value}&quot;<br>  source   = &quot;website/assets/${each.value}&quot;<br>}<br><br># Add a bucket policy to allow public read access<br>resource &quot;aws_s3_bucket_policy&quot; &quot;bucket_policy&quot; {<br>  bucket = aws_s3_bucket.weather_app.id<br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;,<br>    Statement = [<br>      {<br>        Sid       = &quot;PublicReadGetObject&quot;,<br>        Effect    = &quot;Allow&quot;,<br>        Principal = &quot;*&quot;,<br>        Action    = &quot;s3:GetObject&quot;,<br>        Resource  = &quot;arn:aws:s3:::${aws_s3_bucket.weather_app.id}/*&quot;<br>      },<br>      {<br>        Sid       = &quot;CloudFrontLogsWrite&quot;,<br>        Effect    = &quot;Allow&quot;,<br>        Principal = {<br>          Service = &quot;cloudfront.amazonaws.com&quot;<br>        },<br>        Action    = &quot;s3:PutObject&quot;,<br>        Resource  = &quot;arn:aws:s3:::${aws_s3_bucket.weather_app.id}/cloudfront-logs/*&quot;<br>      }<br>    ]<br>  })<br>}</pre><p>Make sure you are using a globally unique name. You can change the trailing numbers in the end to create an unique name</p><h3>3. Explanation of Key Components</h3><ul><li><strong>S3 Bucket</strong></li></ul><p>- <strong>Static Website Hosting:</strong> Enabled with the `<strong><em>website</em></strong>` block, specifying<strong><em> `index.html`</em></strong> as the main entry point and `error.html` for errors.</p><p>- <strong>Lifecycle Rule</strong>: Prevent accidental deletion with `<strong><em>prevent_destroy</em></strong>`.</p><ul><li><strong>Public Access</strong></li></ul><p>- The `<strong><em>aws_s3_bucket_policy</em></strong>` provides public `<strong><em>GET</em></strong>` access to files while keeping upload access restricted.</p><ul><li><strong>File Upload</strong></li></ul><p>- `<strong><em>aws_s3_object</em></strong>` uploads the specified files to the S3 bucket.</p><p>- The `<strong><em>for_each</em></strong>` block iterates over files in the `<strong><em>assets/</em></strong>` directory, uploading them individually.</p><h3>4. Apply Terraform Configuration</h3><p>Initialize Terraform:</p><pre>terraform init</pre><p><strong>Review and Apply Changes</strong></p><pre>terraform apply -var-file=&quot;aws_credentials.tfvars&quot; -var-file=&quot;azure_credentials.tfvars&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ehv0X39-K1xNMNOFghtqYA.png" /></figure><h3>Verify the Resources</h3><ul><li>After the configuration is applied, Terraform will:</li><li>Create the S3 bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cl3SxSMSs25MKY4hv6UTCg.png" /></figure><h3>5. Access Your Website</h3><p>You can now access your hosted website using the S3 website endpoint:</p><pre>http://&lt;your-s3-bucket-name&gt;.s3-website-us-east-1.amazonaws.com</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjLmdpsi_WSIAlm8TAHu-Q.png" /></figure><h3>5.4 Define Azure Resources using Terraform</h3><h4>STEPS TO BE PERFORMED:</h4><p>1. Setup a Resource Group and a Storage Account</p><p>2. Upload Static Files to Azure Blob Storage</p><h4>1. Setup a Resource Group and a Storage Account</h4><h4>1. Define Resource Group</h4><ul><li>In this first step, we will define the <strong>Resource Group </strong>and the <strong>Storage Account </strong>that will host our static website.</li><li>After creating the Terraform configuration, we will apply it to create these resources in Azure. Add the below code in `main.tf`</li></ul><pre># Define Resource Group<br>resource &quot;azurerm_resource_group&quot; &quot;rg&quot; {<br>  name     = &quot;rg-static-website&quot;<br>  location = &quot;East US&quot;<br>}</pre><ul><li><strong>name</strong>: The name of the resource group, which in this case is `”rg-static-website”`.</li><li><strong>location</strong>: The Azure region where the resources will be created. You can use `”East US”` or any other preferred Azure region.</li></ul><h4>2. Define Storage Account</h4><pre># Define Storage Account with Static Website<br>resource &quot;azurerm_storage_account&quot; &quot;storage&quot; {<br>  name                     = &quot;mystorageaccount345382&quot;<br>  resource_group_name       = azurerm_resource_group.rg.name<br>  location                 = azurerm_resource_group.rg.location<br>  account_tier              = &quot;Standard&quot;<br>  account_replication_type = &quot;LRS&quot;<br>  account_kind              = &quot;StorageV2&quot;<br><br>  static_website {<br>    index_document = &quot;index.html&quot;<br>  }<br>}</pre><p>Make sure you are using a globally unique name. You can change the trailing numbers in the end to create an unique name.</p><ul><li><strong>name</strong>: A globally unique name for the storage account (`<strong><em>mystorageaccount345382</em></strong>`).</li><li><strong>account_tier</strong>: `<strong><em>Standard</em></strong>` is the most common choice for static websites.</li><li><strong>account_replication_type</strong>: We use `<strong><em>LRS</em></strong>` for locally redundant storage to ensure high availability.</li><li><strong>account_kind</strong>: `<strong><em>StorageV2</em></strong>` enables general-purpose storage.</li><li><strong>static_website</strong>: Specifies that static website hosting will be enabled, with the `<strong><em>index.html</em></strong>` file being the entry point.</li></ul><h4>3. Apply Terraform Configuration</h4><p>After defining the resource group and storage account, run the following commands to create these resources:</p><ol><li><strong>Initialize Terraform:</strong></li></ol><pre>terraform init --upgrade</pre><p><strong>2. Plan the Deployment:</strong></p><pre>terraform plan -var-file=&quot;aws_credentials.tfvars&quot; -var-file=&quot;azure_credentials.tfvars&quot;</pre><p><strong>3. Apply the Configuration:</strong></p><pre>terraform apply -var-file=&quot;aws_credentials.tfvars&quot; -var-file=&quot;azure_credentials.tfvars&quot;</pre><p>Once applied, Terraform will create the resource group and storage account, enabling the static website feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5IFq4KJk-sWs6a-UfpY0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bye5UaBstC763YUbzn5VWA.png" /></figure><h4>2. Upload Static Files to Azure Blob Storage</h4><ul><li>After the resource group and storage account are set up, the next step is to upload your static files (HTML, CSS, JS, and other assets) to Azure Blob Storage.</li></ul><h4>1. Upload the index.html</h4><pre># Upload index.html<br>resource &quot;azurerm_storage_blob&quot; &quot;index_html&quot; {<br>  name                   = &quot;index.html&quot;<br>  storage_account_name   = azurerm_storage_account.storage.name<br>  storage_container_name = &quot;$web&quot;  # Static website container<br>  type                   = &quot;Block&quot;<br>  content_type           = &quot;text/html&quot;<br>  source                 = &quot;website/index.html&quot;  # Path to local file<br>}</pre><ul><li><strong>name</strong>: The file name in Azure Blob Storage (<strong><em>`index.html`)</em></strong>.</li><li><strong>content_type</strong>: MIME type for HTML files (<strong><em>`text/html`</em></strong>).</li><li><strong>source</strong>: The local path to the `<strong><em>index.html`</em></strong> file.</li></ul><h4>2. Upload the styles.css</h4><pre># Upload styles.css<br>resource &quot;azurerm_storage_blob&quot; &quot;styles_css&quot; {<br>  name                   = &quot;styles.css&quot;<br>  storage_account_name   = azurerm_storage_account.storage.name<br>  storage_container_name = &quot;$web&quot;<br>  type                   = &quot;Block&quot;<br>  content_type           = &quot;text/css&quot;<br>  source                 = &quot;website/styles.css&quot;  # Path to local file<br>}</pre><h4>3. Upload the script.js</h4><pre># Upload script.js<br>resource &quot;azurerm_storage_blob&quot; &quot;scripts_js&quot; {<br>  name                   = &quot;script.js&quot;<br>  storage_account_name   = azurerm_storage_account.storage.name<br>  storage_container_name = &quot;$web&quot;<br>  type                   = &quot;Block&quot;<br>  content_type           = &quot;application/javascript&quot;<br>  source                 = &quot;website/script.js&quot;  # Path to local file<br>}</pre><h4>4. Upload Assets (Images, Files, etc.)</h4><pre># Upload all assets in the assets folder<br>resource &quot;azurerm_storage_blob&quot; &quot;assets&quot; {<br>  for_each = fileset(&quot;website/assets&quot;, &quot;**/*&quot;)<br><br>  name                   = &quot;assets/${each.value}&quot;<br>  storage_account_name   = azurerm_storage_account.storage.name<br>  storage_container_name = &quot;$web&quot;<br>  type                   = &quot;Block&quot;<br>  content_type           = lookup(<br>    {<br>      &quot;png&quot;  = &quot;image/png&quot;<br>      &quot;jpg&quot;  = &quot;image/jpeg&quot;<br>      &quot;jpeg&quot; = &quot;image/jpeg&quot;<br>      &quot;gif&quot;  = &quot;image/gif&quot;<br>      &quot;svg&quot;  = &quot;image/svg+xml&quot;<br>    },<br>    split(&quot;.&quot;, each.value)[length(split(&quot;.&quot;, each.value)) - 1],<br>    &quot;application/octet-stream&quot;<br>  )<br>  source = &quot;website/assets/${each.value}&quot;  # Path to local assets<br>}</pre><ul><li><strong>for_each</strong>: Loops through all files in the `assets` folder and uploads them.</li><li><strong>content_type</strong>: The MIME type for each asset based on its file extension.</li></ul><h4>5. Apply Terraform Configuration</h4><p>After the storage account is set up, the next step is to upload the files. Run the following Terraform commands to upload the static files to Azure Blob Storage:</p><ol><li><strong>Plan the Deployment:</strong></li></ol><pre>terraform plan -var-file=&quot;aws_credentials.tfvars&quot; -var-file=&quot;azure_credentials.tfvars&quot;</pre><p><strong>2. Apply the Configuration:</strong></p><pre>terraform apply -var-file=&quot;aws_credentials.tfvars&quot; -var-file=&quot;azure_credentials.tfvars&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zr57CJVHhmRhc0zfDXW7ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Su6gSmkum_Ty1fQoXVhew.png" /></figure><p>Once the files are uploaded, your static website will be accessible via the Azure Storage Account’s public URL (e.g., <a href="https://stwebakuphe345382.z13.web.core.windows.net/">https://stwebakuphe345382.z13.web.core.windows.net/</a></p><pre>https://&lt;cdn_endpoint_name&gt;.azureedge.net</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cl3kQn4jppQWlM2i0OnwA.png" /></figure><h3>5.5 Implement Disaster Recovery with Route 53 DNS Failover</h3><h4>STEPS TO BE PERFORMED:</h4><p>1. Buy and Register a Domain Name</p><p>2. Create a Hosted Zone in Route 53</p><p>3. Request an SSL Certificate for CloudFront</p><p>4. Configure CloudFront with Alternate Domain Names</p><p>5. Define Health Checks for Failover</p><p>6. Setup Route 53 Records for Failover</p><p>7. Update Namecheap Nameservers</p><p>8. Verify DNS Propagation<br>9. Expected Behavior and Limitations</p><h4>1. Buy and Register a Domain Name</h4><p>You can buy domain names at very affordable prices (as low as $1) from Namecheap. Here’s how to find and purchase domains according to your requirements:</p><p><strong>1. Search for Available Domains:</strong></p><ul><li>Go to <strong>Namecheap</strong>: Visit <a href="https://www.namecheap.com/">Namecheap.com</a>.</li><li>Use the Search Bar: Enter your desired domain name in the search bar to check availability.</li><li>Tip: Domains with popular extensions (like .com) can be more expensive. If you’re on a budget, consider using other domain extensions such as .site, .online, or .tech.</li></ul><p><strong>2. Filter for Cheapest Domains:</strong></p><ul><li>After searching, Namecheap shows a list of available domains, and you can filter results by price range.</li><li>Look for Promotions: Namecheap often offers discounts for new customers, and you may find special pricing for certain domain extensions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj1hOO8LzV97gnH5S1V43w.png" /></figure><p><strong>3. Compare Prices:</strong></p><ul><li><strong>Domain Extensions Matter:</strong> Domains with the traditional .com extension tend to be more expensive. If your goal is to minimize cost, explore other domain extensions like .site, .tech, .online, or .xyz, which often cost much less.</li></ul><p><strong>4. Purchase the Domain:</strong></p><ul><li>Once you find an affordable domain name that fits your needs, add it to your cart.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZC2h2sgYb0y5k7UMvgq0Q.png" /></figure><ul><li>Proceed to checkout and complete the purchase with payment options such as credit cards or PayPal.</li><li>And there you go! We just got a domain name for just $1.18 for one year.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDkDDCT43LY95i0-Y14KHw.png" /></figure><p><strong>5. After Purchase:</strong></p><ul><li>You’ll be able to manage your domain through Namecheap’s dashboard. From there, you can configure DNS settings, set up email forwarding, and more.</li></ul><h4>2. Create a Hosted Zone in Route 53</h4><ul><li>Use Terraform to create the hosted zone. Add the below code to your main.tf file</li></ul><pre>resource &quot;aws_route53_zone&quot; &quot;main&quot; {<br>  name = &quot;yourdomain.com&quot;<br>}</pre><h4>3. Request an SSL Certificate for CloudFront</h4><p>Since <strong>CloudFront</strong> does not support <strong>HTTP to HTTPS redirection </strong>by default, you need an SSL certificate in ACM.</p><p>Request a SSL Certificate:</p><p>1. Go to <strong>AWS Certificate Manager (ACM).</strong></p><p>2. Request a public certificate for `<strong><em>yourdomain.com` </em></strong>and<strong><em> `www.yourdomain.com`.</em></strong></p><p>3. Validate the certificate using <strong>DNS validation </strong>(recommended).</p><p>4. Once the certificate is issued, associate it with your <strong>CloudFront distribution.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9Tr9HrVMpCZl2NFDf2NnQ.png" /></figure><h3>4. Configure CloudFront with Alternate Domain Names</h3><p>After obtaining an<strong> SSL certificate:</strong></p><p>1. Go to <strong>CloudFront</strong> → Select your distribution.</p><p>2. Add Alternate Domain Names (<strong>CNAMEs</strong>):</p><ul><li><strong><em>`yourdomain.com`</em></strong></li><li><strong><em>`www.yourdomain.com`</em></strong></li></ul><p>3. Attach the ACM Certificate to the distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R--FCdjkYqr8F5YWfBHO6g.png" /></figure><h4>5. Define Health Checks for Failover</h4><p>Add the following code in `main.tf` file:</p><p><strong>AWS (Primary) Health Check:</strong></p><pre>resource &quot;aws_route53_health_check&quot; &quot;aws_health_check&quot; {<br>  type              = &quot;HTTPS&quot;<br>  fqdn              = &quot;your-aws-cloudfront.cloudfront.net&quot;<br>  port              = 443<br>  request_interval  = 30<br>  failure_threshold = 3<br>}</pre><p><strong>Azure (Secondary) Health Check</strong></p><pre>resource &quot;aws_route53_health_check&quot; &quot;azure_health_check&quot; {<br>  type              = &quot;HTTPS&quot;<br>  fqdn              = &quot;your-azure-site.web.core.windows.net&quot;<br>  port              = 443<br>  request_interval  = 30<br>  failure_threshold = 3<br>}</pre><h4>6. Setup Route 53 Records for Failover</h4><p>Add the following code to the<strong><em> `main.tf`</em></strong> file:</p><p><strong>Primary Record (AWS — CloudFront)</strong></p><pre>resource &quot;aws_route53_record&quot; &quot;primary&quot; {<br>  zone_id = aws_route53_zone.main.zone_id<br>  name    = &quot;yourdomain.com&quot;<br>  type    = &quot;A&quot;<br><br>  alias {<br>    name                   = &quot;your-aws-cloudfront.cloudfront.net&quot;<br>    zone_id                = &quot;Z2FDTNDATAQYW2&quot;  # CloudFront&#39;s hosted zone ID<br>    evaluate_target_health = true<br>  }<br><br>  failover_routing_policy {<br>    type = &quot;PRIMARY&quot;<br>  }<br><br>  set_identifier = &quot;primary&quot;<br>  health_check_id = aws_route53_health_check.aws_health_check.id<br>}</pre><p><strong>Secondary Record (Azure — Blob Storage)</strong></p><pre>resource &quot;aws_route53_record&quot; &quot;secondary&quot; {<br>  zone_id = aws_route53_zone.main.zone_id<br>  name    = &quot;www.yourdomain.com&quot;<br>  type    = &quot;CNAME&quot;<br><br>  records = [&quot;your-azure-site.web.core.windows.net&quot;]<br><br>  ttl = 300<br><br>  failover_routing_policy {<br>    type = &quot;SECONDARY&quot;<br>  }<br><br>  set_identifier = &quot;secondary&quot;<br>  health_check_id = aws_route53_health_check.azure_health_check.id<br>}<br><br></pre><p>Run the below command in the terminal:</p><pre>terraform apply -var-file=&quot;aws_credentials.tfvars&quot; -var-file=&quot;azure_credentials.tfvars&quot;</pre><h4>7. Update Namecheap Nameservers</h4><p>To use Route 53 as your DNS provider, update the domain’s nameservers in Namecheap.</p><p>1. Log in to Namecheap.</p><p>2. Go to Domain List → Manage your domain.</p><p>3. Under Nameservers, select Custom DNS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWLShzeC6nn_Ef2FYr7hKw.png" /></figure><p>4. Enter the AWS Route 53 nameservers (from your hosted zone).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksBU6e4YmJQgjg8gmONZtQ.png" /></figure><ul><li><strong>Example:</strong></li></ul><pre>CopyEdit<br>ns-123.awsdns-45.com<br>ns-234.awsdns-56.org<br>ns-345.awsdns-67.net<br>ns-456.awsdns-78.co.uk</pre><ul><li>Save Changes and wait for DNS propagation (can take up to half an hour).</li></ul><h4>8. Verify DNS Propagation</h4><p>Check if the domain is resolving correctly using <a href="https://dnschecker.org/">DNS Checker.</a></p><ul><li>Search for A record of <strong><em>`yourdomain.com`</em></strong></li><li>Check CNAME record for `<strong><em>www.yourdomain.com`</em></strong></li><li>Ensure CloudFront URL and domain are resolving correctly</li><li>Now you can try accessing your website by typing in the DNS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDZ9RywrusD2EkleLO4kNw.png" /></figure><p><strong>Primary Site (AWS CloudFront):</strong></p><ul><li>HTTPS enabled and secure</li><li>Custom domain working with SSL certificate</li></ul><p><strong>Failover Site (Azure Blob Storage):</strong></p><ul><li>Failover functionality works correctly</li><li>Shows “Not secure” warning — this is expected behavior</li><li>Azure Blob Storage static websites don’t support HTTPS with custom domains by default</li><li>In production environments, you would configure Azure CDN to enable HTTPS</li></ul><p><strong>Testing Failover:</strong></p><p>To test failover functionality:</p><p>1. Restrict S3 bucket public access (or disable CloudFront)</p><p>2. Visit your domain — it should redirect to Azure</p><p>3. You’ll see “Not secure” warning — this is normal for this course setup</p><p>4. The site should remain functional despite the warning</p><blockquote>To confirm failover, disable the CloudFront distribution and then try to access your website (e.g., www.weather-track-akuphe.site). If the site still loads, the failover is working.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozR5IXA7TidFMQ3Qhm1Ulg.png" /></figure><h4>Why that can prove failover</h4><ul><li>Your Route 53 <strong>primary</strong> record for www points to <strong>CloudFront</strong> and is tied to a <strong>health check</strong> that expects a 2xx/3xx response.</li><li>When you <strong>disable</strong> the CloudFront distribution, requests typically return a <strong>4xx</strong> (e.g., 403 “distribution disabled”), so the <strong>health check becomes unhealthy</strong>.</li><li>Route 53 then <strong>serves the SECONDARY record</strong> (Azure static site). After DNS cache (TTL) expires, www resolves to Azure and the site still loads — confirming failover.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uIQdSepL1tuk7jqVHHPXA.png" /></figure><h4>Important caveats</h4><ul><li>This test applies to <strong>www.weather-track-akuphe.site</strong> where you configured <strong>failover</strong>. Your <strong>apex</strong> (weather-track-akuphe.site) points only to CloudFront, so disabling CloudFront will make the apex <strong>stop working</strong> (by design)</li><li>DNS has <strong>TTL (you set ~60s)</strong>, so allow a minute (sometimes a bit more) for resolvers to switch answers.</li><li>Disabling/re-enabling a CloudFront distribution is <strong>slow and disruptive</strong> in production.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LBhkjyMZvtsjJVaOEugVA.png" /></figure><h3>Conclusion</h3><p>This project demonstrated how to design and deploy a Multi-Cloud Weather Tracker website with built-in disaster recovery using Terraform, AWS, and Azure. Through a series of guided steps, you defined and provisioned cloud resources on both platforms using Infrastructure as Code (IaC), ensuring a repeatable and scalable deployment process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=496ce5f3dec0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Deploying an AI-Powered Threat Detection System on AWS]]></title>
            <link>https://medium.com/@akupheaws/building-and-deploying-an-ai-powered-threat-detection-system-on-aws-b3bfe35e75c4?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3bfe35e75c4</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 05:32:25 GMT</pubDate>
            <atom:updated>2026-07-07T14:47:13.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DP4ashSUj4Ac-ShTXLy10g.png" /></figure><h3>Project Overview ☁️</h3><p>This project focuses on <strong>building and deploying an AI-powered Cybersecurity Threat Detection System</strong> using <strong>Amazon SageMaker</strong>. The solution is designed to detect anomalous network activity that may indicate potential cyberattacks, such as <strong>DDoS attacks</strong>, <strong>unauthorized access attempts</strong>, or <strong>phishing activities</strong>.</p><p>The system leverages a <strong>machine learning pipeline</strong> that fully automates <strong>data ingestion, preprocessing, model training, deployment, and real-time inference</strong>, ensuring scalability and operational efficiency.</p><h3>Key Components</h3><ul><li><strong>Data Ingestion &amp; Preprocessing:</strong> Raw <a href="https://www.cloudforgeconsult.com/">network</a> traffic logs are collected, transformed, and feature-engineered to create a structured dataset.</li><li><strong>Model Training &amp; Evaluation:</strong> An XGBoost model is trained to classify network activity as normal or malicious.</li><li><strong>Deployment &amp; Inference: </strong>The trained <a href="https://www.cloudforgeconsult.com/">model</a> is deployed as an endpoint to detect real-time security threats.</li><li><strong>Pipeline Automation: </strong>An end-to-end SageMaker Pipeline automates data transformation, model training, and deployment.</li></ul><h3>Steps to be performed</h3><p>We’ll go through the following steps in the next few lessons.</p><p>1. Preprocess Data and Feature Engineering</p><p>2. Training and Testing a Model using XGBoost</p><p>3. Deploy and Serve the Model</p><p>4. Automating with SageMaker Pipelines</p><h3>AWS Services Used</h3><ul><li><strong>Amazon SageMaker</strong>: Trains, deploys, and serves the machine learning model. [<strong>Machine Learning]</strong></li><li><strong>Amazon S3</strong>: Stores raw network traffic <a href="https://www.cloudforgeconsult.com/">logs</a>, preprocessed data, and model artifacts. [<strong>Storage</strong>]</li><li><strong>AWS Lambda:</strong> Automates data preprocessing tasks and feature extraction. [<strong>Compute</strong>]</li><li><strong>Amazon CloudWatch:</strong> Monitors model performance and logs security threats. [<strong>Monitoring</strong>]</li><li><strong>AWS IAM: </strong>Manages permissions and security policies for accessing AWS services. [<strong>Security</strong>]</li></ul><h3>4.2 Preprocess Data &amp; Perform Feature Engineering</h3><p>In this stage, we prepare the <strong>network traffic dataset</strong> to ensure it is clean, structured, and optimized for training a <strong>machine learning model</strong> for cybersecurity threat detection.</p><p>The process involves:</p><ol><li><strong>Setting up the AWS environment</strong> with the necessary permissions and configurations.</li><li><strong>Fetching a public dataset</strong> containing network traffic logs relevant to threat detection.</li><li><strong>Cleaning and normalizing the data</strong> to remove inconsistencies, handle missing values, and standardize formats.</li><li><strong>Engineering meaningful features</strong> that capture patterns indicative of malicious activities.</li><li><strong>Saving the processed dataset</strong> in a format suitable for training and evaluation.</li></ol><blockquote><strong><em>Why it matters:</em></strong><em><br> High-quality, well-engineered input data is essential for building a </em><strong><em>reliable and accurate model</em></strong><em>. Poor data preparation can significantly reduce detection performance, even if advanced algorithms are used.</em></blockquote><h3>1. Create an IAM Role for SageMaker</h3><p>To allow Amazon SageMaker to securely access other AWS services such as Amazon S3, you need to create an <strong>IAM role</strong> with the appropriate permissions. In the AWS Management Console, navigate to <strong>IAM</strong>, select <strong>Roles</strong>, and click <strong>Create role</strong>. Choose <strong>AWS service</strong> as the trusted entity type, then select <strong>SageMaker</strong> as the use case. Assign a descriptive name (e.g., SageMakerExecutionRole) to make it easy to identify later, and proceed to attach the necessary permission policies before completing the role creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7pYBNNowAk_l2-zk820Nw.png" /></figure><p>Next, click <strong>Next</strong> to proceed to the permissions section, then search for and attach the <strong>AmazonSageMakerFullAccess</strong> policy to grant SageMaker the required permissions. Click <strong>Next</strong> again, provide a clear and descriptive role name such as SageMakerCybersecurityRole, and complete the role creation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1dCosZGrM-G9QYoXgpnRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xcsoTsEar_cBKKV5zjHDg.png" /></figure><p>After creating the role, navigate back to the <strong>IAM console</strong> and locate your newly created role. Open the role details page, go to the <strong>Permissions</strong> tab, and click <strong>Add permissions</strong> → <strong>Attach policies</strong>. Search for and attach the <strong>AmazonS3FullAccess</strong> policy to grant SageMaker access to read and write data in Amazon S3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGQ3swOGTKxRZcQH4Mr5XQ.png" /></figure><h3>2. Set Up Amazon SageMaker Notebook Instance</h3><p>A Notebook Instance is an easy way to run Jupyter notebooks in AWS. It’s perfect for small projects, learning environments, or when Studio feels like too much.</p><ul><li>Go to the Amazon<strong> SageMaker AI Console</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mzIO60-5Huv2q_HNDm1cg.png" /></figure><p>Click <strong>Notebook instances → Create notebook instance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_ljXdP-WCX09g5KoLL_eQ.png" /></figure><ul><li>Fill in:</li><li>Notebook instance name: `<strong><em>cybersecurity</em></strong>-<strong><em>notebook</em></strong>`</li><li>Instance type: `<strong><em>ml.t2.medium</em></strong>` (free tier eligible)</li><li>IAM role: Select the `<strong><em>SageMakerCybersecurityRole</em></strong>` you created earlier</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqLRIa8XyqOatU4dWQGo6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVTtOiC3O9CVPOBnz3g_Vg.png" /></figure><p>Leave all other settings as default, then click <strong>Create notebook instance</strong>. Wait for the instance status to change to <strong>InService</strong>, and once it is ready, click <strong>Open Jupyter</strong> to access the development environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6ua8LnecqbmU4YzRrGS9w.png" /></figure><h3>3. Download &amp; Upload a Public Dataset to S3</h3><p>You need real-world data for threat detection. We’ll use a public dataset from UNSW-NB15, which contains normal and malicious network activities.</p><p><strong>Dataset</strong>:<em> UNSW-NB15</em></p><ul><li><strong>For simplicity,</strong> we’ll use a cleaned CSV version of the dataset:</li><li><strong>Download</strong>: <a href="https://github.com/akupheaws/Building-and-Deploying-an-AI-Powered-Threat-Detection-System-on-AWS">UNSW_NB15_training-set.csv</a></li><li>If you want to view training set, access it here:<a href="https://drive.google.com/file/d/1ShuzJvAe5uANn6-0FQMW5gAL5sYa0Ncf/view?usp=drive_link"> Training Set</a></li><li>Upload to <strong>S3</strong>:</li><li>Go to<strong> Amazon S3 → Click Create Bucket</strong> (name it something like <strong><em>`cybersecurity-ml-data1`</em></strong>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FW7aCABCGX_CukC6xQRug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fNLWs2aDjU7fyhVz621rg.png" /></figure><ul><li>Once the bucket is created, open it and create a folder called `<strong>raw-data</strong>`</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYvoqIQdzvw2xnx3gFD83A.png" /></figure><p>Upload the CSV file into this folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Bck6xhETZMqKmQar29UGA.png" /></figure><h3>4. Load &amp; Explore the Dataset in SageMaker</h3><p>Before processing the data, you need to understand it. What features exist, how many records there are, and whether labels are balanced.</p><ul><li>Navigate to<strong> Amazon SageMaker AI Console → Notebook instances → `<em>cybersecurity-notebook</em></strong><em>`</em></li><li>Click<strong> Open Jupyter → File → New → Notebook →</strong> Name it `<strong><em>data_preprocessing.ipynb</em></strong>`</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbkaZsguVYCwUdknrYLN2g.png" /></figure><ul><li>Paste the below code in <strong><em>data_preprocessing</em></strong>.<strong><em>ipynb</em></strong>:</li></ul><pre>import boto3<br>import pandas as pd<br>import io<br><br># Setup S3 client<br>s3_client = boto3.client(&#39;s3&#39;)<br><br># Download the file into memory<br>response = s3_client.get_object(Bucket=&#39;cybersecurity-ml-data1&#39;, Key=&#39;raw-data/UNSW_NB15_training-set.csv&#39;)<br><br># Read it into pandas<br>df = pd.read_csv(io.BytesIO(response[&#39;Body&#39;].read()))<br><br># Explore<br>print(df.shape)<br>print(df.columns)<br>print(df.head())<br>print(df[&#39;label&#39;].value_counts())</pre><ul><li>Click Run ▶ from the Navbar</li><li>You will receive this output:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dP03S-W7aiJ8qLY0NrNMBw.png" /></figure><p><strong>Explanation:</strong><br> Amazon S3 is used as the primary storage location for datasets, allowing seamless access from the SageMaker notebook. The <strong>label</strong> column in the dataset indicates whether the network traffic is <strong>normal (0)</strong> or <strong>malicious (1)</strong>. Performing an initial exploration of the data helps identify necessary cleaning steps and preprocessing requirements to ensure the dataset is ready for model training.</p><h3>5. Clean, Feature Engineer, Encode, and Normalize Data</h3><p>We now prepare the dataset so that our ML models can use it effectively. This step combines data cleaning, feature engineering, categorical encoding, and numerical scaling.</p><h3>1. Drop irrelevant columns</h3><ul><li><strong><em>id</em></strong> is just a row number and has no predictive value.</li><li><strong><em>attack_cat</em></strong> is a more detailed attack type label, but for binary classification (label = malicious or normal), it’s not needed.</li></ul><h3>2. Feature engineering (before encoding &amp; scaling)</h3><p>We create new features from existing ones to help the model detect patterns:</p><ul><li><strong><em>byte_ratio</em></strong> — Source bytes / (Destination bytes + 1)<br>- Helps detect traffic that’s heavily one-sided.<br>- +1 prevents division by zero.</li><li><strong><em>is_common_port</em></strong> — 1 if destination port is 80, 443, or 22<br>- Flags traffic over common HTTP/HTTPS/SSH ports.</li><li><strong><em>flow_intensity</em></strong> — (Source packets + Destination packets) / (Duration + 1e-6)<br>- Measures packet rate; useful for spotting floods or spikes.<br>- Small number (1e-6) prevents division by zero.</li></ul><h3>3. One-hot encode categorical features</h3><ul><li>Converts text columns like <strong><em>proto, service, </em></strong>and<strong><em> state </em></strong>into multiple binary columns.</li><li>Each unique category becomes its own column with <strong><em>1 (present) or 0 (absent).</em></strong></li></ul><h3>4. Convert Booleans to integers</h3><ul><li>Some one-hot columns might be<strong><em> True/False.</em></strong></li><li>We explicitly convert them to <strong><em>1/0 </em></strong>for compatibility with ML models.</li></ul><h3>5. Scale numerical features</h3><ul><li>Standardize all numeric columns except <strong><em>label</em></strong> so they have mean 0 and standard deviation 1.</li><li>Prevents features with larger ranges (e.g., byte counts) from dominating smaller-range features (e.g., ratios).</li></ul><h3>6. Sanity checks</h3><ul><li>Print final dataset shape, column names, a preview of the first rows, and class distribution in <strong><em>label</em></strong>.</li></ul><h3>Code:</h3><ul><li>Paste the below code in new cell and Click Run</li></ul><pre># --- 1. Drop irrelevant columns ---<br>df = df.drop(columns=[&#39;id&#39;, &#39;attack_cat&#39;])<br><br># --- 2. Feature engineering BEFORE encoding/scaling ---<br>df[&#39;byte_ratio&#39;] = df[&#39;sbytes&#39;] / (df[&#39;dbytes&#39;] + 1)<br>df[&#39;is_common_port&#39;] = df[&#39;ct_dst_sport_ltm&#39;].isin([80, 443, 22]).astype(int)<br>df[&#39;flow_intensity&#39;] = (df[&#39;spkts&#39;] + df[&#39;dpkts&#39;]) / (df[&#39;dur&#39;] + 1e-6)<br><br># --- 3. One-hot encode categorical columns ---<br>categorical_cols = [&#39;proto&#39;, &#39;service&#39;, &#39;state&#39;]<br>df = pd.get_dummies(df, columns=categorical_cols)<br><br># Convert booleans to ints<br>df = df.astype({col: &#39;int&#39; for col in df.columns if df[col].dtype == &#39;bool&#39;})<br><br># --- 4. Scale numerical features (except label) ---<br>from sklearn.preprocessing import StandardScaler<br><br>numerical_cols = df.select_dtypes(include=[&#39;int64&#39;, &#39;float64&#39;]).columns.tolist()<br>numerical_cols.remove(&#39;label&#39;)<br><br>scaler = StandardScaler()<br>df[numerical_cols] = scaler.fit_transform(df[numerical_cols])<br><br># --- Checks ---<br>print(df.shape)                                  # Final number of rows &amp; columns<br>print(df.head())                                 # Preview first few rows<br>print(df.describe().T[[&#39;mean&#39;, &#39;std&#39;]])          # Confirm scaling stats<br>print(df[numerical_cols].mean().round(3))        # Should be ~0<br>print(df[numerical_cols].std().round(3))         # Should be ~1</pre><p>You will receive the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kW1CLIDDqy6xawGRApS5w.png" /></figure><h3>Conceptual Notes for Beginners</h3><ul><li><strong>One-hot encoding:</strong> This takes a column like `<strong><em>proto</em></strong>` with values `<strong><em>TCP</em></strong>`, `<strong><em>UDP</em></strong>`, and `<strong><em>ICMP</em></strong>`, and turns it into 3 new columns — each showing 1 or 0.</li><li><strong>StandardScaler:</strong> It transforms values so they have a mean of 0 and standard deviation of 1 useful when features have wildly different units (like packet count vs. byte size).</li></ul><h3>Tips for Feature Engineering</h3><ul><li>Always divide by<strong> `+1</strong>` or add a tiny number to avoid division by zero.</li><li>Try plotting distributions of these new features — sometimes it helps visualize how well they separate classes.</li></ul><h3>6. Save the Preprocessed Data to S3</h3><p>Now that your dataset is ready, you need to store it in S3 so it can be accessed later by your ML model.</p><ul><li>Save your processed dataset locally as <strong>CSV</strong></li><li>Upload it to your S3 bucket using SageMaker’s session utility</li><li>Paste the below code in new cell and <strong>Click Run</strong></li></ul><pre>import sagemaker<br>from sagemaker import get_execution_role<br><br># Create SageMaker session and define bucket<br>session = sagemaker.Session()<br>bucket = &#39;cybersecurity-ml-data1&#39;  # Replace with your actual S3 bucket name<br>processed_prefix = &#39;processed-data&#39;      # Folder in S3 to store processed files<br><br># Save preprocessed data locally<br>df.to_csv(&#39;preprocessed_data.csv&#39;, index=False)<br><br># Upload to S3 inside the &#39;processed-data/&#39; folder<br>s3_path = session.upload_data(<br>    path=&#39;preprocessed_data.csv&#39;,<br>    bucket=bucket,<br>    key_prefix=processed_prefix<br>)<br><br>print(f&quot;Preprocessed data uploaded to: {s3_path}&quot;)</pre><p>Validate your S3 Bucket if the <strong>‘<em>processed-data.csv</em></strong>’ file got uploaded under the ‘<strong><em>processed-data</em></strong>’ folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VF2G3kbOg1ArjQDVaBdBEA.png" /></figure><ul><li>S3 is like your <strong>cloud hard drive</strong>. Storing the preprocessed data there means you can train your model later on <strong>SageMaker</strong> or any cloud environment without redoing all preprocessing steps.</li></ul><h3>4.3 Training and Testing a Model using XGBoost</h3><p>Train a machine learning model (using <strong>XGBoost</strong>) to classify whether a given network activity is normal or malicious, based on the features extracted in Step 1.</p><p>We’ll use <strong>Amazon SageMaker’s built-in XGBoost algorithm,</strong> which makes training efficient and scalable.</p><h3>STEPS TO BE PERFORMED:</h3><ol><li>Load Preprocessed Data from S3</li><li>Split Data into Train/Test Sets</li><li>Upload Training and Test Data to S3</li><li>Set Up the XGBoost Training Job</li><li>Train the Model</li><li>Evaluate Model Performance</li></ol><h3>1. Load Preprocessed Data from S3</h3><ul><li>Paste the below code in new cell and Click Run</li></ul><pre>import pandas as pd<br>import boto3<br>import sagemaker<br><br># Set up session and bucket<br>session = sagemaker.Session()<br>bucket = &#39;cybersecurity-ml-data1&#39;<br>processed_prefix = &#39;processed-data&#39;<br><br># Download preprocessed data from S3<br>s3 = boto3.client(&#39;s3&#39;)<br>file_name = &#39;preprocessed_data.csv&#39;<br>s3.download_file(bucket, f&#39;{processed_prefix}/{file_name}&#39;, file_name)<br><br># Load into pandas<br>df = pd.read_csv(file_name)<br>df.head()</pre><p>This code downloads a <strong>preprocessed CSV file</strong> from an S3 bucket and loads it into a Pandas DataFrame for inspection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RQzMNEV_xVDPy4OgcYAjg.png" /></figure><h3>2. Split Data into Train/Test Sets</h3><ul><li>Paste the below code in new cell and Click <strong>Run</strong></li></ul><pre>from sklearn.model_selection import train_test_split<br>from sklearn.datasets import dump_svmlight_file<br>import pandas as pd<br><br># Load data<br>df = pd.read_csv(&#39;preprocessed_data.csv&#39;)<br>X = df.drop(columns=[&#39;label&#39;])<br>y = df[&#39;label&#39;]<br><br># Split data<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br># CSV for inspection<br>train_df = pd.concat([y_train, X_train], axis=1)<br>test_df = pd.concat([y_test, X_test], axis=1)<br>train_df.to_csv(&#39;train.csv&#39;, index=False)<br>test_df.to_csv(&#39;test.csv&#39;, index=False)<br><br># LIBSVM for SageMaker - fixed version<br>dump_svmlight_file(X_train, y_train.values.ravel(), &#39;train.libsvm&#39;)<br>dump_svmlight_file(X_test, y_test.values.ravel(), &#39;test.libsvm&#39;)</pre><p>This code <strong>loads</strong> a preprocessed CSV dataset, <strong>splits</strong> it into <strong>training</strong> and <strong>testing</strong> sets, saves them as CSV for inspection, and converts them into <strong>LIBSVM</strong> format for use with Amazon SageMaker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rrmv6O6vb2AQyt2TzqdXjQ.png" /></figure><h3>3. Upload Training and Test Data to S3</h3><ul><li>Paste the below code in new cell and Click <strong>Run</strong></li></ul><pre>import sagemaker<br><br>session = sagemaker.Session()<br>bucket = &#39;cybersecurity-ml-data1&#39;<br>train_prefix = &#39;xgboost-data/train&#39;<br>test_prefix = &#39;xgboost-data/test&#39;<br><br>train_input = session.upload_data(&#39;train.libsvm&#39;, bucket=bucket, key_prefix=train_prefix)<br>test_input = session.upload_data(&#39;test.libsvm&#39;, bucket=bucket, key_prefix=test_prefix)<br><br>print(f&quot;Training data: {train_input}&quot;)<br>print(f&quot;Testing data: {test_input}&quot;)</pre><p>This code uploads the LIBSVM-formatted training and testing data files to specified paths in an S3 bucket for use with Amazon SageMaker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmtFJDxo0lNq7japEBTWXQ.png" /></figure><p>Validate your S3 Bucket if the test &amp; train folders got created under the ‘xgboost-data’ folder with respective files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6UXMlqcY33-lTzWTXMu0g.png" /></figure><h3>4. Set Up the XGBoost Training Job</h3><ul><li>Paste the below code in new cell and Click Run</li></ul><pre>from sagemaker import image_uris<br>from sagemaker.estimator import Estimator<br><br>xgboost_image_uri = image_uris.retrieve(&quot;xgboost&quot;, region=session.boto_region_name, version=&quot;1.3-1&quot;)<br><br>xgb = Estimator(<br>    image_uri=xgboost_image_uri,<br>    role=sagemaker.get_execution_role(),<br>    instance_count=1,<br>    instance_type=&#39;ml.m5.large&#39;,<br>    output_path=f&#39;s3://cybersecurity-ml-data1/xgboost-model-output&#39;,<br>    sagemaker_session=session<br>)<br><br>xgb.set_hyperparameters(<br>    objective=&#39;binary:logistic&#39;,<br>    num_round=100,<br>    max_depth=5,<br>    eta=0.2,<br>    gamma=4,<br>    min_child_weight=6,<br>    subsample=0.8,<br>    verbosity=1<br>)</pre><p>This code configures an XGBoost estimator in SageMaker by retrieving the appropriate container image, setting training resources and output path, and specifying hyperparameters for a binary classification task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xptoiDDfnN4pf2Mh1siXg.png" /></figure><h3>5. Train the Model</h3><ul><li>Paste the below code in new cell and Click Run</li></ul><pre># Train using data channels<br>xgb.fit({&#39;train&#39;: train_input, &#39;validation&#39;: test_input})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7VbiKfV3DlEixMWlqbu_w.png" /></figure><h3>6. Evaluate Model Performance</h3><ul><li>- Once training is complete, we’ll download the trained model, make predictions on test data, and calculate accuracy.</li><li>- Firstly we need to install `<strong><em>xgboost</em></strong>` Python package.</li></ul><pre> !pip install xgboost</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNfVVwqUvJbnk6WU9CNhhg.png" /></figure><ul><li>Paste the below code in new cell and Click <strong>Run</strong></li></ul><pre>import pandas as pd<br>import xgboost as xgb<br>from sklearn.metrics import accuracy_score, classification_report<br><br># Load and convert data<br>train_data = pd.read_csv(&#39;train.csv&#39;, header=None, dtype=str)<br>test_data = pd.read_csv(&#39;test.csv&#39;, header=None, dtype=str)<br><br># Convert all columns to numeric<br>train_data = train_data.apply(pd.to_numeric, errors=&#39;coerce&#39;)<br>test_data = test_data.apply(pd.to_numeric, errors=&#39;coerce&#39;)<br><br># Drop any rows with NaNs<br>train_data = train_data.dropna()<br>test_data = test_data.dropna()<br><br># Split into features (X) and labels (y)<br>X_train = train_data.iloc[:, 1:]<br>y_train = train_data.iloc[:, 0]<br>X_test = test_data.iloc[:, 1:]<br>y_test = test_data.iloc[:, 0]<br><br># Convert to DMatrix format<br>dtrain = xgb.DMatrix(X_train, label=y_train)<br>dtest = xgb.DMatrix(X_test)<br><br># Set parameters and train the model<br>params = {<br>    &quot;objective&quot;: &quot;binary:logistic&quot;,<br>    &quot;max_depth&quot;: 5,<br>    &quot;eta&quot;: 0.2,<br>    &quot;gamma&quot;: 4,<br>    &quot;min_child_weight&quot;: 6,<br>    &quot;subsample&quot;: 0.8,<br>    &quot;verbosity&quot;: 1<br>}<br><br>model = xgb.train(params=params, dtrain=dtrain, num_boost_round=100)<br><br># Predict<br>y_pred_prob = model.predict(dtest)<br>y_pred = [1 if p &gt; 0.5 else 0 for p in y_pred_prob]<br><br># Evaluate<br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))<br>print(&quot;Classification Report:\n&quot;, classification_report(y_test, y_pred))</pre><p>This code trains an <strong>XGBoost</strong> model locally using the same parameters as the <strong>SageMaker</strong> model and evaluates its performance on the test set by computing <strong>accuracy</strong> and a <strong>classification</strong> <strong>report</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*pkOeORhI2m0_KeecUMLNZQ.png" /></figure><h3>4.4 Deploy and Serve the Model</h3><p>To deploy the trained model on <strong>Amazon SageMaker</strong> and expose it as an API endpoint for real-time cybersecurity threat detection.</p><h3>STEPS TO BE PERFORMED:</h3><p>1. Create a SageMaker Model from the Trained Model Artifact</p><p>2. Deploy the Model as a SageMaker Endpoint</p><p>3. Test the Deployed Endpoint</p><h3>1. Create a SageMaker Model from the Trained Model Artifact</h3><ul><li>Before deployment, we register the trained model in <strong>SageMaker</strong>.</li><li>Paste the below code in new cell and Click <strong>Run</strong>.</li></ul><pre>import boto3<br>from sagemaker import image_uris<br><br>sagemaker_client = boto3.client(&quot;sagemaker&quot;)<br>region = &quot;us-east-1&quot;<br>bucket_name = &quot;cybersecurity-ml-data1&quot;<br>model_artifact = f&quot;s3://cybersecurity-ml-data1/xgboost-model-output/sagemaker-xgboost-2025-05-21-08-48-39-127/output/model.tar.gz&quot;<br>model_name = &quot;cybersecurity-threat-xgboost&quot;<br><br># Get XGBoost image URI<br>image_uri = image_uris.retrieve(&quot;xgboost&quot;, region=region, version=&quot;1.3-1&quot;)<br><br># Use actual IAM Role ARN<br>execution_role = &quot;arn:aws:iam::252366102382:role/SageMakerCybersecurityRole&quot;<br><br># Register the model<br>response = sagemaker_client.create_model(<br>    ModelName=model_name,<br>    PrimaryContainer={<br>        &quot;Image&quot;: image_uri,<br>        &quot;ModelDataUrl&quot;: model_artifact<br>    },<br>    ExecutionRoleArn=execution_role<br>)<br><br>print(f&quot;Model {model_name} registered successfully in SageMaker!&quot;)</pre><ul><li>Replace the placeholders in the code below:</li><li><strong><em>`&lt;bucket-name&gt;`</em></strong>: Name of your S3 bucket where the model is stored. Eg- cybersecurity-ml-data1</li><li><strong><em>`&lt;training-job-name&gt;`:</em></strong> Name of your SageMaker training job.</li><li>You can find these in the SageMaker Console under “<strong>Training jobs</strong>” and in the job’s output section.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqwwSTBA4jag97ioN8CaMg.png" /></figure><ul><li>Set Your <strong>SageMaker Execution Role</strong></li><li>Find this in the AWS IAM Console under “<strong>Roles</strong>”. Look for a role with <strong><em>SageMakerCyberSecurityRole</em></strong>” in the name, and copy the full ARN.</li></ul><p>You will receive this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOBZiYHw6v-tiDf11VuVYQ.png" /></figure><h3>2. Deploy the Model as a SageMaker Endpoint</h3><ul><li>We now create a real-time endpoint that applications can call for cybersecurity threat detection.</li><li>Paste the below code in new cell and Click Run.</li></ul><pre># Define model name if not already defined<br>model_name = &quot;cybersecurity-threat-xgboost&quot;<br><br># Define endpoint configuration<br>endpoint_config_name = &quot;cybersecurity-threat-config&quot;<br><br>sagemaker_client.create_endpoint_config(<br>    EndpointConfigName=endpoint_config_name,<br>    ProductionVariants=[<br>        {<br>            &quot;VariantName&quot;: &quot;DefaultVariant&quot;,<br>            &quot;ModelName&quot;: model_name,<br>            &quot;InstanceType&quot;: &quot;ml.m5.large&quot;,<br>            &quot;InitialInstanceCount&quot;: 1,<br>            &quot;InitialVariantWeight&quot;: 1<br>        }<br>    ]<br>)<br><br># Deploy endpoint<br>endpoint_name = &quot;cybersecurity-threat-endpoint&quot;<br><br>sagemaker_client.create_endpoint(<br>    EndpointName=endpoint_name,<br>    EndpointConfigName=endpoint_config_name<br>)<br><br>print(f&quot;Endpoint &#39;{endpoint_name}&#39; is being deployed. This may take a few minutes...&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*SLi2MSeY6RFu7f5lyJmcjA.png" /></figure><h3>3. Test the Deployed Endpoint</h3><ul><li>Once the endpoint is active, we send a sample request to check if it correctly detects threats.</li></ul><pre>import boto3<br>import numpy as np<br><br>runtime_client = boto3.client(&quot;sagemaker-runtime&quot;)<br><br># Sample input in CSV format<br>sample_input = &quot;0.5,0.3,0.8,0.2,0.1,0.6,0.9,0.4&quot;<br><br># Invoke the endpoint<br>response = runtime_client.invoke_endpoint(<br>    EndpointName=&quot;cybersecurity-threat-endpoint&quot;,  # or use endpoint_name if defined<br>    ContentType=&quot;text/csv&quot;,<br>    Body=sample_input<br>)<br><br># Get prediction from response<br>result = response[&quot;Body&quot;].read().decode(&quot;utf-8&quot;)<br>prediction_score = float(result.strip())<br><br># Interpret prediction<br>predicted_label = &quot;THREAT&quot; if prediction_score &gt; 0.5 else &quot;SAFE&quot;<br><br>print(f&quot;Prediction: {predicted_label}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mKMOpVM9qurGZooFZJ8RA.png" /></figure><h3>3.5 Automating with SageMaker Pipelines</h3><p>This step connects all the earlier parts of our project into one automated, production-grade ML workflow. It automates the entire machine learning workflow, including <strong>data preprocessing, training, evaluation, </strong>and<strong> deployment </strong>using <strong>Amazon SageMaker Pipelines.</strong></p><p>It transitions our project from: Manual development/testing to Automated pipeline orchestration using<strong> Amazon SageMaker Pipelines, Lambda, </strong>and<strong> EventBridge.</strong></p><p><strong>What is Amazon SageMaker Pipelines?</strong></p><p>Amazon SageMaker Pipelines is a workflow automation tool that helps:</p><ul><li>Streamline data preprocessing, model training, and deployment.</li><li>Maintain version control for models.</li><li>Automate model retraining when new data arrives.</li></ul><h3>STEPS TO BE PERFORMED:</h3><p>1. Define the SageMaker Pipeline Workflow</p><p>2. Create a SageMaker Pipeline Definition</p><p>3. Trigger the Pipeline Execution</p><p>4. Automate Retraining with AWS EventBridge’</p><p>5. Test the Automation</p><h3>1. Define the SageMaker Pipeline Workflow</h3><p><strong>Steps in Our ML Pipeline</strong></p><ul><li><strong>Data Processing Step</strong> → Load &amp; preprocess raw data (S3 storage).</li><li><strong>Training Step</strong> → Train XGBoost model on preprocessed data.</li><li><strong>Evaluation Step </strong>→ Check model performance (Accuracy, F1-score).</li><li><strong>Conditional Deployment Step</strong> → Deploy the model only if it meets accuracy requirements.</li></ul><h3>2. Create a SageMaker Pipeline Definition</h3><ul><li>We define a pipeline that includes <strong>data preprocessing, training, evaluation, and deployment.</strong></li><li>Paste the below code in the notebook for Automated SageMaker pipeline and click <strong>Run</strong></li></ul><pre># SageMaker Pipeline<br>import boto3<br>import sagemaker<br>from sagemaker.workflow.pipeline import Pipeline<br>from sagemaker.workflow.steps import TrainingStep<br>from sagemaker.workflow.parameters import ParameterString<br>from sagemaker.inputs import TrainingInput<br>from sagemaker import image_uris<br><br># Setup<br>session = sagemaker.Session()<br>role = sagemaker.get_execution_role()<br>bucket = &#39;cybersecurity-ml-data1&#39;<br><br># Parameters<br>training_instance_type = ParameterString(<br>    name=&quot;TrainingInstanceType&quot;, <br>    default_value=&quot;ml.m5.large&quot;<br>)<br><br># Use built-in XGBoost (same as your step 3.3)<br>xgb_estimator = sagemaker.estimator.Estimator(<br>    image_uri=image_uris.retrieve(&quot;xgboost&quot;, session.boto_region_name, version=&quot;1.3-1&quot;),<br>    role=role,<br>    instance_count=1,<br>    instance_type=training_instance_type,<br>    output_path=f&#39;s3://{bucket}/pipeline-model-output/&#39;,<br>    hyperparameters={<br>        &#39;objective&#39;: &#39;binary:logistic&#39;,<br>        &#39;num_round&#39;: 100,<br>        &#39;max_depth&#39;: 5,<br>        &#39;eta&#39;: 0.2,<br>        &#39;gamma&#39;: 4,<br>        &#39;min_child_weight&#39;: 6,<br>        &#39;subsample&#39;: 0.8,<br>        &#39;verbosity&#39;: 1<br>    }<br>)<br><br># Training Step<br>step_train = TrainingStep(<br>    name=&quot;TrainCybersecurityModel&quot;,<br>    estimator=xgb_estimator,<br>    inputs={<br>        &quot;train&quot;: TrainingInput(<br>            s3_data=f&#39;s3://{bucket}/xgboost-data/train/train.libsvm&#39;,<br>            content_type=&quot;text/libsvm&quot;<br>        ),<br>        &quot;validation&quot;: TrainingInput(<br>            s3_data=f&#39;s3://{bucket}/xgboost-data/test/test.libsvm&#39;,<br>            content_type=&quot;text/libsvm&quot;<br>        )<br>    }<br>)<br><br># Create Pipeline<br>pipeline = Pipeline(<br>    name=&quot;simple-cybersecurity-pipeline&quot;,<br>    parameters=[training_instance_type],<br>    steps=[step_train],<br>    sagemaker_session=session,<br>)<br><br># Run Pipeline<br>def run_pipeline():<br>    pipeline.upsert(role_arn=role)<br>    print(&quot;Pipeline created successfully!&quot;)<br>    <br>    execution = pipeline.start()<br>    print(f&quot;Pipeline execution started: {execution.arn}&quot;)<br>    return execution<br><br>print(&quot;Automated pipeline ready! Run: execution = run_pipeline()&quot;)</pre><ul><li>This pipeline automates the machine learning workflow for cybersecurity threat detection by creating a reusable, one-click training process</li></ul><h3>What the Pipeline Does:</h3><ul><li><strong>Automated Training:</strong> Automatically trains the XGBoost model using your preprocessed cybersecurity data from S3, eliminating the need to manually run training jobs.</li><li><strong>Consistent Results: </strong>Ensures the same hyperparameters and data sources are used every time, providing reproducible model training.</li><li><strong>Parameterized Workflow: </strong>Allows easy modification of training instance types and other parameters without changing the core pipeline code.</li><li><strong>Scalable Process: </strong>Can be easily re-run when new threat data becomes available, enabling continuous model updates as cybersecurity patterns evolve.</li></ul><h3>3. Trigger the Pipeline Execution</h3><ul><li>Once the pipeline is defined, we trigger execution to run the entire workflow in the next cell:</li></ul><pre>execution = run_pipeline()<br>print(&quot;SageMaker Pipeline Execution Started!&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDmIW6nlTYvM0eAmc2saSQ.png" /></figure><ul><li>Check status in another cell:</li></ul><pre>status = execution.describe()[&#39;PipelineExecutionStatus&#39;]<br>print(f&quot;Pipeline Status: {status}&quot;)</pre><h3>4. Automate Retraining with AWS EventBridge</h3><h3>Create Lambda Function First</h3><ul><li>Go to AWS Lambda Console → Click “<strong>Create function</strong>”</li><li>Function name: `<strong><em>trigger-cybersecurity-pipeline</em></strong>`</li><li>Runtime: <strong><em>Python 3.9</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYLuxv88wzBRuUGe3udp-A.png" /></figure><p><strong>Execution role</strong>: Create new role with basic Lambda permissions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K76is0tMN3idVvxyh6gUlQ.png" /></figure><ul><li>Click <strong>Create function</strong></li><li>Replace the default code with below and Deploy</li></ul><pre>import json<br>import boto3<br><br>def lambda_handler(event, context):<br># Initialize SageMaker client<br>    sagemaker_client = boto3.client(&quot;sagemaker&quot;)<br><br>    try:<br># Start your pipeline<br>        response = sagemaker_client.start_pipeline_execution(<br>            PipelineName=&quot;simple-cybersecurity-pipeline&quot;# Your pipeline name<br>        )<br><br>        print(f&quot;Pipeline started: {response[&#39;PipelineExecutionArn&#39;]}&quot;)<br><br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({<br>                &quot;message&quot;: &quot;Pipeline execution started successfully&quot;,<br>                &quot;executionArn&quot;: response[&#39;PipelineExecutionArn&#39;]<br>            })<br>        }<br><br>    except Exception as e:<br>        print(f&quot;Error: {str(e)}&quot;)<br>        return {<br>            &quot;statusCode&quot;: 500,<br>            &quot;body&quot;: json.dumps(f&quot;Error starting pipeline: {str(e)}&quot;)<br>        }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQpfmbaCnpOclLhlJ2dGXw.png" /></figure><h3>Add SageMaker permissions to Lambda</h3><ul><li>Go to <strong>Configuration → Permissions</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*oczzlvhDlwlxXeLOzX9FOQ.png" /></figure><ul><li>Click on the execution role name</li><li>Attach policies → Add `<strong><em>AmazonSageMakerFullAccess</em></strong>`</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMhvH0Juwlp6hvVBZCeG5A.png" /></figure><h3>Create EventBridge Rule</h3><ul><li>Go to <strong>AWS EventBridge Console → Rules → Create rule</strong></li><li>Name: `<strong><em>cybersecurity-data-trigger</em></strong>`<br> — Event bus: <strong><em>default</em></strong><br> — Rule type: <strong><em>Rule with an event pattern → Custom pattern</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJa5l5m3gh5rWvdSMMn_RA.png" /></figure><ul><li>Event pattern:</li></ul><pre>{<br>  &quot;source&quot;: [&quot;aws.s3&quot;],<br>  &quot;detail-type&quot;: [&quot;Object Created&quot;],<br>  &quot;detail&quot;: {<br>    &quot;bucket&quot;: {<br>      &quot;name&quot;: [&quot;cybersecurity-ml-data1&quot;]<br>    },<br>    &quot;object&quot;: {<br>      &quot;key&quot;: [{<br>        &quot;prefix&quot;: &quot;new-data/&quot;<br>      }]<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vj5Wm8MG_uPw2GyH9pTUlA.png" /></figure><ul><li>Target:</li><li>Target type: <strong><em>AWS service</em></strong><br> — Select a target: <strong><em>Lambda function</em></strong><br> — Function: `<strong><em>trigger-cybersecurity-pipeline</em></strong>`</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-_jpmHc7TqBvSGKqHhjQg.png" /></figure><ul><li>Leave other settings as <strong>default</strong>.</li><li>Click <strong>Next → Review → Create rule</strong></li></ul><h3>5. Test the Automation</h3><h3>Enable S3 Event Notifications</h3><ul><li>Go to your S3 bucket → Properties → Event notifications</li><li>Create event notification<br> — Name: `<strong><em>new-data-notification`</em></strong><br> — Prefix: <strong><em>`new-data/`</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*291YJ9OaBKPT6TQHbTmPDw.png" /></figure><p>Event types: Check <strong><em>All object create events</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*BEUDXyuX3erKj4zQeVYWmg.png" /></figure><p>Destination: <strong>Lambda</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8p-gsZzdShzkzwcO63RQA.png" /></figure><h3>Test the Setup</h3><ul><li>Create a test file in your notebook:</li></ul><pre># Test automation<br>import boto3<br><br>s3_client = boto3.client(&#39;s3&#39;)<br><br># Upload a test file to trigger the pipeline<br>test_content = &quot;This is test data for pipeline automation&quot;<br>s3_client.put_object(<br>    Bucket=&#39;cybersecurity-ml-data1&#39;,<br>    Key=&#39;new-data/test-trigger.txt&#39;,<br>    Body=test_content<br>)<br><br>print(&quot;Test file uploaded! Check Lambda logs to see if pipeline triggered.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*QSmfs-aFcg0JMpqM8_7nqg.png" /></figure><h3>What This Automation Does:</h3><ol><li><strong>New Data Arrives</strong> → File uploaded to s3://cybersecurity-ml-data1/new-data/</li></ol><p><strong>2. S3 Notifies EventBridge </strong>→ S3 sends event to EventBridge</p><p><strong>3. EventBridge Triggers Lambda </strong>→ Lambda function receives the event</p><p>4.<strong> Lambda Starts Pipeline </strong>→ Your SageMaker pipeline begins training</p><p>5. <strong>Automatic Retraining </strong>→ Model updates without manual intervention</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DCdr2OT9iw0gMEmUqa5Wfw.png" /></figure><h3>Conclusion</h3><p>This project successfully demonstrates how to build and deploy <strong>a machine learning-based cybersecurity threat detection system</strong> using Amazon SageMaker and other AWS services. By integrating <strong>Amazon S3, Amazon SageMaker, AWS Lambda, Amazon CloudWatch, and SageMaker Pipelines</strong>, we created a robust, scalable, and automated ML pipeline capable of detecting malicious network activity in near real-time.</p><p>Key outcomes include:</p><ul><li><strong>Data preprocessing and feature engineering</strong> using Pandas and SageMaker processing jobs.</li><li><strong>Training and evaluation of an XGBoost model</strong> to classify network traffic as benign or malicious.</li><li><strong>Deployment of a real-time inference endpoint</strong> using SageMaker for live threat detection.</li><li><strong>Automation of the ML workflow via SageMaker Pipelines</strong> for consistent and repeatable model building.</li><li><strong>End-to-end integration of cloud-native services </strong>with secure, serverless infrastructure.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3bfe35e75c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud-Native Social App Deployment on AWS ECS with Terraform and GitHub Actions]]></title>
            <link>https://medium.com/@akupheaws/cloud-native-social-app-deployment-on-aws-ecs-with-terraform-and-github-actions-0ab029edffc0?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ab029edffc0</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 01:27:18 GMT</pubDate>
            <atom:updated>2026-07-07T14:46:23.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-ENuaxcQU62cXcgh7mgMA.png" /></figure><h4>This project demonstrates how to take a real web application from commit to production on AWS with zero local commands. Every push to main triggers a fully automated pipeline that builds a Docker image, stores it in <a href="https://www.cloudforgeconsult.com/">Amazon</a> ECR, provisions or updates AWS infrastructure with Terraform, deploys to Amazon ECS Fargate behind an Application Load Balancer (ALB), and finally runs a smoke test against the live URL.</h4><h4>The <a href="https://www.cloudforgeconsult.com/">app</a> used here is a social media–style Node/Express service (“SocialApp”) that persists data in DynamoDB, publishes logs to CloudWatch, and is instrumented for container health checks. The entire workflow runs in GitHub Actions; state and locking for Terraform are handled securely in S3 and DynamoDB so there’s no local testing or manual steps required.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kr5PbFtL5xQZ7Vgh_nFRUQ.png" /></figure><p>At a high level, the repository has two major pieces. The first is Terraform, which defines every AWS resource the app needs: an ECR repository, an ECS cluster and service, an ALB, task roles and policies, CloudWatch log groups, security groups, and three DynamoDB tables for users, posts, and likes. The second is a single <a href="https://www.cloudforgeconsult.com/">GitHub Actions</a> workflow that bootstraps Terraform’s backend, guarantees the ECR repo exists and is tracked by state, builds and pushes the container image, applies the Terraform plan with the new image tag, and verifies the application responds with HTTP 200 from the ALB.</p><h3>What the Terraform Files Do</h3><h3>main.tf</h3><p>This is the heart of the infrastructure. It begins by defining project-wide tags and discovering the default <a href="https://www.cloudforgeconsult.com/">VPC</a> and its subnets. It then creates three DynamoDB tables (users, posts, likes) using on-demand capacity, which keeps cost simple while the app scales. The ECR repository for the container image is defined here as well, with on-push scanning and mutable tags so the pipeline can publish a :latest and a content-addressed tag per commit.</p><p>The compute layer is <a href="https://www.cloudforgeconsult.com/">Amazon ECS</a> on Fargate. main.tf creates the ECS cluster with Container Insights enabled and defines two IAM roles: a task execution role (to pull images and write logs) and an application task role. The task role is attached to a least-privilege policy granting read/write access only to the three tables the app uses. A CloudWatch Logs group is created for application logs.</p><pre>#####################################<br># Locals<br>#####################################<br><br>locals {<br>  tags = {<br>    Project = var.project_name<br>    Env     = &quot;default&quot;<br>  }<br>}<br><br>#####################################<br># Data sources (default VPC / subnets)<br>#####################################<br><br>data &quot;aws_vpc&quot; &quot;default&quot; {<br>  default = true<br>}<br><br>data &quot;aws_subnets&quot; &quot;default_all&quot; {<br>  filter {<br>    name   = &quot;vpc-id&quot;<br>    values = [data.aws_vpc.default.id]<br>  }<br>}<br><br>#####################################<br># DynamoDB tables<br>#####################################<br><br>resource &quot;aws_dynamodb_table&quot; &quot;users&quot; {<br>  name         = &quot;${var.project_name}-users&quot;<br>  billing_mode = &quot;PAY_PER_REQUEST&quot;<br>  hash_key     = &quot;username&quot;<br><br>  attribute {<br>    name = &quot;username&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  tags = local.tags<br>}<br><br>resource &quot;aws_dynamodb_table&quot; &quot;posts&quot; {<br>  name         = &quot;${var.project_name}-posts&quot;<br>  billing_mode = &quot;PAY_PER_REQUEST&quot;<br>  hash_key     = &quot;post_id&quot;<br><br>  attribute {<br>    name = &quot;post_id&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  tags = local.tags<br>}<br><br>resource &quot;aws_dynamodb_table&quot; &quot;likes&quot; {<br>  name         = &quot;${var.project_name}-likes&quot;<br>  billing_mode = &quot;PAY_PER_REQUEST&quot;<br>  hash_key     = &quot;post_id&quot;<br>  range_key    = &quot;username&quot;<br><br>  attribute {<br>    name = &quot;post_id&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  attribute {<br>    name = &quot;username&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  tags = local.tags<br>}<br><br>#####################################<br># ECR repository<br>#####################################<br><br>resource &quot;aws_ecr_repository&quot; &quot;app&quot; {<br>  name                 = var.ecr_repo_name<br>  image_tag_mutability = &quot;MUTABLE&quot;<br><br>  image_scanning_configuration {<br>    scan_on_push = true<br>  }<br><br>  tags = local.tags<br>}<br><br>#####################################<br># CloudWatch Logs<br>#####################################<br><br>resource &quot;aws_cloudwatch_log_group&quot; &quot;app&quot; {<br>  name              = &quot;/ecs/${var.project_name}&quot;<br>  retention_in_days = 14<br>  tags              = local.tags<br>}<br><br>#####################################<br># ECS cluster<br>#####################################<br><br>resource &quot;aws_ecs_cluster&quot; &quot;this&quot; {<br>  name = &quot;${var.project_name}-cluster&quot;<br><br>  setting {<br>    name  = &quot;containerInsights&quot;<br>    value = &quot;enabled&quot;<br>  }<br><br>  tags = local.tags<br>}<br><br>#####################################<br># IAM (task exec role, task role, DDB policy)<br>#####################################<br><br>data &quot;aws_iam_policy_document&quot; &quot;assume_task&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;ecs-tasks.amazonaws.com&quot;]<br>    }<br><br>    actions = [&quot;sts:AssumeRole&quot;]<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;task_execution&quot; {<br>  name               = &quot;${var.project_name}-task-exec&quot;<br>  assume_role_policy = data.aws_iam_policy_document.assume_task.json<br>  tags               = local.tags<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;task_exec_attach&quot; {<br>  role       = aws_iam_role.task_execution.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy&quot;<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;task&quot; {<br>  name               = &quot;${var.project_name}-task-role&quot;<br>  assume_role_policy = data.aws_iam_policy_document.assume_task.json<br>  tags               = local.tags<br>}<br><br># Task role → DynamoDB RW<br>data &quot;aws_iam_policy_document&quot; &quot;ddb_rw&quot; {<br>  statement {<br>    sid    = &quot;DDBRW&quot;<br>    effect = &quot;Allow&quot;<br><br>    actions = [<br>      &quot;dynamodb:GetItem&quot;,<br>      &quot;dynamodb:PutItem&quot;,<br>      &quot;dynamodb:UpdateItem&quot;,<br>      &quot;dynamodb:DeleteItem&quot;,<br>      &quot;dynamodb:Scan&quot;,<br>      &quot;dynamodb:Query&quot;,<br>      &quot;dynamodb:DescribeTable&quot;<br>    ]<br><br>    resources = [<br>      aws_dynamodb_table.users.arn,<br>      aws_dynamodb_table.posts.arn,<br>      aws_dynamodb_table.likes.arn<br>    ]<br>  }<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;ddb_rw&quot; {<br>  name   = &quot;${var.project_name}-ddb-rw&quot;<br>  policy = data.aws_iam_policy_document.ddb_rw.json<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;task_ddb_attach&quot; {<br>  role       = aws_iam_role.task.name<br>  policy_arn = aws_iam_policy.ddb_rw.arn<br>}<br><br>#####################################<br># ECS task definition<br>#####################################<br><br>resource &quot;aws_ecs_task_definition&quot; &quot;app&quot; {<br>  family                   = &quot;${var.project_name}-task&quot;<br>  cpu                      = var.cpu<br>  memory                   = var.memory<br>  network_mode             = &quot;awsvpc&quot;<br>  requires_compatibilities = [&quot;FARGATE&quot;]<br>  execution_role_arn       = aws_iam_role.task_execution.arn<br>  task_role_arn            = aws_iam_role.task.arn<br><br>  runtime_platform {<br>    operating_system_family = &quot;LINUX&quot;<br>    cpu_architecture        = &quot;X86_64&quot;<br>  }<br><br>  container_definitions = jsonencode([<br>    {<br>      name  = &quot;app&quot;<br>      image = &quot;${aws_ecr_repository.app.repository_url}:${var.image_tag}&quot;<br><br>      essential = true<br><br>      portMappings = [<br>        {<br>          containerPort = var.container_port<br>          protocol      = &quot;tcp&quot;<br>        }<br>      ]<br><br>      environment = [<br>        { name = &quot;AWS_REGION&quot;,     value = var.region },<br>        { name = &quot;APP_NAME&quot;,       value = var.project_name },<br>        { name = &quot;TABLE_USERS&quot;,    value = aws_dynamodb_table.users.name },<br>        { name = &quot;TABLE_POSTS&quot;,    value = aws_dynamodb_table.posts.name },<br>        { name = &quot;TABLE_LIKES&quot;,    value = aws_dynamodb_table.likes.name },<br>        { name = &quot;SESSION_SECRET&quot;, value = var.session_secret }<br>      ]<br><br>      logConfiguration = {<br>        logDriver = &quot;awslogs&quot;<br>        options = {<br>          awslogs-group         = aws_cloudwatch_log_group.app.name<br>          awslogs-region        = var.region<br>          awslogs-stream-prefix = &quot;app&quot;<br>        }<br>      }<br><br>      healthCheck = {<br>        command     = [&quot;CMD-SHELL&quot;, &quot;wget -qO- http://localhost:${var.container_port}/healthz || exit 1&quot;]<br>        interval    = 30<br>        timeout     = 5<br>        retries     = 3<br>        startPeriod = 10<br>      }<br>    }<br>  ])<br><br>  tags = local.tags<br>}<br><br>#####################################<br># Security groups<br>#####################################<br><br>resource &quot;aws_security_group&quot; &quot;alb&quot; {<br>  name   = &quot;${var.project_name}-alb-sg&quot;<br>  vpc_id = data.aws_vpc.default.id<br><br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><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>  tags = local.tags<br>}<br><br>resource &quot;aws_security_group&quot; &quot;tasks&quot; {<br>  name   = &quot;${var.project_name}-tasks-sg&quot;<br>  vpc_id = data.aws_vpc.default.id<br><br>  ingress {<br>    from_port       = var.container_port<br>    to_port         = var.container_port<br>    protocol        = &quot;tcp&quot;<br>    security_groups = [aws_security_group.alb.id]<br>  }<br><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>  tags = local.tags<br>}<br><br>#####################################<br># ALB + Target group + Listener<br>#####################################<br><br>resource &quot;aws_lb&quot; &quot;app&quot; {<br>  name               = &quot;${var.project_name}-alb&quot;<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [aws_security_group.alb.id]<br>  subnets            = data.aws_subnets.default_all.ids<br>  tags               = local.tags<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;app&quot; {<br>  name        = &quot;${var.project_name}-tg&quot;<br>  port        = var.container_port<br>  protocol    = &quot;HTTP&quot;<br>  target_type = &quot;ip&quot;<br>  vpc_id      = data.aws_vpc.default.id<br><br>  health_check {<br>    path                = &quot;/healthz&quot;<br>    matcher             = &quot;200&quot;<br>    interval            = 30<br>    timeout             = 5<br>    healthy_threshold   = 2<br>    unhealthy_threshold = 5<br>  }<br><br>  tags = local.tags<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;http&quot; {<br>  load_balancer_arn = aws_lb.app.arn<br>  port              = 80<br>  protocol          = &quot;HTTP&quot;<br><br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.app.arn<br>  }<br>}<br><br>#####################################<br># ECS service<br>#####################################<br><br>resource &quot;aws_ecs_service&quot; &quot;app&quot; {<br>  name            = &quot;${var.project_name}-svc&quot;<br>  cluster         = aws_ecs_cluster.this.id<br>  task_definition = aws_ecs_task_definition.app.arn<br>  desired_count   = var.desired_count<br>  launch_type     = &quot;FARGATE&quot;<br><br>  network_configuration {<br>    assign_public_ip = true<br>    subnets          = data.aws_subnets.default_all.ids<br>    security_groups  = [aws_security_group.tasks.id]<br>  }<br><br>  load_balancer {<br>    target_group_arn = aws_lb_target_group.app.arn<br>    container_name   = &quot;app&quot;<br>    container_port   = var.container_port<br>  }<br><br>  lifecycle {<br>    ignore_changes = [task_definition]<br>  }<br><br>  depends_on = [aws_lb_listener.http]<br>  tags       = local.tags<br>}</pre><p>Networking is handled by two security groups and an internet-facing ALB across the default subnets. The ALB accepts HTTP/80 from the world and forwards to a target group that does health checks on /healthz. The service tasks run with awsvpc networking in their own security group and only allow traffic from the ALB. Finally, the ECS task definition wires everything up: the container image reference from ECR (tag provided by the pipeline), container port, health check command, and environment variables such as table names, region, and a session secret. An ECS service attaches the task to the <a href="https://www.cloudforgeconsult.com/">ALB</a> target group, requests a desired count, and opts into Fargate launch type so you don’t manage servers.</p><h3>outputs.tf</h3><p>This file exposes the values you need after apply. The most important output is the ALB’s DNS name, which the pipeline uses to run a smoke test and which you can paste directly into a browser. It also outputs the ECR repository URL for reference.</p><pre>output &quot;alb_dns_name&quot;       { value = aws_lb.app.dns_name }<br>output &quot;ecr_repository_url&quot; { value = aws_ecr_repository.app.repository_url }<br>output &quot;users_table&quot;        { value = aws_dynamodb_table.users.name }<br>output &quot;posts_table&quot;        { value = aws_dynamodb_table.posts.name }<br>output &quot;likes_table&quot;        { value = aws_dynamodb_table.likes.name }</pre><h3>variables.tf</h3><p>This file collects all configuration knobs used by the stack so they can be passed in by the pipeline and kept out of code. You’ll see variables for project_name, region, ecr_repo_name, the image_tag to deploy, container sizing such as cpu, memory, and desired_count, networking such as container_port, and sensitive settings such as session_secret. Sensible defaults are provided, but the pipeline overrides the values that must change per deploy (like the image tag).</p><pre>variable &quot;project_name&quot; {<br>  description = &quot;Name prefix for AWS resources (cluster, ALB, tables, etc.).&quot;<br>  type        = string<br>  default     = &quot;socialapp&quot;<br>}<br><br>variable &quot;region&quot; {<br>  description = &quot;AWS region to deploy into.&quot;<br>  type        = string<br>  default     = &quot;us-east-1&quot;<br>}<br><br>variable &quot;image_tag&quot; {<br>  description = &quot;Container image tag to deploy (CI sets this to the commit SHA).&quot;<br>  type        = string<br>  default     = &quot;bootstrap&quot;<br>}<br><br>variable &quot;container_port&quot; {<br>  description = &quot;Container port exposed by the app and targeted by the ALB.&quot;<br>  type        = number<br>  default     = 8000<br><br>  validation {<br>    condition     = var.container_port &gt; 0 &amp;&amp; var.container_port &lt; 65536<br>    error_message = &quot;container_port must be between 1 and 65535.&quot;<br>  }<br>}<br><br>variable &quot;desired_count&quot; {<br>  description = &quot;Number of ECS tasks to run.&quot;<br>  type        = number<br>  default     = 1<br><br>  validation {<br>    condition     = var.desired_count &gt;= 1<br>    error_message = &quot;desired_count must be at least 1.&quot;<br>  }<br>}<br><br>variable &quot;cpu&quot; {<br>  description = &quot;Fargate vCPU units for the task (e.g., 256, 512, 1024...).&quot;<br>  type        = number<br>  default     = 256<br>}<br><br>variable &quot;memory&quot; {<br>  description = &quot;Fargate memory (MB) for the task (e.g., 512, 1024, 2048...).&quot;<br>  type        = number<br>  default     = 512<br>}<br><br>variable &quot;ecr_repo_name&quot; {<br>  description = &quot;ECR repository name for the application image.&quot;<br>  type        = string<br>  default     = &quot;socialapp&quot;<br>}<br><br>variable &quot;session_secret&quot; {<br>  description = &quot;Secret used to sign sessions in the app&quot;<br>  type        = string<br>  default     = &quot;change-me-in-prod&quot; # overridden by SOCIAlAPP_SESSION_SECRET in CI<br>}<br><br></pre><h3>versions.tf</h3><p>This pin file ensures Terraform uses compatible provider and CLI versions. It declares the AWS provider and the minimum Terraform core version the configuration supports. Pinning versions makes the pipeline deterministic and prevents surprise provider changes from breaking your deploy.</p><pre>terraform {<br>  required_version = &quot;&gt;= 1.6.0&quot;<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;placeholder-bucket&quot;<br>    key            = &quot;placeholder.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>    dynamodb_table = &quot;placeholder-locks&quot;<br>    encrypt        = true<br>  }<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.53&quot;<br>    }<br>  }<br>}<br>provider &quot;aws&quot; { region = var.region }</pre><h3>What the deploy.yml GitHub Action Does</h3><p>The workflow is designed to run entirely in CI and to be idempotent. It first bootstraps the Terraform backend by creating a versioned, encrypted S3 bucket (with public access blocked) and a DynamoDB lock table if they don’t already exist. It then ensures the ECR repository for the app exists and is imported into Terraform state even if it was created outside of Terraform or renamed. Next, the job builds a Docker image from the repository’s Dockerfile, logs in to ECR, and pushes both a commit-specific tag and latest. After the image is published, the pipeline runs terraform plan and terraform apply with the new tag, which updates the ECS task definition and causes ECS to roll out a new Fargate deployment via the ALB. Finally, a smoke test step resolves the ALB’s DNS name and curls it until it returns HTTP 200, failing the run if the service never becomes healthy.</p><pre>name: Deploy (SocialApp • Root Dockerfile &amp; Context + Robust ECR + Deterministic npm ci)<br><br>on:<br>  push:<br>    branches: [&quot;main&quot;]<br>  workflow_dispatch:<br><br>env:<br>  AWS_REGION: ${{ secrets.AWS_REGION }}<br>  PROJECT_NAME: socialapp<br>  TF_STATE_KEY: terraform-socialapp.tfstate<br>  DOCKERFILE: Dockerfile<br>  BUILD_CONTEXT: .<br>  ECR_REPO_NAME: socialapp<br>  LOCK_TABLE_NAME: tf-locks<br><br>concurrency:<br>  group: deploy-socialapp<br>  cancel-in-progress: false<br><br>defaults:<br>  run:<br>    shell: bash<br><br>jobs:<br>  bootstrap_state:<br>    name: Bootstrap backend (S3 + DynamoDB)<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: read<br>    steps:<br>      - name: Configure AWS (access keys)<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_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Compute valid bucket name<br>        id: bk<br>        run: |<br>          REPO_SLUG=&quot;${{ github.repository }}&quot;<br>          SLUG_LOWER=$(echo &quot;$REPO_SLUG&quot; | tr &#39;[:upper:]&#39; &#39;[:lower:]&#39;)<br>          BASE=$(echo &quot;$SLUG_LOWER&quot; | sed -E &#39;s/[^a-z0-9-]/-/g; s/-+/-/g; s/^-+//; s/-+$//&#39;)<br>          BASE=${BASE:0:32}<br>          ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)<br>          SUFFIX=$(printf &#39;%s&#39; &quot;$SLUG_LOWER&quot; | sha1sum | cut -c1-8)<br>          BUCKET=&quot;${BASE}-${ACCOUNT_ID}-${SUFFIX}-tf&quot;<br>          BUCKET=$(echo &quot;$BUCKET&quot; | sed -E &#39;s/^-+//; s/-+$//&#39;)<br>          test -n &quot;$BUCKET&quot; || { echo &quot;Bucket empty&quot;; exit 1; }<br>          echo &quot;bucket_name=$BUCKET&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>          echo &quot;Bucket: $BUCKET (len=$(echo -n $BUCKET | wc -c))&quot;<br><br>      - name: Create S3 bucket (if missing)<br>        env:<br>          BUCKET: ${{ steps.bk.outputs.bucket_name }}<br>        run: |<br>          if ! aws s3api head-bucket --bucket &quot;$BUCKET&quot; 2&gt;/dev/null; then<br>            if [ &quot;$AWS_REGION&quot; = &quot;us-east-1&quot; ]; then<br>              aws s3api create-bucket --bucket &quot;$BUCKET&quot;<br>            else<br>              aws s3api create-bucket --bucket &quot;$BUCKET&quot; --region &quot;$AWS_REGION&quot; \<br>                --create-bucket-configuration LocationConstraint=&quot;$AWS_REGION&quot;<br>            fi<br>            aws s3api put-bucket-versioning --bucket &quot;$BUCKET&quot; --versioning-configuration Status=Enabled<br>            aws s3api put-bucket-encryption --bucket &quot;$BUCKET&quot; --server-side-encryption-configuration &#39;{<br>              &quot;Rules&quot;:[{&quot;ApplyServerSideEncryptionByDefault&quot;:{&quot;SSEAlgorithm&quot;:&quot;AES256&quot;}}]}&#39;<br>            aws s3api put-public-access-block --bucket &quot;$BUCKET&quot; --public-access-block-configuration &#39;{<br>              &quot;BlockPublicAcls&quot;:true,&quot;IgnorePublicAcls&quot;:true,&quot;BlockPublicPolicy&quot;:true,&quot;RestrictPublicBuckets&quot;:true}&#39;<br>          fi<br><br>      - name: Create DynamoDB lock table (if missing)<br>        run: |<br>          if ! aws dynamodb describe-table --table-name &quot;${LOCK_TABLE_NAME}&quot; &gt;/dev/null 2&gt;&amp;1; then<br>            aws dynamodb create-table --table-name &quot;${LOCK_TABLE_NAME}&quot; \<br>              --attribute-definitions AttributeName=LockID,AttributeType=S \<br>              --key-schema AttributeName=LockID,KeyType=HASH \<br>              --billing-mode PAY_PER_REQUEST<br>            aws dynamodb wait table-exists --table-name &quot;${LOCK_TABLE_NAME}&quot;<br>          fi<br><br>    outputs:<br>      tf_bucket: ${{ steps.bk.outputs.bucket_name }}<br><br>  seed_ecr:<br>    name: Ensure ECR exists (robust create/import with rename handling)<br>    runs-on: ubuntu-latest<br>    needs: bootstrap_state<br>    permissions:<br>      contents: read<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Configure AWS<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_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Compute valid bucket name (this job)<br>        id: bk<br>        run: |<br>          REPO_SLUG=&quot;${{ github.repository }}&quot;<br>          SLUG_LOWER=$(echo &quot;$REPO_SLUG&quot; | tr &#39;[:upper:]&#39; &#39;[:lower:]&#39;)<br>          BASE=$(echo &quot;$SLUG_LOWER&quot; | sed -E &#39;s/[^a-z0-9-]/-/g; s/-+/-/g; s/^-+//; s/-+$//&#39;)<br>          BASE=${BASE:0:32}<br>          ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)<br>          SUFFIX=$(printf &#39;%s&#39; &quot;$SLUG_LOWER&quot; | sha1sum | cut -c1-8)<br>          BUCKET=&quot;${BASE}-${ACCOUNT_ID}-${SUFFIX}-tf&quot;<br>          BUCKET=$(echo &quot;$BUCKET&quot; | sed -E &#39;s/^-+//; s/-+$//&#39;)<br>          test -n &quot;$BUCKET&quot; || { echo &quot;Bucket empty&quot;; exit 1; }<br>          echo &quot;bucket_name=$BUCKET&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br><br>      - name: Setup Terraform<br>        uses: hashicorp/setup-terraform@v3<br>        with:<br>          terraform_version: 1.9.5<br><br>      - name: Write backend.hcl<br>        working-directory: terraform<br>        run: |<br>          cat &gt; backend.hcl &lt;&lt;EOF<br>          bucket         = &quot;${{ steps.bk.outputs.bucket_name }}&quot;<br>          key            = &quot;${{ env.TF_STATE_KEY }}&quot;<br>          region         = &quot;${{ env.AWS_REGION }}&quot;<br>          dynamodb_table = &quot;${{ env.LOCK_TABLE_NAME }}&quot;<br>          encrypt        = true<br>          EOF<br>          cat backend.hcl<br><br>      - name: Terraform Init<br>        working-directory: terraform<br>        run: terraform init -reconfigure -backend-config=backend.hcl<br><br>      - name: Ensure ECR exists and is in TF state (handle rename safely)<br>        working-directory: terraform<br>        run: |<br>          set -euo pipefail<br>          REPO=&quot;${ECR_REPO_NAME}&quot;<br><br>          # Current repo name in TF state (if any)<br>          CURR_NAME=&quot;$(terraform state show aws_ecr_repository.app 2&gt;/dev/null \<br>            | awk -F&#39;= &#39; &#39;/^ *name *=/ {gsub(/&quot;/,&quot;&quot;,$2); print $2; exit}&#39; || true)&quot;<br><br>          # 1) Ensure desired ECR repo exists<br>          if ! aws ecr describe-repositories --repository-names &quot;$REPO&quot; &gt;/dev/null 2&gt;&amp;1; then<br>            echo &quot;ECR &#39;$REPO&#39; not found; creating via AWS CLI...&quot;<br>            aws ecr create-repository --repository-name &quot;$REPO&quot; &gt;/dev/null<br>          else<br>            echo &quot;ECR &#39;$REPO&#39; already exists.&quot;<br>          fi<br><br>          # 2) Make TF state point to the desired repo (handles rename cleanly)<br>          if [ -z &quot;${CURR_NAME:-}&quot; ]; then<br>            echo &quot;No existing TF state for aws_ecr_repository.app; importing &#39;$REPO&#39;...&quot;<br>            terraform import -input=false aws_ecr_repository.app &quot;$REPO&quot;<br>          elif [ &quot;$CURR_NAME&quot; != &quot;$REPO&quot; ]; then<br>            echo &quot;TF state currently points to &#39;$CURR_NAME&#39; but desired is &#39;$REPO&#39; — re-importing...&quot;<br>            terraform import -input=false aws_ecr_repository.app &quot;$REPO&quot;<br>          else<br>            echo &quot;TF state already points to &#39;$REPO&#39;.&quot;<br>          fi<br><br>          # 3) Reconcile repo settings with HCL (no destroy/create)<br>          terraform apply -auto-approve \<br>            -target=aws_ecr_repository.app \<br>            -var &quot;region=${AWS_REGION}&quot; \<br>            -var &quot;ecr_repo_name=${ECR_REPO_NAME}&quot;<br><br>      - name: Get ECR repo URL (output or compute)<br>        id: out<br>        working-directory: terraform<br>        run: |<br>          URI=&quot;$(terraform output -raw ecr_repository_url 2&gt;/dev/null || true)&quot;<br>          if [ -z &quot;$URI&quot; ] || [ &quot;$URI&quot; = &quot;null&quot; ]; then<br>            ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)<br>            URI=&quot;${ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO_NAME}&quot;<br>          fi<br>          echo &quot;ecr_url=$URI&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>          echo &quot;ECR URL: $URI&quot;<br><br>    outputs:<br>      ecr_url: ${{ steps.out.outputs.ecr_url }}<br><br>  build_and_push:<br>    name: Build &amp; push Docker image (latest + SHA)<br>    runs-on: ubuntu-latest<br>    needs: seed_ecr<br>    permissions:<br>      contents: read<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Configure AWS<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_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Ensure Docker uses default context<br>        run: |<br>          docker context use default || true<br>          unset DOCKER_CONTEXT || true<br><br>      - name: Derive ECR registry + repo (robust)<br>        id: ecr<br>        run: |<br>          ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)<br>          REGISTRY=&quot;${ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com&quot;<br>          REPO_URL=&quot;${{ needs.seed_ecr.outputs.ecr_url }}&quot;<br>          if [ -z &quot;$REPO_URL&quot; ]; then<br>            REPO_URL=&quot;${REGISTRY}/${ECR_REPO_NAME}&quot;<br>          fi<br>          echo &quot;registry=$REGISTRY&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>          echo &quot;repo_url=$REPO_URL&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>          echo &quot;Resolved registry: $REGISTRY&quot;<br>          echo &quot;Resolved repo_url: $REPO_URL&quot;<br><br>      # Deterministic builds: generate/sync lockfile before Docker build<br>      - uses: actions/setup-node@v4<br>        with:<br>          node-version: &#39;20&#39;<br><br>      - name: Ensure package-lock.json is synced<br>        run: |<br>          npm install --package-lock-only<br><br>      - name: Login to ECR<br>        run: |<br>          aws ecr get-login-password --region &quot;$AWS_REGION&quot; \<br>            | docker login --username AWS --password-stdin &quot;${{ steps.ecr.outputs.registry }}&quot;<br><br>      - name: Locate Dockerfile &amp; context (with auto-fallback)<br>        id: locate<br>        run: |<br>          if [ -f &quot;$DOCKERFILE&quot; ] &amp;&amp; { [ -d &quot;$BUILD_CONTEXT&quot; ] || [ &quot;$BUILD_CONTEXT&quot; = &quot;.&quot; ]; }; then<br>            DF=&quot;$DOCKERFILE&quot;; CTX=&quot;$BUILD_CONTEXT&quot;<br>          else<br>            echo &quot;Configured paths not found. Auto-detecting...&quot;<br>            DF=$(git ls-files | grep -E &#39;(^|/)Dockerfile$&#39; | head -n1 || true)<br>            if [ -z &quot;$DF&quot; ]; then<br>              echo &quot;No Dockerfile found in repository.&quot; &gt;&amp;2<br>              exit 1<br>            fi<br>            CTX=$(dirname &quot;$DF&quot;)<br>            [ -z &quot;$CTX&quot; ] &amp;&amp; CTX=&quot;.&quot;<br>          fi<br>          echo &quot;dockerfile=$DF&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>          echo &quot;context=$CTX&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>          echo &quot;Using Dockerfile: $DF&quot;<br>          echo &quot;Using build context: $CTX&quot;<br><br>      - name: Build<br>        run: docker build -f &quot;${{ steps.locate.outputs.dockerfile }}&quot; -t app:${{ github.sha }} &quot;${{ steps.locate.outputs.context }}&quot;<br><br>      - name: Tag &amp; push (latest + SHA)<br>        run: |<br>          REPO=&quot;${{ steps.ecr.outputs.repo_url }}&quot;<br>          docker tag app:${{ github.sha }} &quot;$REPO&quot;:${{ github.sha }}<br>          docker tag app:${{ github.sha }} &quot;$REPO&quot;:latest<br>          docker push &quot;$REPO&quot;:${{ github.sha }}<br>          docker push &quot;$REPO&quot;:latest<br><br>  plan:<br>    name: Terraform Plan<br>    runs-on: ubuntu-latest<br>    needs: [bootstrap_state, build_and_push]<br>    permissions:<br>      contents: read<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Configure AWS<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_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Compute valid bucket name (this job)<br>        id: bk<br>        run: |<br>          REPO_SLUG=&quot;${{ github.repository }}&quot;<br>          SLUG_LOWER=$(echo &quot;$REPO_SLUG&quot; | tr &#39;[:upper:]&#39; &#39;[:lower:]&#39;)<br>          BASE=$(echo &quot;$SLUG_LOWER&quot; | sed -E &#39;s/[^a-z0-9-]/-/g; s/-+/-/g; s/^-+//; s/-+$//&#39;)<br>          BASE=${BASE:0:32}<br>          ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)<br>          SUFFIX=$(printf &#39;%s&#39; &quot;$SLUG_LOWER&quot; | sha1sum | cut -c1-8)<br>          BUCKET=&quot;${BASE}-${ACCOUNT_ID}-${SUFFIX}-tf&quot;<br>          BUCKET=$(echo &quot;$BUCKET&quot; | sed -E &#39;s/^-+//; s/-+$//&#39;)<br>          test -n &quot;$BUCKET&quot; || { echo &quot;Bucket empty&quot;; exit 1; }<br>          echo &quot;bucket_name=$BUCKET&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br><br>      - name: Setup Terraform<br>        uses: hashicorp/setup-terraform@v3<br>        with:<br>          terraform_version: 1.9.5<br><br>      - name: Write backend.hcl<br>        working-directory: terraform<br>        run: |<br>          cat &gt; backend.hcl &lt;&lt;EOF<br>          bucket         = &quot;${{ steps.bk.outputs.bucket_name }}&quot;<br>          key            = &quot;${{ env.TF_STATE_KEY }}&quot;<br>          region         = &quot;${{ env.AWS_REGION }}&quot;<br>          dynamodb_table = &quot;${{ env.LOCK_TABLE_NAME }}&quot;<br>          encrypt        = true<br>          EOF<br>          cat backend.hcl<br><br>      - name: Terraform Init<br>        working-directory: terraform<br>        run: terraform init -reconfigure -backend-config=backend.hcl<br><br>      - name: Terraform fmt &amp; validate<br>        working-directory: terraform<br>        run: |<br>          terraform fmt -recursive<br>          terraform fmt -check -recursive<br>          terraform validate<br><br>      - name: Terraform Plan (with image tag)<br>        working-directory: terraform<br>        env:<br>          TF_VAR_session_secret: ${{ secrets.SOCIALAPP_SESSION_SECRET }}<br>        run: |<br>          args=( \<br>            -var &quot;region=${AWS_REGION}&quot; \<br>            -var &quot;project_name=${PROJECT_NAME}&quot; \<br>            -var &quot;image_tag=${GITHUB_SHA}&quot; \<br>            -var &quot;ecr_repo_name=${ECR_REPO_NAME}&quot; \<br>          )<br>          if [ -n &quot;${TF_VAR_session_secret:-}&quot; ]; then<br>            args+=(-var &quot;session_secret=${TF_VAR_session_secret}&quot;)<br>          fi<br>          terraform plan &quot;${args[@]}&quot;<br><br>  apply:<br>    name: Terraform Apply (deploy)<br>    runs-on: ubuntu-latest<br>    needs: plan<br>    permissions:<br>      contents: read<br>    outputs:<br>      alb: ${{ steps.resolve.outputs.alb }}<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Configure AWS<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_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Compute valid bucket name (this job)<br>        id: bk<br>        run: |<br>          REPO_SLUG=&quot;${{ github.repository }}&quot;<br>          SLUG_LOWER=$(echo &quot;$REPO_SLUG&quot; | tr &#39;[:upper:]&#39; &#39;[:lower:]&#39;)<br>          BASE=$(echo &quot;$SLUG_LOWER&quot; | sed -E &#39;s/[^a-z0-9-]/-/g; s/-+/-/g; s/^-+//; s/-+$//&#39;)<br>          BASE=${BASE:0:32}<br>          ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)<br>          SUFFIX=$(printf &#39;%s&#39; &quot;$SLUG_LOWER&quot; | sha1sum | cut -c1-8)<br>          BUCKET=&quot;${BASE}-${ACCOUNT_ID}-${SUFFIX}-tf&quot;<br>          BUCKET=$(echo &quot;$BUCKET&quot; | sed -E &#39;s/^-+//; s/-+$//&#39;)<br>          test -n &quot;$BUCKET&quot; || { echo &quot;Bucket empty&quot;; exit 1; }<br>          echo &quot;bucket_name=$BUCKET&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br><br>      - name: Setup Terraform<br>        uses: hashicorp/setup-terraform@v3<br>        with:<br>          terraform_version: 1.9.5<br><br>      - name: Write backend.hcl<br>        working-directory: terraform<br>        run: |<br>          cat &gt; backend.hcl &lt;&lt;EOF<br>          bucket         = &quot;${{ steps.bk.outputs.bucket_name }}&quot;<br>          key            = &quot;${{ env.TF_STATE_KEY }}&quot;<br>          region         = &quot;${{ env.AWS_REGION }}&quot;<br>          dynamodb_table = &quot;${{ env.LOCK_TABLE_NAME }}&quot;<br>          encrypt        = true<br>          EOF<br>          cat backend.hcl<br><br>      - name: Terraform Init<br>        working-directory: terraform<br>        run: terraform init -reconfigure -backend-config=backend.hcl<br><br>      - name: Terraform Apply (with image tag)<br>        working-directory: terraform<br>        env:<br>          TF_VAR_session_secret: ${{ secrets.SOCIALAPP_SESSION_SECRET }}<br>        run: |<br>          args=( \<br>            -auto-approve \<br>            -var &quot;region=${AWS_REGION}&quot; \<br>            -var &quot;project_name=${PROJECT_NAME}&quot; \<br>            -var &quot;image_tag=${GITHUB_SHA}&quot; \<br>            -var &quot;ecr_repo_name=${ECR_REPO_NAME}&quot; \<br>          )<br>          if [ -n &quot;${TF_VAR_session_secret:-}&quot; ]; then<br>            args+=(-var &quot;session_secret=${TF_VAR_session_secret}&quot;)<br>          fi<br>          terraform apply &quot;${args[@]}&quot;<br><br>      - name: Wait for ECS service stable<br>        run: |<br>          aws ecs wait services-stable \<br>            --cluster &quot;${PROJECT_NAME}-cluster&quot; \<br>            --services &quot;${PROJECT_NAME}-svc&quot;<br><br>      - name: Resolve ALB DNS (tf output -&gt; AWS CLI fallback)<br>        id: resolve<br>        working-directory: terraform<br>        run: |<br>          set -e<br>          ALB=&quot;$(terraform output -raw alb_dns_name || true)&quot;<br>          if [ -z &quot;$ALB&quot; ] || [ &quot;$ALB&quot; = &quot;None&quot; ]; then<br>            NAME=&quot;${PROJECT_NAME}-alb&quot;<br>            ALB=$(aws elbv2 describe-load-balancers --names &quot;$NAME&quot; \<br>              --query &#39;LoadBalancers[0].DNSName&#39; --output text 2&gt;/dev/null || true)<br>          fi<br>          if [ -z &quot;$ALB&quot; ] || [ &quot;$ALB&quot; = &quot;None&quot; ]; then<br>            echo &quot;Failed to resolve ALB DNS name&quot; &gt;&amp;2<br>            aws elbv2 describe-load-balancers --query &#39;LoadBalancers[].{Name:LoadBalancerName,DNS:DNSName}&#39; --output table || true<br>            exit 1<br>          fi<br>          echo &quot;alb=$ALB&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>          echo &quot;Resolved ALB: $ALB&quot;<br><br>  smoke_test:<br>    name: Smoke test<br>    runs-on: ubuntu-latest<br>    needs: apply<br>    permissions:<br>      contents: read<br>    steps:<br>      - name: Configure AWS (for CLI fallback)<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_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Resolve ALB URL (robust)<br>        id: resolve<br>        run: |<br>          set -euo pipefail<br><br>          # 1) Prefer the output from the apply job if present<br>          FROM_APPLY=&quot;${{ needs.apply.outputs.alb }}&quot;<br>          if [ -n &quot;$FROM_APPLY&quot; ] &amp;&amp; [ &quot;$FROM_APPLY&quot; != &quot;None&quot; ]; then<br>            echo &quot;url=http://$FROM_APPLY&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>            echo &quot;Resolved from apply outputs: http://$FROM_APPLY&quot;<br>            exit 0<br>          fi<br><br>          # 2) Fallback: try canonical name &quot;&lt;project&gt;-alb&quot;<br>          NAME=&quot;${PROJECT_NAME}-alb&quot;<br>          ALB=&quot;$(aws elbv2 describe-load-balancers --names &quot;$NAME&quot; \<br>                  --query &#39;LoadBalancers[0].DNSName&#39; --output text 2&gt;/dev/null || true)&quot;<br><br>          # 3) Final fallback: search by Project tag<br>          if [ -z &quot;$ALB&quot; ] || [ &quot;$ALB&quot; = &quot;None&quot; ]; then<br>            echo &quot;Name lookup failed, searching by tag Project=${PROJECT_NAME}...&quot;<br>            ARNS=&quot;$(aws elbv2 describe-load-balancers --query &#39;LoadBalancers[].LoadBalancerArn&#39; --output text || true)&quot;<br>            FOUND=&quot;&quot;<br>            for ARN in $ARNS; do<br>              HAS_TAG=&quot;$(aws elbv2 describe-tags --resource-arns &quot;$ARN&quot; \<br>                         --query &quot;TagDescriptions[0].Tags[?Key==&#39;Project&#39; &amp;&amp; Value==&#39;${PROJECT_NAME}&#39;] | length(@)&quot; \<br>                         --output text || echo 0)&quot;<br>              if [ &quot;$HAS_TAG&quot; = &quot;1&quot; ]; then<br>                FOUND=&quot;$ARN&quot;<br>                break<br>              fi<br>            done<br>            if [ -n &quot;$FOUND&quot; ]; then<br>              ALB=&quot;$(aws elbv2 describe-load-balancers --load-balancer-arns &quot;$FOUND&quot; \<br>                       --query &#39;LoadBalancers[0].DNSName&#39; --output text || true)&quot;<br>            fi<br>          fi<br><br>          if [ -z &quot;$ALB&quot; ] || [ &quot;$ALB&quot; = &quot;None&quot; ]; then<br>            echo &quot;Failed to resolve ALB for project ${PROJECT_NAME}&quot; &gt;&amp;2<br>            # Diagnostics to help troubleshoot<br>            aws elbv2 describe-load-balancers \<br>              --query &#39;LoadBalancers[].{Name:LoadBalancerName,DNS:DNSName,Scheme:Scheme,State:State.Code}&#39; \<br>              --output table || true<br>            exit 1<br>          fi<br><br>          echo &quot;url=http://$ALB&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>          echo &quot;Resolved ALB via fallback: http://$ALB&quot;<br><br>      - name: Curl homepage until 200<br>        run: |<br>          URL=&quot;${{ steps.resolve.outputs.url }}&quot;<br>          if [ -z &quot;$URL&quot; ] || [ &quot;$URL&quot; = &quot;http://&quot; ]; then<br>            echo &quot;ALB URL is empty after resolution. See previous step logs.&quot; &gt;&amp;2<br>            exit 1<br>          fi<br>          echo &quot;Hitting $URL&quot;<br>          for i in {1..30}; do<br>            code=$(curl -s -o /dev/null -w &quot;%{http_code}&quot; &quot;$URL&quot; || true)<br>            if [ &quot;$code&quot; = &quot;200&quot; ]; then<br>              echo &quot;OK (200) at $URL&quot;<br>              exit 0<br>            fi<br>            echo &quot;Attempt $i -&gt; $code&quot;<br>            sleep 5<br>          done<br>          echo &quot;Service did not return 200 in time&quot;<br>          exit 1</pre><h3>GitHub Actions: Job-by-Job</h3><h3>bootstrap_state — Prepare Terraform’s Remote Backend</h3><p>This job configures AWS credentials using repository secrets, derives a DNS-compliant, globally unique S3 bucket name from the repository and account ID, and creates the bucket in your region with versioning and AES-256 default encryption. It also creates a DynamoDB table for state locking. The job outputs the bucket name for downstream jobs. The result is a secure, shared state backend and lock orchestration so that multiple applies cannot corrupt state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYWb5atG0Q3AXT9-dwuyvQ.png" /></figure><h3>seed_ecr — Ensure the ECR Repository Exists and Is Tracked</h3><p>This job checks out the code, initializes Terraform using the backend created above, and then guarantees the ECR repository exists. If the repo is missing, it creates it via the AWS CLI. If the repo exists but Terraform’s state points to an old repository name, the job re-imports the correct repo into aws_ecr_repository.app so Terraform won’t try to destroy/recreate. Finally, it applies only that resource to align settings like image scanning and tags, and computes the repository URL for the next job.</p><h3>build_and_push — Build the Container and Publish to ECR</h3><p>Here the workflow sets up Node.js to make sure the lockfile is in sync (a deterministic precursor step), logs in to the ECR registry, auto-detects the Dockerfile and context if needed, and builds the image. It tags the image twice — once with the current commit SHA and once as latest—and pushes both tags to ECR. Using the commit SHA makes each deployment traceable and reproducible; latest is convenient for quick testing and humans.</p><h3>plan — Format, Validate, and Create a Plan with the New Image Tag</h3><p>This job initializes Terraform with the same backend, auto-formats HCL (and enforces the check), validates the configuration, and then runs terraform plan. Crucially, it passes variables from the workflow environment: the AWS region, project_name (“socialapp”), ecr_repo_name, and image_tag (the commit SHA just built). If you’ve set SOCIALAPP_SESSION_SECRET in GitHub secrets, it will also pass that into Terraform, so the app’s sessions are signed with a secret that never appears in code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OHt9XjnRg9rNMbtomEraQ.png" /></figure><h3>apply — Roll Out the Deployment on ECS Fargate</h3><p>The apply job repeats initialization and then runs terraform apply with the same set of variables. ECS updates the service’s task definition to point to the new ECR image tag and performs a rolling deployment through the ALB, respecting your health checks. After applying, the job waits for the ECS service to reach a stable state and resolves the ALB DNS either from Terraform outputs or by looking up the standard name (socialapp-alb) via the AWS API. It exposes the DNS as a job output for the smoke test.</p><h3>smoke_test — Verify the App Is Up</h3><p>The final job resolves the ALB URL robustly. If the apply job didn’t emit an output, it queries AWS directly by name and, as a last resort, by resource tags. Once it has a URL, it curls the root endpoint in a retry loop until it receives a 200 OK or times out. This provides an end-to-end validation that the new version is live, the target group is healthy, and the ALB is routing traffic.</p><p>This setup is intentionally production-oriented. Terraform codifies everything AWS-side and stores state in an encrypted, versioned S3 bucket with DynamoDB locking. ECR holds immutable images for exact rollbacks. ECS Fargate avoids server management and integrates cleanly with ALB health checks and CloudWatch Logs. GitHub Actions stitches it all together in a single, declarative workflow that you can audit, fork, or extend. There are no ad-hoc scripts and no manual steps — push to main, watch the pipeline, and open the ALB URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5e-FtfHd9aPb_mNGpIKwyA.png" /></figure><p>If you want, I can follow up with a short “Improvements &amp; Next Steps” section (HTTPS/ACM, Route 53, GitHub OIDC to remove long-lived AWS keys, blue/green deploys with CodeDeploy, alarms &amp; dashboards, and preview environments) to round out the Medium article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ab029edffc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a CI/CD Pipeline for the 2048 Game using AWS CodePipeline, ECS, and ECR]]></title>
            <link>https://medium.com/@akupheaws/build-a-ci-cd-pipeline-for-the-2048-game-using-aws-codepipeline-ecs-and-ecr-b89ddfdf6050?source=rss-1e0d66a765bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89ddfdf6050</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Dieudonne Akuphe]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 23:38:30 GMT</pubDate>
            <atom:updated>2026-07-07T14:39:39.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bi_c3I8V0y7-g-iRwPN2Rw.png" /></figure><p>This project demonstrates the implementation of a <a href="https://www.cloudforgeconsult.com/">CI/CD</a> pipeline to automate the deployment of a Dockerized 2048 game to AWS. The pipeline streamlines the entire lifecycle building, testing, and deploying the application using modern <a href="https://www.cloudforgeconsult.com/">AWS services</a> such as Amazon Elastic Container Service (ECS), Amazon Elastic Container Registry (ECR), and AWS CodePipeline. The goal is to deliver a scalable, reliable, and fully automated deployment solution for containerized applications on AWS.</p><h3>🔧 Key Tasks</h3><ul><li><strong>Build and Push Docker Image</strong>: Containerize the 2048 game and push the Docker image to Amazon Elastic Container Registry (ECR).</li><li><strong>Configure CI/CD Pipeline</strong>: Set up AWS CodePipeline to automate the build, test, and deployment stages.</li><li><strong>Deploy to ECS with Fargate</strong>: Launch the containerized application on Amazon Elastic Container Service (ECS) using the Fargate launch type for serverless container management.</li></ul><h3>👩‍💻 Steps to Be Performed</h3><ol><li><strong>Set Up ECS Cluster &amp; ECR Repository</strong><br> Create an Amazon ECS cluster and an <a href="https://www.cloudforgeconsult.com/">Amazon ECR</a> repository to host and run the Dockerized application.</li><li><strong>Prepare the 2048 Game Code</strong><br> Clone and structure the game’s source code for containerization and deployment.</li><li><strong>Configure CodeBuild for Continuous Integration</strong><br> Set up AWS CodeBuild to automatically build and test the Docker image on code changes.</li><li><strong>Configure CodePipeline for Continuous Deployment</strong><br> Create an end-to-end CI/CD pipeline with AWS CodePipeline to automate deployment to ECS.</li></ol><h3>🛠 Services Used</h3><ul><li><strong>AWS CodePipeline</strong><br> Orchestrates the CI/CD workflow by automating the build, test, and deployment stages.</li><li><strong>Amazon ECS (Fargate Launch Type)</strong><br> Deploys and manages the containerized 2048 game in a serverless environment without managing EC2 instances.</li><li><strong>Amazon ECR</strong><br> Hosts and manages Docker images used in ECS tasks, serving as the container image registry.</li><li><strong>AWS CodeBuild</strong><br> Executes the build phase, including compiling the code and creating Docker images.</li><li><strong>IAM Roles &amp; Policies</strong><br> Provides secure, granular access control between AWS services involved in the pipeline.</li></ul><h3>2.2 Prerequisites [Install Docker &amp; AWS CLI Login]</h3><h3>STEPS TO BE PERFORMED:</h3><p>1. Docker installation</p><p>2. Configure AWS CLI</p><h3>1. Docker Installation</h3><p>We need Docker and AWS CLI setup to perform this project. Steps for Docker installation for Windows, Linux and MacOS is mentioned below:</p><h3>Docker Installation on Windows</h3><p><strong>1. Check System Requirements:</strong></p><ul><li>Windows 10/11 (64-bit): Pro, Enterprise, or Education editions.</li><li>WSL2 backend (Windows Subsystem for Linux 2) is required for Docker Desktop.</li></ul><p><strong>2. Download Docker Desktop:</strong></p><ul><li>Visit the official Docker Desktop for Windows page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0sQ6kfURn5fqz4yBnoyfQ.png" /></figure><p><strong>3. Install Docker Desktop:</strong></p><ul><li>Run the downloaded installer and follow the on-screen instructions.</li><li>Ensure the WSL2 backend is enabled during installation.</li></ul><p><strong>4. Configure Docker Desktop:</strong></p><ul><li>Launch Docker Desktop.</li><li>Go to <strong>Settings &gt; Resources &gt; WSL Integration</strong> and ensure your distributions are enabled.</li></ul><p><strong>5. Verify Installation:</strong></p><ul><li>Open a new terminal (e.g., PowerShell or Command Prompt).</li><li>Run the following command:</li></ul><pre>docker --version</pre><ul><li>Test Docker with:</li></ul><pre>docker run hello-world</pre><h3>Docker Installation on Linux</h3><p>For <strong>Ubuntu/Debian-Based Distributions</strong>:</p><ol><li><strong>Uninstall Old Docker Versions (if any):</strong></li></ol><pre>sudo apt-get remove docker docker-engine docker.io containerd run</pre><p><strong>2. Set Up Repository:</strong></p><ul><li>Update the system:</li></ul><pre>sudo apt-get update</pre><ul><li>Install prerequisites:</li></ul><pre>sudo apt-get install ca-certificates curl gnupg</pre><pre>sudo install -m 0755 -d /etc/apt/keyrings<br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg<br>echo &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable&quot; | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/nul</pre><p>3. Install Docker Engine:</p><pre>sudo apt-get update<br>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p><strong>4. Start and Test Docker:</strong></p><ul><li>Start Docker:</li></ul><pre>sudo systemctl start docker</pre><ul><li>Verify Docker is running:</li></ul><pre>sudo docker run hello-world</pre><p><strong>5. Enable Docker Without <em>sudo</em> (Optional):</strong></p><pre>sudo usermod -aG docker $USER</pre><p>Log out and back in for the changes to take effect.</p><h3>Docker Installation on macOS</h3><p>1. <strong>Check System Requirements:</strong></p><ul><li>macOS Monterey (12) or later is recommended.</li><li>Ensure your system supports virtualization.</li></ul><p>2. <strong>Download Docker Desktop:</strong></p><ul><li>Visit the official Docker Desktop for Mac page.</li><li>Download the installer for macOS (Intel or Apple Silicon).</li></ul><p>3. <strong>Install Docker Desktop:</strong></p><ul><li>Open the `.dmg` file and drag Docker Desktop to the **Applications** folder.</li><li>Launch Docker Desktop and follow the onboarding steps.</li></ul><p>4. <strong>Configure Docker Desktop:</strong></p><ul><li>You may need to grant permissions (e.g., to access network resources).</li></ul><p>5. <strong>Verify Installation:</strong></p><ul><li>Open the Terminal app and run:</li></ul><pre>docker --version</pre><ul><li>Test Docker functionality:</li></ul><pre>docker run hello-world</pre><h3>2. Configure AWS CLI</h3><p>The AWS Command Line Interface (CLI) allows you to interact with AWS services directly from your terminal. To download and configure AWS CLI —</p><h3>1. Download and Install AWS CLI</h3><p>Before using AWS CLI, you need to install it on your system. Follow these steps:</p><p><strong>For Windows Users</strong></p><p>1. Go to the <a href="https://aws.amazon.com/cli/">AWS CLI Download page</a></p><p>2. Download the latest <strong>Windows Installer</strong> (`<strong><em>.msi</em></strong>` file).</p><p>3. Run the installer and follow the installation steps.</p><p>4. Once installed, open <strong>Command Prompt (cmd)</strong> and type:</p><pre>aws --version</pre><p>This should return something like:</p><pre>aws-cli/2.x.x Python/3.x.x Windows/10</pre><p>If you see this, AWS CLI is installed correctly!</p><p><strong>For macOS Users</strong></p><p>1. Open the <strong>Terminal</strong>.</p><p>2. Install AWS CLI using <strong>Homebrew</strong> (recommended):</p><pre>brew install awscli</pre><p>3. Verify the installation:</p><pre>aws --version</pre><p>If it displays a version number, you’re good to go!</p><p><strong>For Linux Users</strong></p><p>1. Open the <strong>Terminal</strong>.</p><p>2. Download and install AWS CLI:</p><pre>curl &quot;https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o &quot;awscliv2.zip&quot;<br>unzip awscliv2.zip<br>sudo ./aws/install</pre><p>3. Check the installation:</p><pre>aws --version</pre><h3>2. Create or Retrieve AWS Credentials</h3><p>To configure AWS CLI, you’ll need an **<strong>AWS Access Key ID</strong> and <strong>AWS Secret Access Key</strong>. Here’s how to find them:</p><ol><li>Log in to the AWS Management Console.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SW1wJ8bO7pRff8hb3e25dw.png" /></figure><p>2. Navigate to<strong> IAM (Identity and Access Management).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-gFYl05PM4P7-EEPLWmDQ.png" /></figure><p>3. Click <strong>Users → Add user</strong>.</p><p>4. Set a username and check <strong>Programmatic access</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkXM0NRS3A1OyfkBdeJ2Kw.png" /></figure><p>5. Assign a permission policy (e.g., “<strong><em>AdministratorAccess</em></strong>” or custom permissions).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9miqVbjZR-WXNI1l0GFtg.png" /></figure><p>6. Click <strong>Create user</strong> and download the generated <strong>credentials</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ju9dgkhG9lmVeAiSQgdeNQ.png" /></figure><p>7. Go to newly created User and Click ‘<strong><em>Create access key’</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTS04cHzh1n1ka-93fYpsQ.png" /></figure><p>8. Select ‘<strong>Use case</strong>’ as CLI and provide consent, Click <strong>Next</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iK2g4mUWT4brcFQSaHW_lg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrogMlWUSqroSwSWs-FGPQ.png" /></figure><p>9. Set description tag value and proceed to create access key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6HAi0gQ_Th1JA7adV7JsQ.png" /></figure><p>10. Access key will get created download the generated <strong>Access key </strong>and<strong> Secret access key.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAJxlDj-HcR74xVOa1M_Tg.png" /></figure><h3>3. Configure AWS CLI</h3><p>Now that you have your credentials, let’s set up AWS CLI.</p><p>1. Open a terminal (or Command Prompt on Windows).</p><p>2. Run the configuration command:</p><pre>aws configure</pre><p>3. You’ll be prompted to enter the following details:</p><ul><li><strong>AWS Access Key ID</strong>: Enter your access key.</li><li><strong>AWS Secret Access Key</strong>: Enter your secret key.</li><li><strong>Default region name</strong>: Enter your preferred region (e.g., `us-east-1`, `ap-south-1` for India).</li><li><strong>Default output format</strong>: You can leave this blank (default) or choose `json`, `table`, or `text`.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BsCr_Mxeh2MAtboNotqe_g.png" /></figure><h3>2.3 Prepare the 2048 Game Code</h3><h3>STEPS TO BE PERFORMED:</h3><p>1. Clone the website code.</p><p>2. Run a docker container and push to ECR.</p><p>3. Access the website through ECS URL.</p><p>4. Create your own GitHub repository.</p><h3>1. Clone the website code</h3><p>The website code for 2048 game is already provided to you. To get this code, open your preferred IDE and open a terminal</p><ul><li>Use the following command to clone the game code:</li></ul><pre>https://github.com/akupheaws/Build-a-CI-CD-Pipeline-for-the-2048-Game-using-AWS-CodePipeline-ECS-and-ECR.git</pre><h3>2. Run a Docker container and push to ECR</h3><p>The website code that you cloned already has a Dockerfile which defines the steps to be performed to run a container. We will be running a container locally and then push the container to ECR. To do this —</p><h3>Check the Dockerfile for the Application</h3><ul><li>Check the <strong><em>Dockerfile</em></strong> to containerize the 2048 game present in the root directory.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Npn-i2Pdl1Qg4Ci1lIhvww.png" /></figure><ul><li>This <strong>Dockerfile</strong> is designed to create a lightweight container for hosting the 2048 game using the Nginx web server. It begins by using the official `<strong><em>nginx:latest</em></strong>` image as the base, which provides a preconfigured Nginx environment.</li><li>The `<strong><em>COPY</em></strong>` command transfers all the 2048 game files into Nginx’s default web root directory (`<strong><em>/usr/share/nginx/html</em></strong>`), ensuring they are ready to be served. The `<strong><em>EXPOSE 80</em></strong>` directive makes port 80 available, allowing the game to be accessed over HTTP.</li><li>Finally, the `<strong><em>CMD</em></strong>` command ensures that Nginx runs in the foreground (`<strong><em>daemon off </em></strong><em>‘) </em>when the container starts, serving the 2048 game seamlessly.</li></ul><h3>Build the Docker Image</h3><ul><li>Run the following commands in the terminal to build the image (Ensure the Docker Desktop is running in the background):</li></ul><pre>docker build -t 2048-game .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jA_nayVXdNgUE5yVzN4-gA.png" /></figure><h3>Tag the Docker Image for ECR:</h3><ul><li>Navigate to AWS Console &gt; ECR and Create an ECR Repository (e.g., <strong><em>097670902547.dkr.ecr.ap-south-1.amazonaws.com/2048-game-repo</em></strong>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUe0HRDSmkdOarCICcjJBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWYlqAlStB32mcYRiojDXQ.png" /></figure><p>Use the ECR URI to tag the image:Replace &lt;<strong><em>ECR_URI</em></strong>&gt; with your ECR repository URI (e.g., <strong><em>097670902547.dkr.ecr.ap-south-1.amazonaws.com/2048-game-repo</em></strong>) which can be found in the ECR console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxSCiriSAFe32mlMluF41g.png" /></figure><pre>docker tag 2048-game:latest &lt;ECR_URI&gt;:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEeV2j-BuYD8GlkX5LtEow.png" /></figure><h3>Push the Image to ECR</h3><ul><li>Authenticate with ECR:</li></ul><pre>aws ecr get-login-password --region ap-south-1 | docker login --username AWS --password-stdin &lt;ECR_URI&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dGUxbzmSY7H7Ekqg4-5Fw.png" /></figure><ul><li>Push the image:</li></ul><pre>docker push &lt;ECR_URI&gt;:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFXPa_989AFwBHZrrq2lrw.png" /></figure><h3>Verify the Image in ECR</h3><ul><li>Navigate to the ECR console and confirm the image appears in the repository.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCA0cjHCTHZMMGJy9cZXew.png" /></figure><h3>3. Access the Website through ECS URL</h3><p>Now that you have pushed your container image to Amazon ECR, you need to run it on ECS before you can access it. Follow these sub‑steps:</p><h3>Create the ECS Service‑Linked Role</h3><p>1. In the AWS Console, go to <strong>IAM → Roles → Create role</strong>.</p><p>2. Under <strong>Select trusted entity</strong>, choose <strong>AWS service</strong>.</p><p>3. In <strong>Use case</strong>, select <strong>Elastic Container Service</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0XsdSokHeU7fHq1n5Fi5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgKLFukyoYyYLBrN5eLJtQ.png" /></figure><p>4. Click <strong>Next → </strong>Name<strong>: AWSServiceRoleForECS→ Create role.</strong></p><h3>Create an ECS Cluster</h3><ul><li>In the AWS Console, go to <strong>ECS → Clusters → Create cluster</strong>.</li><li>Give your cluster a name, e.g. `<strong><em>2048-game-cluster</em></strong>`, then <strong>Create</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hKHF5hT1ZdIaEoY8UpkZxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEYwg_1YpWkR74uC7yxjoA.png" /></figure><p>Choose Infrastructure as AWS Fargate and leave other settings as default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFnpVHbXTyRE6Isn-anV8Q.png" /></figure><p>Click <strong>Create</strong>, Wait for the cluster to get created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NO05qUYhkPESbKoa0jBTJA.png" /></figure><h3>Register a Task Definition</h3><ul><li>In <strong>ECS → Task Definitions → Create new Task Definition.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4_D2Pq9ZHeSBuExdwNobQ.png" /></figure><ul><li><strong>Task Definition name</strong>: `<strong><em>2048-game-task</em></strong>`</li><li>Select <strong>FARGATE → Next step</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acSMmqcz1pEVTKiYlIDOZA.png" /></figure><ul><li>Under Container definitions, click <strong>Add container</strong>:<br>- <strong>Container name</strong>: ‘<em>2048-container`</em><br>- <strong>Image</strong>: `<em>&lt;your‑ecr‑uri&gt;:latest</em>`</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMQDbOUWNwIkTFL_Dtg_3Q.png" /></figure><p><strong>Port mappings: </strong>Host port 80 → Container port 80</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jd2mwtpil9WqABimSvFF-w.png" /></figure><ul><li><strong>Add</strong>, then <strong>Create</strong>.</li></ul><h3>Create a Service</h3><ul><li>In <strong>ECS → Clusters,</strong> select `<em>2048-game-cluster</em>`.</li><li><strong>Services </strong>tab<strong> → Create.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ftlnD4vWrh79Gfuo6SQZA.png" /></figure><ul><li><strong>Launch type: </strong><em>FARGATE</em></li><li><strong>Task Definition: `</strong><em>2048-game-task</em><strong>`</strong></li><li><strong>Service name: `</strong><em>2048-service</em><strong>`</strong></li><li><strong>Number of tasks: `</strong><em>1</em><strong><em> ‘</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTihbbuK6TdnwiwoVj4e3A.png" /></figure><p>Under <strong>Network</strong>, choose default VPC and subnets, <strong>Public IP </strong>= <em>ENABLED</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjzj8Jnj6AmLhcwL7ySmrA.png" /></figure><p>For <strong>Security group</strong>, select (or create) one allowing HTTP (port 80)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDha2g4KMpzsKFXoelwB8A.png" /></figure><p><strong>Next step → Create service → View service.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbgZ48IoYppJu97TWL3-ag.png" /></figure><h3>Find the Public IP of the ECS Task</h3><ul><li>- In <strong>Clusters</strong> → `<em>2048-game-cluster</em>` → <strong>Tasks</strong>, click the running task.</li><li>- Under <strong>Network</strong>, note the <strong>Public IP</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgMtjRUtsowT-VQpiUkbAg.png" /></figure><h3>Access the Website Using the Public IP</h3><ul><li>Open your browser and enter the public IP address of the ECS task. For example:</li></ul><pre>http://&lt;Public-IP&gt;:80</pre><ul><li>Replace <strong>&lt;Public-IP&gt; </strong>with the actual IP address from the previous step.</li></ul><h3>Verify Functionality</h3><ul><li>Ensure the website is fully functional, including loading the game and interacting with the frontend as intended</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V71o6YhIzdsnx0gp5b18lQ.png" /></figure><h3>4. Create Your Own GitHub Repository</h3><p>Since you will be performing CI/CD operations, you need to have your own GitHub repository with the website code. To do this —</p><h3>Create a New GitHub Repository</h3><ul><li>Navigate to <a href="https://github.com/">GitHub</a> and create a new <a href="https://akuphecloud.com/">repository</a>. Make sure the repository is public or private depending on your preference.</li><li>Provide a repository name, such as `<strong><em>2048-game-ci-cd</em></strong>`.</li><li>Optionally, add a description for the repository (e.g., “CI/CD pipeline setup for 2048 game”).</li><li>Do not initialize with a README or `<strong><em>.gitignore</em></strong>` (as you’ll be pushing an existing codebase).</li><li>Click <strong>Create repository</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nmv_zeX3jKr_ZKrahcFeKg.png" /></figure><h3>Modify buildspec.yml</h3><p><strong>Update </strong>the<strong> `buildspec.yml` </strong>by changing the placeholders:</p><ul><li>The `<strong><em>buildspec.yml</em></strong>` file is crucial for AWS CodeBuild as it defines the build commands. You’ll need to modify it to reflect your project’s ECR URI and ECS service details.</li><li>Here’s an example of a typical `<strong><em>buildspec.yml</em></strong>` file for building a Docker image and pushing it to ECR:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b427Q1QLie4dX5kSu3hRog.png" /></figure><h3>Placeholder Details:</h3><ul><li><strong><em>&lt;your-region&gt;</em></strong>: Replace this with your AWS region (e.g., <em>`ap-south-1`, `us-east-1`</em>).</li><li><strong><em>&lt;your-ecr-repository-uri&gt;</em></strong>: Replace this with your Amazon ECR repository URI (e.g., `<em>123456789012.dkr.ecr.ap-south-1.amazonaws.com/2048-game-repo</em>`).</li><li><strong><em>&lt;image-name&gt;</em></strong>: Replace this with the name of the Docker image you’re building (e.g., `<em>2048-game</em>`).</li><li><strong><em>&lt;container-name&gt;</em></strong>: Replace this with the ECS container name (e.g., `<em>2048-container</em>`).</li><li><strong>Explanation</strong>:</li><li><strong>- install phase:</strong> Specifies the Docker version to use.</li><li><strong>- build phase: </strong>Builds the Docker image, logs into ECR, tags the image, and prepares it for pushing.</li><li><strong>- post_build phase:</strong> Pushes the Docker image to ECR and generates the <em>imagedefinitions.json</em> file, which ECS uses for deployments.</li><li><strong>- artifacts: </strong>The <em>imagedefinitions.json</em> file is saved as an artifact so it can be used in later stages like ECS deployment.</li></ul><h3>Push Your Local Code to GitHub</h3><ul><li>Open a terminal or command prompt in the folder where your code and `<strong><em>buildspec.yml</em></strong>` are located.</li><li>Run the following commands to push your code to the newly created GitHub repository:</li></ul><pre>git init<br>git add .<br>git commit -m &quot;Initial commit&quot;<br>git remote remove origin<br>git remote add origin &lt;your-repository-url&gt;<br>git branch -M main<br>git push -u origin main</pre><h3>Verify on GitHub</h3><ul><li>Visit the GitHub repository page, and you should see all your files, including the <strong><em>Dockerfile</em></strong>, <strong><em>buildspec.yml,</em></strong> and the 2048 game source code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tG1oVMVgaHvy55dx-QnUiQ.png" /></figure><h3>2.4 Set up CodeBuild and CodePipeline for CI/CD</h3><h3>STEPS TO BE PERFORMED:</h3><p>1. Create an IAM Role for CodeBuild.</p><p>2. Create a S3 Bucket for Build Artifacts.</p><p>3. Create a CodeBuild Project.</p><p>4. Test the CodeBuild Project.</p><p>5. Create an AWS CodePipeline</p><h3>1. Create an IAM Role for CodeBuild</h3><p>AWS services like CodeBuild need permissions to interact with <strong>ECR (Elastic Container Registry), ECS, S3, </strong>and<strong> CodeBuild</strong> itself. To give CodeBuild all the necessary permissions —</p><h3>Create a New IAM Role</h3><ul><li>Navigate to the <strong>IAM</strong> section of the AWS console.</li><li>Choose <strong>Create Role</strong> and select <strong>CodeBuild</strong> as the trusted entity type.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDd08eFQwIUpE07RtN-X0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6docA14TS-BixS5zWqd9w.png" /></figure><ul><li>- Attach the following <strong>Managed Policies</strong>:</li><li><strong>AmazonEC2ContainerRegistryFullAccess</strong>: Allows CodeBuild to interact with ECR (Elastic Container Registry).</li><li><strong>AWSCodeBuildDeveloperAccess</strong>: Grants permissions for CodeBuild to access build-related resources.</li><li><strong>AmazonS3FullAccess</strong>: Grants access to read/write to S3 buckets (for storing build artifacts).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6c2Hqn6Lg3jD6GUCdsAfg.png" /></figure><p>Name the role (e.g., <strong>codeBuildServiceRole</strong>) and create it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Css_0gezTE_xXtan2gKdaw.png" /></figure><ul><li><strong>Attach Inline Policy</strong> for ECS:</li><li>Navigate to the <strong>codeBuildServiceRole</strong> you created and click on <strong>Add Permissions &gt; Attach Inline Policies.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPlHYFnhsX7dbIbaO1HL0g.png" /></figure><p>Click on JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbqYf4b-8llxWoOXA65jdg.png" /></figure><ul><li>Attach the following Inline Policy to allow CodeBuild to update ECS services:</li></ul><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ecs:UpdateService&quot;,<br>                &quot;ecs:DescribeServices&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;&lt;ENTER_YOUR_ECS_SERVICE_ARN&gt;&quot;<br>        }<br>    ]<br>}</pre><p>You can get your &lt;<strong>ECS_SERVICE_ARN</strong>&gt; by navigating to<strong><em> ECS</em></strong><em> &gt; </em><strong><em>Clusters </em></strong><em>&gt; </em><strong><em>2048-game-cluster </em></strong><em>&gt; </em><strong><em>Services </em></strong><em>&gt; </em><strong><em>2048-service</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*_NQllwjTz5WOrFqgnnVKAw.png" /></figure><p>Click on Next. Give the policy a name (e.g. <strong>ECSAccessPolicy</strong>) and click on Create Policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0-jdKKseNpCAd6TdOW5SA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kY6kzjM8EPa6IsdpdIANuQ.png" /></figure><h3>2. Create an S3 Bucket for Build Artifacts</h3><p>CodeBuild generates output files, such as Docker images and logs. We store them in Amazon S3 so they can be accessed later. To do this:</p><h3>Navigate to the S3 Console</h3><ul><li>Go to the S3 Console and create a new bucket (e.g., <strong><em>2048-ci-cd-pipeline-artifacts1</em></strong>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SEAzPUgqQS92EPR94iP_-A.png" /></figure><p>Ensure the bucket name is globally unique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RHcvKReZrX2SS6qWaZ4Tg.png" /></figure><p>Keep the rest of the settings as default and click on Create Bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVmX7Mg0cV9cv-z2EUhSzA.png" /></figure><h3>3. Create a CodeBuild Project</h3><p>The CodeBuild project is where AWS pulls your GitHub repository, builds the project (e.g., compiles code, builds Docker images), and pushes the results to S3. Create a CodeBuild project by following the steps below —</p><h3>Go to the CodeBuild Console</h3><ul><li>Navigate to the <strong>CodeBuild Console</strong> and choose Create Build Project.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMNfWFMhWx-qNsE3oTAXYg.png" /></figure><h3>Configure the Project</h3><ul><li><strong>Project Name</strong>: Enter a project name (e.g.,<strong><em> 2048-game-build)</em></strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsiuupLVd75n_uAj7znIeA.png" /></figure><p><strong>Source Provider:</strong> Choose <strong>GitHub</strong> (or other source if required) and connect to your GitHub repository. Connect to GitHub by clicking on Manage default source credential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1H-jBkv1ZJNGLgHvKZV-jQ.png" /></figure><p>Choose the option <strong>OAuth App</strong> for Credential type and <strong>CodeBuild</strong> for service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2fCjcj2L1oQ9ynjXE_MmA.png" /></figure><p>After you are successfully connected to GitHub, you can choose your respective GitHub repository that you created in the last step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPSuBJEgUYA0Flhu49CTmA.png" /></figure><ul><li><strong>Environment</strong>:</li><li>Keep the environment configurations as default.</li><li>Under the <strong>Service role, </strong>choose<strong> Existing role</strong> and select the <strong><em>codeBuildServiceRole</em></strong> IAM role that was created earlier.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JysS5xQ7wwnBzY_sKzc-Xw.png" /></figure><h3>Buildspec Configuration</h3><ul><li>Click on Use a <strong>buildspec</strong> file option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1Tnmb_t8fYse3e8N6-aAQ.png" /></figure><h3>Artifacts Configuration</h3><ul><li><strong>Type</strong>: Select <strong>Amazon S3</strong> for artifacts.</li><li><strong>Bucket</strong>: Choose the S3 bucket `<strong><em>2048-ci-cd-pipeline-artifacts1</em></strong>`.</li><li>Leave the rest as default.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUZZg_T3ByHr6hOHSyYchA.png" /></figure><h3>Create the Build Project</h3><ul><li>Review all the settings and click<strong> Create Build Project</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzIMZvbQOKAC4DMOWuf_oQ.png" /></figure><h3>4. Test the CodeBuild Project</h3><h3>Start a Build</h3><ul><li>Trigger the build manually from the <strong>CodeBuild</strong> console and monitor its progress.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCqP1m01ZGYNBv1nOiPWfA.png" /></figure><h3>Verify Build Success:</h3><ul><li>Check the <strong>Build Logs </strong>to ensure the Docker image is built and pushed to ECR successfully.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXpXXf-9AcQzEi3wzRzF0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUY_kuX-r8buTn90bQ3heg.png" /></figure><p>Verify the <strong>imagedefinitions.json</strong> file is created in the specified S3 artifact bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OknvmbDHicbpzDym1puM0g.png" /></figure><h3>5. Create an AWS CodePipeline</h3><p>AWS CodePipeline is the service that connects all the different stages of your CI/CD pipeline. First, we need to create a new pipeline to define how changes in your code will trigger builds and deployments</p><h3>Go to the CodePipeline Console</h3><ul><li>In the AWS Management Console, search for <strong>CodePipeline</strong> in the search bar and navigate to the CodePipeline section.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9XrFemOn4gFinlCZeNKIQ.png" /></figure><h3>Create a New Pipeline</h3><p>A <strong>pipeline</strong> is a sequence of automated steps that CodePipeline follows whenever there’s a code update. We need to define the pipeline structure before adding specific build and deploy steps.</p><p>1. <strong>Create Pipeline:</strong> Click on the <strong>Create pipeline</strong> button to begin creating a new pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sATbN-Ks-C8lhPi0haXGZA.png" /></figure><p>2. Click on <strong>Build Custom pipeline</strong> and click <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfZyRyzggvgcN5nCkNs-qQ.png" /></figure><p>3. <strong>Pipeline Name</strong>:</p><ul><li>Give your pipeline a name (e.g., `<em>2048-game-pipeline</em>`).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v92_vTeOlJlS0Sj1qeYIdw.png" /></figure><p>4. <strong>Service Role</strong>:</p><ul><li>You can either create a new service role or use an existing one.</li><li>For simplicity, select <strong>Create a service role</strong>. Add a role name (`e.g. <em>codePipelineServiceRole</em>`)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZG2MDVbRpDpfsfjKLNk6-Q.png" /></figure><p>5. Click on Next.</p><h3>Add Source Stage (GitHub)</h3><p>The <strong>source stage</strong> tells CodePipeline where to pull the latest code from. In this case, we’re using <strong>GitHub</strong> as our repository.</p><p>1. <strong>Source Provider</strong>:</p><ul><li>Choose <strong>GitHub(via OAuth App)</strong> as the source provider.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5V9sAaYF_2raWln9SEWXoA.png" /></figure><p>2. <strong>Connect to GitHub</strong>:</p><ul><li>Click on <strong>Connect to GitHub</strong>.</li><li>If you haven’t already connected your GitHub account to AWS before, you’ll be prompted to authorize AWS to access your GitHub repositories.</li></ul><p>3. <strong>Repository</strong>:</p><ul><li>Select the <strong>GitHub repository</strong> where your project code is stored. Ensure that this repository is the one you intend to build and deploy. Click the main branch.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hyk-_dHWWUAHtv_fqIxokA.png" /></figure><p>4. Keep the rest as <strong>default</strong> and click <strong>Next</strong>.</p><h3>Add Build Stage (CodeBuild)</h3><p>After pulling code from GitHub, AWS needs to <strong>build and test</strong> the application before deploying it. We use <strong>AWS CodeBuild</strong> for this step.</p><p>1. <strong>Build Provider</strong>:</p><ul><li>Select <strong>AWS CodeBuild</strong> as the build provider.</li></ul><p>2. <strong>Project Name</strong>:</p><ul><li>Choose the <strong>CodeBuild project</strong> that you created earlier (e.g., `2048-game-build`).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGE8DGNiTCkOLHqlCIjBBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vr-jxULaT7qNFhzW6OrwFA.png" /></figure><p>3. Keep the rest as <strong>default</strong> and click <strong>Next</strong>.</p><p>4. Skip the <strong>Test</strong> stage.</p><h3>Add Deploy Stage (ECS Deployment)</h3><p>Once the application is built successfully, it needs to be <strong>deployed to Amazon ECS</strong> so the latest version is live. This step ensures seamless automatic updates. <strong>Deploy Provider:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9W632WsK1bZz-pGPhaYrWQ.png" /></figure><ol><li><strong>Cluster</strong>: Choose your ECS cluster (e.g., <em>2048-game-cluster</em>).<br>2.<strong> Service</strong>: Choose your ECS service (e.g., <em>2048-service</em>).<br>3. Keep the rest as default and click Next.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpETuV-oXHxIn2W1B_gq4Q.png" /></figure><h3>Review and Create Pipeline</h3><p>1. <strong>Review</strong>:</p><ul><li>Review all the stages to ensure that the source, build, and deploy steps are configured correctly.</li></ul><p>2. <strong>Create Pipeline</strong>:</p><ul><li>Once everything looks good, click <strong>Create pipeline</strong> to finalize the process.</li></ul><p>3. The CodePipeline will run the test process and verify that every step succeeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNAvIVvCZ8wHLQQCcm1x2w.png" /></figure><h3>2.5 Test the pipeline</h3><h3>STEPS TO BE PERFORMED:</h3><p>1. Modify the Website Code.</p><p>2. Commit and Push the Change.</p><p>3. Monitor the Pipeline Execution.</p><p>4. Verify the Deployment.</p><h3>1. Modify the Website Code</h3><p><strong>Make a Change to the Game Name locally</strong>:</p><ul><li>Open the main game code file (`<strong><em>index.html</em></strong>` where the game name is defined).</li><li>Check on Line 22, you can change the name from 2048 to 2048 by <strong>your name</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Jdiu91XJalbotq2nJIFxw.png" /></figure><ul><li>Find the part where the name “2048” is displayed, and update it to include your name. For example:</li></ul><pre>&lt;h1&gt;2048 Game&lt;/h1&gt;</pre><pre>&lt;h1&gt;2048 by *your name*&lt;/h1&gt;</pre><ul><li>Save the changes.</li></ul><h3>2. Commit and Push the Change</h3><p>1. <strong>Stage the Changes:</strong></p><ul><li>Stage the modified file for commit:</li></ul><pre>git add .</pre><p>2. <strong>Commit the Changes</strong>:</p><ul><li>Commit the changes with a descriptive message:</li></ul><pre>git commit -m &quot;Changed game name to 2048 by *your name*&quot;</pre><p>3. <strong>Push the Changes to GitHub</strong>:</p><ul><li>Push the changes to the GitHub repository (assuming you’re on the `main` branch):</li></ul><pre>git push -u origin main</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29Y5B5Op0NyyQJZDpNJHcg.png" /></figure><h3>3. Monitor the Pipeline Execution</h3><p>1. <strong>Check CodePipeline</strong>:</p><ul><li>After pushing the changes, navigate to the <strong>AWS CodePipeline</strong> console.</li><li>The pipeline should automatically trigger upon detecting the push to GitHub.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOF4Q6jolTlI1sBYYgdJmw.png" /></figure><ul><li>The stages should begin running:</li></ul><p>- <strong>Source</strong>: Code will be fetched from GitHub.</p><p>- <strong>Build</strong>: CodeBuild will run the `buildspec.yml` script and package the application.</p><ul><li><strong>Deploy</strong>: CodePipeline will deploy the changes to ECS</li></ul><p>2. <strong>Check Logs</strong>:</p><ul><li>You can monitor the pipeline’s execution in real-time via the AWS CodePipeline console.</li><li>If there’s an issue, check the logs for each stage (Source, Build, and Deploy) to identify the cause.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fb0sQHjS36jhro9aH92npw.png" /></figure><h3>4. Verify the Deployment</h3><p>1. <strong>Visit Your Website:</strong></p><ul><li>After the pipeline runs successfully, visit the URL where your website is hosted.</li><li>You can get the IP address of the website by navigating to ECS&gt; Cluster&gt; 2048-game-cluster, click on the Tasks tab and click on the latest task.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmwhfzXxZGzdrULGTu6hqg.png" /></figure><ul><li>Under the Networking tab, you will find the Public IP address. Open a new chrome tab and type in the URL as:</li></ul><pre>http://&lt;ip_address&gt;:80</pre><p>Ensure that the game name has been updated to “2048 by *your name*” on the live website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5IDmemmWKD0l6PqWZp3Jw.png" /></figure><h3>Conclusion</h3><p>This project focused on building a complete <strong>CI/CD pipeline on AWS</strong> to automate the deployment of a containerized application, enhancing <strong>efficiency,</strong> <strong>reliability</strong>, and <strong>scalability</strong>.</p><p><strong>Key highlights:</strong></p><ul><li>Set up a <strong>CI/CD pipeline</strong> using <strong>AWS CodePipeline</strong> and <strong>CodeBuild</strong>.</li><li>Containerized the application and deployed it using <strong>Amazon ECS</strong>.</li><li>Automated build, test, and deployment workflows to reduce manual effort.</li><li>Improved consistency and speed of application delivery.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89ddfdf6050" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>