<?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 Joshua Adeyemi on Medium]]></title>
        <description><![CDATA[Stories by Joshua Adeyemi on Medium]]></description>
        <link>https://medium.com/@adeyemijoshua?source=rss-8cf5586b479d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uDJZ4Ku8pPwIBeJg</url>
            <title>Stories by Joshua Adeyemi on Medium</title>
            <link>https://medium.com/@adeyemijoshua?source=rss-8cf5586b479d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:17:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adeyemijoshua/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[Ansible: The Future of Configuration Management]]></title>
            <link>https://medium.com/@adeyemijoshua/ansible-the-future-of-configuration-management-1d6c9f3cdf94?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6c9f3cdf94</guid>
            <category><![CDATA[configuration-management]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[yaml]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 15:31:39 GMT</pubDate>
            <atom:updated>2025-09-05T15:43:29.782Z</atom:updated>
            <content:encoded><![CDATA[<p>In early infrastructure management, teams relied on brittle combinations of shell scripts, manual SSH work, and ad-hoc cron jobs. These manual methods eventually became unsustainable at scale. Heavyweight configuration tools like Puppet and Chef appeared to offer structure and consistency, but often brought drawbacks such as agent management, complex setups, and rigid operational models.</p><p>Ansible emerged in February 2012, created by Michael DeHaan, promising a clearer alternative: agentless orchestration over SSH, human-readable YAML playbooks, and a declarative style that resonated with engineers. Red Hat’s acquisition in October 2015 accelerated Ansible’s integration into enterprise DevOps pipelines, helping it gain widespread adoption.</p><p>Nevertheless, simplicity does not come without trade-offs. A <a href="https://www.researchgate.net/publication/390749744_From_Worse_is_Better_to_Better_Lessons_from_a_Mixed_Methods_Study_of_Ansible%27s_Challenges">recent mixed-methods study</a> analyzed 59,157 posts from Stack Overflow, Reddit, and the Ansible forum, plus interviews with practitioners of varying experience levels. The findings highlight recurring issues: performance bottlenecks, limited debugging features, and fragmented documentation. <a href="https://www.reddit.com/r/devops/comments/q9s2vq/cant_justify_terraform_an_ansible_perspective/">Reddit</a> users resonate with these critiques. One put it bluntly:</p><p>“Terraform is a declarative execution engine that will parallelize tasks … Terraform is substantially faster to execute than Ansible for anything beyond a trivially small code base.”</p><p>Another <a href="https://www.reddit.com/r/Terraform/comments/nkbwzp/ansible_vs_terraform_for_iac/">user</a> drove the point home with this clear distinction:</p><p>“Use Terraform for provisioning and Ansible for configuration management. Terraform maintains state, Ansible does not.”</p><p>This article is not a product brochure or feature summary. Instead, it is a reflective journey through how infrastructure automation evolved, why Ansible captured engineers’ trust, where it struggles in authentic contexts, and how future paradigms like immutable infrastructure and event-driven workflows may reshape what we mean by configuration management.</p><h3>Brief history of configuration management</h3><p>To understand this evolution, it helps to first look at the origins of configuration management.<strong> </strong><a href="https://en.wikipedia.org/wiki/Configuration_management">Configuration management</a> began in the 1950s under the U.S. Department of Defense, where the discipline was essential for maintaining hardware and software consistency across complex systems. Early automation foundations emerged through tools like Unix’s make (introduced in 1976) and version control systems such as <a href="https://en.wikipedia.org/wiki/Source_Code_Control_System?">SCCS</a> and <a href="https://en.wikipedia.org/wiki/Revision_Control_System?">RCS</a>, which supported reproducibility and process control.</p><p>By 1993, the modern era of configuration tools had begun. Mark Burgess released <a href="https://en.wikipedia.org/wiki/CFEngine"><strong>CFEngine</strong></a>, which introduced the groundbreaking concept of convergence, where systems automatically adjust themselves to reach and maintain a desired state. This approach shifted operations from reactive firefighting to proactive, self-healing infrastructure. Over time, CFEngine evolved, with version 3 in 2008 incorporating <a href="https://www.researchgate.net/publication/224646884_Promise_theory_-_A_model_of_autonomous_objects_for_pervasive_computing_and_swarms"><em>promise theory</em></a>, a formal model that influenced later automation paradigms.</p><p>In the mid-2000s, <a href="https://help.puppet.com/core/current/Content/PuppetCore/puppet_index.htm"><strong>Puppet</strong></a> brought configuration management into wider enterprise use with its master agent architecture and declarative domain-specific language. It offered much-needed structure in large, distributed environments. Yet the complexity of managing agents left room for alternatives. Around 2009, <a href="https://docs.chef.io/"><strong>Chef</strong></a> entered the scene with a ruby-based recipe model, appealing to teams that valued flexibility and code-like control over their infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALmJTNbUo6uBhxw3QmjCsA.png" /></figure><p><em>How configuration management evolved. Image source: </em><a href="https://medium.com/%40mike_tyson_cloud/the-origins-of-infrastructure-as-code-a-brief-history-of-devops-a883d8877f19"><em>Medium</em></a></p><p>As these tools matured, <a href="https://docs.saltproject.io/en/latest/topics/salt_system_architecture.html#overview"><strong>SaltStack</strong></a> emerged with a different focus: speed and responsiveness at massive scale. Using a master minion design paired with ZeroMQ messaging, SaltStack achieved fan-out execution in seconds across thousands of nodes. Its <em>beacon</em> and <em>reactor</em> system enabled true event-driven automation, letting infrastructure respond immediately to changes in state or security posture.</p><p>This real-time capability won its adoption in industries where seconds matter, such as security patching or large-scale cluster orchestration, and eventually led to <a href="https://www.fierce-network.com/telecom/vmware-to-acquire-software-automation-vendor-saltstack">VMware</a> acquiring SaltStack in 2020 to enhance its automation suite.</p><p>Despite their capabilities, Puppet, Chef, and SaltStack all came with operational overhead, from maintaining agents to managing control servers. In 2012, <a href="https://www.redhat.com/en/technologies/management/ansible"><strong>Ansible</strong></a> arrived as a fresh way to handle configuration management. Operating over <a href="https://www.ssh.com/academy/ssh/protocol">SSH</a> or <a href="https://docs.ansible.com/ansible/latest/os_guide/windows_winrm.html">WinRM</a> without extra agents and using clear, readable YAML, it made managing infrastructure far more straightforward than relying on traditional, agent-based systems.</p><p>Today, the landscape is shaped by trends like immutable infrastructure, container orchestration, and declarative provisioning with tools such as <a href="https://developer.hashicorp.com/terraform"><strong>Terraform</strong></a> and <a href="https://developer.hashicorp.com/packer/docs/intro?"><strong>Packer</strong></a>. Ansible remains a link between traditional configuration management and modern infrastructure practices, showing that simplicity and active community support can continue to deliver real value in an ever-changing technology landscape.</p><h3>Where Ansible fits</h3><p>To explore this value in practice, it helps to start with the scenarios where Ansible truly shines and how its design choices influence operational workflows.</p><h4>Post-provisioning and day-2 operations</h4><p>Infrastructure flows evolve rapidly, from provisioning to third-party integrations to security patches. Ansible shines in this <a href="https://www.redhat.com/en/blog/bringing-order-to-the-cloud-day-2-operations-in-aws-with-ansible">Day-2 phase</a>. It acts as the operations interface: a control-plane tool delivering targeted, incremental changes.</p><p>Teams apply playbooks directly, adapt configurations mid-flight, and manage systems without rebuilding. This practical agility is why Ansible remains a staple in mature DevOps setups.</p><h4>Heterogeneous environments and agentless advantage</h4><p>Many environments include network appliances, edge devices, and legacy systems that cannot run Python interpreters or persistent agents.</p><p>Ansible’s design runs modules directly from the control system over existing protocols, making it especially effective across diverse environments, as demonstrated in <a href="https://www.redhat.com/en/technologies/management/ansible/network-automation">Red Hat’s network automation</a>.</p><p>The result is consistent automation across devices that are not uniformly manageable.</p><h4>Pairing with Terraform for end-to-end IaC</h4><p>Ansible often shares infrastructure responsibilities with Terraform. Terraform defines and creates the infrastructure, while Ansible configures it post-provisioning.</p><p>This separation of concerns offers clear ownership, version-controlled change management, and predictable, safe deployments, a pattern widely endorsed by practitioners (<a href="https://www.reddit.com/r/devops/comments/13zzd62/do_i_need_both_terraform_and_ansible/">example discussion</a>) and highlighted in <a href="https://www.hashicorp.com/en/resources/ansible-terraform-better-together">official resources</a>.</p><h4>Accessible, code-like configuration</h4><p>Compared to <a href="https://dev.to/spacelift/puppet-vs-ansible-key-differences-explained-5in">Puppet’s ruby-based DSL</a> or Chef’s recipe syntax, Ansible’s YAML approach offers a lower barrier to entry.</p><p>Cross-functional teams, including developers, operators, and security engineers, can read, contribute, and maintain playbooks without specialized training. YAML playbooks often become the de facto “source of truth” in git workflows.</p><h4>Community momentum and real-world roots</h4><p>With nearly <a href="https://github.com/ansible/ansible">66,000 GitHub stars</a> and a vibrant ecosystem on Ansible Galaxy, the project reflects deep and widespread engagement. Practitioners share playbooks, plugins, and lessons learned across GitHub, <a href="https://www.reddit.com/r/ansible/">Reddit</a>, and Stack Overflow.</p><p>This community-driven exchange keeps Ansible closely aligned with real-world challenges.</p><h3>Where Ansible falls short</h3><p>Despite a strong community and wide practical use, Ansible still faces certain limitations.</p><p>In large or complex infrastructures, some of its design choices can create trade-offs that affect efficiency and platform coverage.</p><h4>Performance bottlenecks at scale</h4><p>Ansible’s agentless simplicity often trades off raw performance at scale. Since most runs fan out over SSH or WinRM from a central controller, very large inventories can create connection churn, long runtimes, and controller resource pressure unless forks, strategy, and inventory topology are carefully tuned, as practitioners document in troubleshooting threads and guides.</p><p>Real-world reports of <a href="https://serverfault.com/questions/1155969/ansible-performance-issues-on-a-huge-group">slow runs</a> and <a href="https://stackoverflow.com/questions/68396384/improve-ansible-performance">tuning advice</a> can be found on Server Fault and Stack Overflow.</p><h4>Limited debugging and troubleshooting clarity</h4><p>Debugging and observability remain brittle compared with modern orchestration platforms. Verbosity flags (-v/-vvv) often produce noisy output, and playbook failures frequently lack contextual tracebacks, slowing root cause analysis.</p><p>Teams repeatedly point out that long runs with intermittent failures are notoriously hard to triage in CI/CD pipelines.</p><h4>Lack of persistent state management</h4><p>Ansible does not provide built-in, persistent state management in the same way provisioners like Terraform do. Each playbook run is essentially “stateless,” meaning Ansible applies tasks but does not maintain an execution plan or global resource state.</p><p>This can complicate complex provisioning workflows, make drift reconciliation more challenging, and hinder safe parallel planning.</p><h3>Limited and less mature Windows support</h3><p>Windows support is real, but still less mature and more fragile than SSH/Linux workflows.</p><p>Managing WinRM, PowerShell differences, and various Windows versions often requires more configuration and results in slower execution times than Linux targets. Some modules behave inconsistently across Windows releases, increasing operational friction.</p><h3>Scaling limitations without enterprise features</h3><p>Out-of-the-box scaling for global, multi-region fleets is limited in Open-Source Ansible. Enterprise scale typically requires Red Hat’s <a href="https://docs.redhat.com/en/documentation/red_hat_ansible_automation_platform/2.5">Ansible automation platform</a> and <a href="https://www.redhat.com/en/technologies/management/ansible/automation-mesh">automation mesh</a> to distribute execution and avoid central controller bottlenecks.</p><p>That means teams either accept operational limits or invest in commercial platform features to regain throughput and topology flexibility.</p><h4>Fragility in templating and task ordering</h4><p>Templating and imperative task ordering create fragile edges. <a href="https://jinja.palletsprojects.com/en/stable/">Jinja2</a> templates embedded in playbooks are powerful but can be brittle. Subtle template logic, undefined variables, or unexpected data shapes introduce runtime errors.</p><p>Similarly, imperative sequences (handlers, when conditions, ordered tasks) can hide implicit dependencies that only surface in production.</p><h3>Adoption trends in the real world</h3><p>Ansible’s influence isn’t confined to tech blogs or conference talks; its footprint can be seen in startups, mid-sized businesses, and global enterprises alike.</p><h3>From Open-Source roots to enterprise scale</h3><p>Ansible started as a widely embraced open-source project and has grown into a key automation platform across industries.</p><p>By 2019, <a href="https://www.redhat.com/en/about/press-releases/red-hat-ansible-automation-accelerates-past-major-adoption-milestone-now-manages-more-four-million-customer-systems-worldwide">Red Hat</a> reported that Ansible was managing more than four million customer systems worldwide, showing its practical impact across hybrid and enterprise environments.</p><h3>Recognition from industry analysts</h3><p>This traction has been reaffirmed in recent market analysis. In Q4 2024, Forrester named Red Hat’s <a href="https://www.redhat.com/en/about/press-releases/red-hat-ansible-automation-platform-established-leader-infrastructure-automation-industry-research-firm">Ansible automation platform</a> a leader in its <em>Infrastructure Automation Platforms </em>report, awarding perfect scores for innovation and ecosystem.</p><p>The recognition highlights Ansible’s position not just as a popular tool, but as a strategic force in automation.</p><p><strong>Measurable ROI for enterprises</strong></p><p>Enterprise users have reported measurable improvements.</p><p>At <a href="https://www.redhat.com/en/resources/dwp-digital-case-study">BPS</a>, deployment times dropped from 50 minutes to just 10 after using Ansible’s automation platform, allowing teams to work from a single unified playbook instead of juggling fragmented toolsets.</p><h3>Efficiency gains in lean operations</h3><p>Similarly, Verizon Media, a lean operations team, boosted efficiency by 65% by automating routine infrastructure tasks with Ansible.</p><p><a href="https://medium.com/@18bhavyasharma/ansibles-impact-on-enterprises-case-studies-and-benefits-01ca8ac87732">Medium-led</a> summaries also spotlight companies like NASA, Target, and Hootsuite, all achieving operational cohesion and faster deployments through Ansible-led automation.</p><h3>Integration with broader toolchains</h3><p>It’s also telling how practitioners blend Ansible within broader toolchains. A consistent adoption pattern is pairing Ansible with Terraform, using Terraform for declarative infrastructure provisioning and Ansible for post-deployment configuration.</p><h3>Balancing growth with real-world constraints</h3><p>That said, adoption isn’t blind. Over 59,000 community posts highlight recurring issues such as performance slowdowns, patchy documentation, and tricky debugging, showing that real-world use continues to shape how teams implement Ansible.</p><h3>The future beyond Ansible</h3><p>Ansible has grown alongside the automation landscape, starting as a simple agentless open-source tool and becoming a key platform in enterprise automation. The focus, however, is beginning to shift.</p><p>One major signal of the future is AI-driven playbook generation. Red Hat’s <a href="https://www.redhat.com/en/technologies/management/ansible/ansible-lightspeed">Ansible Lightspeed</a> with IBM Watson code assistant is an early example of automation tools shifting from manual coding of workflows to guided, context-aware suggestions.</p><p>Container orchestration integration is another vector. While Kubernetes manifests and Helm charts already manage some application lifecycles, Ansible’s <a href="https://docs.ansible.com/ansible/latest/collections/kubernetes/core/index.html">Kubernetes collection</a> opens the door to blending infrastructure and application automation. Discussions on <a href="https://stackoverflow.com/questions/tagged/ansible+kubernetes">Stack Overflow</a> show interest in this unification, though some express concern about overlap with native Kubernetes tools.</p><p>In short, the “future beyond Ansible” is less about replacing it and more about augmenting and integrating it into next-generation automation fabrics. Edge execution, cloud-native pipelines, and strong community stewardship will likely decide whether Ansible continues as a central tool for infrastructure automation or evolves into a specialised component within a larger, more independent orchestration framework.</p><h3>The road ahead with Ansible</h3><p>Ansible has evolved far beyond a simple automation utility. It has become a practical way to cut through the complexity that often slows down IT operations. With playbooks written in plain language and a wide range of ready-made modules, teams can automate tasks with clarity, scale systems smoothly, and achieve consistent outcomes.</p><p>Whether it’s a few servers or a full enterprise rollout, Ansible turns plans into working systems.</p><p>As infrastructure grows more complex and teams push for faster delivery, its flexibility keeps it central to how organizations approach automation. For organizations seeking to deliver reliable, and scalable solutions, Ansible is not merely a tool to adopt today, but a strategic asset for the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6c9f3cdf94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing a Weather Data Collection System with AWS S3 and OpenWeather API]]></title>
            <link>https://medium.com/@adeyemijoshua/developing-a-weather-data-collection-system-with-aws-s3-and-openweather-api-61810a167f83?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/61810a167f83</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 19:55:51 GMT</pubDate>
            <atom:updated>2025-03-19T19:55:51.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*9nFSyet6JLPtAAZhSlTi1Q.png" /></figure><p>The Weather Dashboard is a Python-powered application designed to simplify weather data collection and visualization. By leveraging the OpenWeather API, it fetches real-time weather information for multiple cities, displaying key details such as temperature, feels-like temperature, humidity, and weather conditions. Additionally, the application integrates with AWS S3 to securely store the collected weather data, ensuring it is easily accessible and well-organized for future use.</p><p>By the end, you’ll have a functional project that combines API integration, cloud storage, and data visualization. Let’s dive in!</p><h3>Organizing Your Weather Data Project</h3><p>Here’s a quick look at how the project is structured:</p><pre>weather-dashboard/<br>├── src/<br>│ ├── __init__.py<br>│ └── weather_dashboard.py<br>├── .env<br>├── tests/<br>├── data/<br>├── .gitignore<br>└── README.md</pre><h3>Foundational Requirements</h3><p>Before starting the weather data collection project, you’ll need the following:</p><ul><li><strong>OpenWeather API Account</strong>: Register for an <a href="https://home.openweathermap.org/api_keys">OpenWeather account</a> to get your API keys for fetching weather data.</li><li><strong>Python Scripting</strong>: Basic knowledge of Python for writing scripts to fetch and process weather data.</li><li><strong>AWS S3</strong>: Understanding of AWS S3 for storing the collected weather data.</li><li><strong>AWS CLI</strong>: Basic knowledge of AWS CLI for interacting with AWS services.</li><li><strong>Linux Commands</strong>: Familiarity with basic Linux commands for navigating and executing scripts in the terminal.</li><li><strong>Git</strong>: Version control skills to manage and track changes in your project.</li></ul><p><strong>Step 1: </strong>You can find the project repository link <a href="https://github.com/ShaeInTheCloud/30days-weather-dashboard.git">here</a>. Next, open Visual Studio Code, go to the Source Control section, and clone the repository directly into your workspace. Once it’s cloned, navigate into the newly created 30days-weather-dashboard directory using the cd command.</p><p>After that, create the necessary folders by running the following command:</p><pre>mkdir tests<br>mkdir data</pre><p>Next, create a .env file using the touch command. This hidden file will store your OPENWEATHER_API_KEY, AWS_BUCKET_NAME, AWS_ACCESS_KEY_ID, and AWS_SECRET_ACCESS_KEY. The .env file holds important environment variables needed by the application, helping to keep sensitive information secure and separate from the codebase.</p><p><strong>Step 2: </strong>To get started, you’ll need to sign up with OpenWeather. Simply visit this <a href="https://openweathermap.org/">link</a> to create an account. Once registered, choose a free or paid plan, fill in the necessary details, and make sure to confirm your email address.</p><p>After confirming your email, navigate to the <strong>“API Keys” </strong>section in your account. Here, you’ll be able to find and copy your API key, which you’ll use in your project. Your API key will be displayed below, corresponding to the name you used when creating it. Ensure to save it somewhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JpFxVYoZdr3ajox2epjq3A.png" /></figure><p><strong>Step 3: </strong>To set up your AWS environment, start by signing up for an AWS account. Once you’re in, go to the S3 service in the AWS Management Console and click on <strong>“Create bucket.”</strong></p><p>Choose a name that fits your project; for example, I named mine <strong>“weather-data-buckets” </strong>But make sure the name you choose is available in your region. If the name is already taken or unavailable in your region, you won’t be able to create the bucket.<strong> </strong>If you want to keep multiple versions of your data, enable versioning. Then, configure the permissions according to your needs, such as setting the bucket to private if that’s more suitable for your project. Once you’ve chosen an available name, click on <strong>“Create Bucket.”</strong> After that, your bucket will be created, as shown in the image below, and you can proceed with configuring it as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiNNLKSTuH9ljpFEHviRfQ.png" /></figure><p>To start, go to the IAM section in the AWS Management Console. Simply search for <strong>“IAM”</strong> in the search bar and select it from the results. In the IAM dashboard, click on “Users” in the left sidebar. Then, click the <strong>“Create user”</strong> button at the top of the page.</p><p>Next, enter a username like <strong>“weather-data-user”</strong> or any name that suits your project. When you reach the “Set permissions” page, choose the option to “Attach policies directly.” After that, click on the <strong>“Create policy”</strong> button to create a custom policy that will allow access to your S3 bucket.</p><p>In the “Create policy” page, go to the “JSON” tab and paste the policy code into the editor as shown below. Make sure to replace “weather-data-bucket” with the actual name of your S3 bucket.</p><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;: &quot;s3:*&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::weather-data-bucket/*&quot;<br>    }<br>  ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvyi0VvfVOfnijuJjnUCjg.png" /></figure><p>Click on <strong>Review Policy</strong>. Give your policy a name, such as <strong>WeatherDataS3AccessPolicy</strong>, and provide a description, like “<strong>Policy to allow access to the weather data S3 bucket</strong>.” Once the policy is created, return to the <strong>Create</strong> <strong>User</strong>. In the search box, type the name of the policy you just created (e.g., <strong>WeatherDataS3AccessPolicy</strong>) and check the box next to it.</p><p>Click <strong>Next: Review</strong> to review the user details and ensure everything is correct, including the username and permissions. Once you’re satisfied, click <strong>Create User</strong>.</p><p>After the user is created, a success message will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFSBYVLRuHqbqJH-iLlQOw.png" /></figure><p><strong>Important:</strong> Make sure to save the <strong>Access Key ID</strong> and <strong>Secret Access Key</strong>. You won’t be able to view the Secret Access Key again once you close this window. You can click <strong>Download .csv</strong> to save the credentials to a file or copy them manually to a secure location.</p><p><strong>Step 4: </strong>Next, run the following command:</p><pre>aws configure</pre><p>This will prompt you to enter your <strong>Access Key ID</strong>, <strong>Secret Access Key</strong>, <strong>region</strong>, and the desired output format (usually json or text).</p><p>Next, we’ll run the following commands to set up our environment variables:</p><pre>echo &quot;OPENWEATHER_API_KEY= &lt;insert the Api key&gt;&quot; &gt;&gt; .env<br>echo &quot;AWS_BUCKET_NAME=&lt;insert the bucket name&gt;&quot; &gt;&gt; .env<br>echo &quot;AWS_ACCESS_KEY_ID=&lt;insert the access key id&gt;&quot; &gt;&gt; .env<br>echo &quot;AWS_SECRET_ACCESS_KEY=&lt;insert the secret access key&quot; &gt;&gt; .env</pre><p>These commands add the necessary environment variables to a .env file. The .env file is a hidden configuration file where sensitive data, such as API keys and access credentials, are stored. Here’s what each command does:</p><ul><li><strong>OPENWEATHER_API_KEY</strong>: Stores your OpenWeather API key, which is needed to fetch weather data.</li><li><strong>AWS_BUCKET_NAME</strong>: Specifies the name of your AWS S3 bucket where the weather data will be stored.</li><li><strong>AWS_ACCESS_KEY_ID</strong>: Stores your AWS access key, which is used to authenticate requests to AWS services.</li><li><strong>AWS_SECRET_ACCESS_KEY</strong>: Stores your AWS secret access key, which works alongside the access key to authenticate requests.</li></ul><p>If you open the .env file, you’ll see that all your sensitive data, like API keys and access credentials, are stored there securely. This file holds the environment variables we set earlier, ensuring that they’re not exposed directly in the application code.</p><p>Next, run the command:</p><pre>pip install -r requirements.txt</pre><p>Make sure that <strong>Python</strong> is installed on your Windows machine by checking the version first, as this command will only work if Python is properly set up.</p><p>This command installs all the dependencies listed in the requirements.txt file, which are necessary for the project to run smoothly. It ensures that the required libraries and packages are available for your application to function as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sl2fkxnHeop-MM8Tj4y0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RREh28B6boXhaQ1Ou3vsjA.png" /></figure><p><strong>Step 5: </strong>To ensure everything is set up correctly, verify that your Python script is intact. If needed, add the following configuration below to your weather_dashboard.py file. This will ensure your script is properly configured and ready to run.</p><pre>import os<br>import json<br>import boto3<br>import requests<br>from datetime import datetime<br>from dotenv import load_dotenv<br>import matplotlib.pyplot as plt</pre><pre># Load environment variables<br>load_dotenv()</pre><pre>class WeatherDashboard:<br>    def __init__(self):<br>        self.api_key = os.getenv(&#39;OPENWEATHER_API_KEY&#39;)<br>        self.bucket_name = os.getenv(&#39;AWS_BUCKET_NAME&#39;)<br>        self.s3_client = boto3.client(&#39;s3&#39;)</pre><pre>    def create_bucket_if_not_exists(self):<br>        &quot;&quot;&quot;Create S3 bucket if it doesn&#39;t exist&quot;&quot;&quot;<br>        try:<br>            self.s3_client.head_bucket(Bucket=self.bucket_name)<br>            print(f&quot;Bucket {self.bucket_name} exists&quot;)<br>        except:<br>            print(f&quot;Creating bucket {self.bucket_name}&quot;)<br>        try:<br>            # Simpler creation for us-east-1<br>            self.s3_client.create_bucket(Bucket=self.bucket_name)<br>            print(f&quot;Successfully created bucket {self.bucket_name}&quot;)<br>        except Exception as e:<br>            print(f&quot;Error creating bucket: {e}&quot;)</pre><pre>    def fetch_weather(self, city):<br>        &quot;&quot;&quot;Fetch weather data from OpenWeather API&quot;&quot;&quot;<br>        base_url = &quot;http://api.openweathermap.org/data/2.5/weather&quot;<br>        params = {<br>            &quot;q&quot;: city,<br>            &quot;appid&quot;: self.api_key,<br>            &quot;units&quot;: &quot;imperial&quot;<br>        }<br>        <br>        try:<br>            response = requests.get(base_url, params=params)<br>            response.raise_for_status()<br>            return response.json()<br>        except requests.exceptions.RequestException as e:<br>            print(f&quot;Error fetching weather data: {e}&quot;)<br>            return None</pre><pre>    def save_to_s3(self, weather_data, city):<br>        &quot;&quot;&quot;Save weather data to S3 bucket&quot;&quot;&quot;<br>        if not weather_data:<br>            return False<br>            <br>        timestamp = datetime.now().strftime(&#39;%Y%m%d-%H%M%S&#39;)<br>        file_name = f&quot;weather-data/{city}-{timestamp}.json&quot;<br>        <br>        try:<br>            weather_data[&#39;timestamp&#39;] = timestamp<br>            self.s3_client.put_object(<br>                Bucket=self.bucket_name,<br>                Key=file_name,<br>                Body=json.dumps(weather_data),<br>                ContentType=&#39;application/json&#39;<br>            )<br>            print(f&quot;Successfully saved data for {city} to S3&quot;)<br>            return True<br>        except Exception as e:<br>            print(f&quot;Error saving to S3: {e}&quot;)<br>            return False</pre><pre>    def visualize_weather_data(self, cities, temperatures):<br>        &quot;&quot;&quot;Visualize weather data using Matplotlib&quot;&quot;&quot;<br>        plt.bar(cities, temperatures, color=&#39;skyblue&#39;)<br>        plt.title(&quot;City Temperatures&quot;)<br>        plt.xlabel(&quot;Cities&quot;)<br>        plt.ylabel(&quot;Temperature (°F)&quot;)<br>        plt.show()</pre><pre>def main():<br>    dashboard = WeatherDashboard()<br>    <br>    # Create bucket if needed<br>    dashboard.create_bucket_if_not_exists()<br>    <br>    cities = [&quot;Philadelphia&quot;, &quot;Seattle&quot;, &quot;New York&quot;, &quot;Tokyo&quot;]<br>    temperatures = []  # List to store temperatures for visualization<br>    <br>    for city in cities:<br>        print(f&quot;\nFetching weather for {city}...&quot;)<br>        weather_data = dashboard.fetch_weather(city)<br>        if weather_data:<br>            temp = weather_data[&#39;main&#39;][&#39;temp&#39;]<br>            feels_like = weather_data[&#39;main&#39;][&#39;feels_like&#39;]<br>            humidity = weather_data[&#39;main&#39;][&#39;humidity&#39;]<br>            description = weather_data[&#39;weather&#39;][0][&#39;description&#39;]<br>            <br>            print(f&quot;Temperature: {temp}°F&quot;)<br>            print(f&quot;Feels like: {feels_like}°F&quot;)<br>            print(f&quot;Humidity: {humidity}%&quot;)<br>            print(f&quot;Conditions: {description}&quot;)<br>            <br>            # Append temperature for visualization<br>            temperatures.append(temp)<br>            <br>            # Save to S3<br>            success = dashboard.save_to_s3(weather_data, city)<br>            if success:<br>                print(f&quot;Weather data for {city} saved to S3!&quot;)<br>        else:<br>            print(f&quot;Failed to fetch weather data for {city}&quot;)<br>    <br>    # Visualize weather data<br>    dashboard.visualize_weather_data(cities, temperatures)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Here’s a breakdown of the weather_dashboard.py script and what each part does:</p><p><strong>1. Imports</strong>:</p><ul><li>The script imports essential libraries:</li><li>os for interacting with environment variables.</li><li>json for handling JSON data.</li><li>boto3 for interacting with AWS S3.</li><li>requests for making API calls.</li><li>datetime for working with timestamps.</li><li>dotenv for loading environment variables from the .env file.</li></ul><p><strong>2. WeatherDashboard Class</strong>:</p><ul><li><strong>Initialization</strong>: The __init__ method loads the API key and bucket name from the .env file and sets up the S3 client.</li><li><strong>Create S3 Bucket</strong>: The create_bucket_if_not_exists method checks if the specified S3 bucket exists. If not, it creates the bucket.</li><li><strong>Fetch Weather Data</strong>: The fetch_weather method uses the OpenWeather API to get the weather data for a specified city. It sends a request with the city name and API key, then processes the response.</li><li><strong>Save to S3</strong>: The save_to_s3 method saves the weather data to the S3 bucket. It generates a timestamped file name and uploads the data in JSON format.</li></ul><p><strong>3. Main Function</strong>:</p><ul><li>The main function creates an instance of the WeatherDashboard class, ensures the S3 bucket exists, and fetches weather data for a list of cities.</li><li>It prints out the weather information and saves it to the S3 bucket if the data retrieval is successful.</li></ul><h3>Summary of Configuration:</h3><ul><li><strong>Environment Variables</strong>: The script loads sensitive information like the OpenWeather API key and AWS S3 bucket name from the .env file. This keeps your credentials secure and out of the main code.</li><li><strong>Weather Data Fetching</strong>: The script fetches current weather information (temperature, humidity, etc.) for different cities from the OpenWeather API.</li><li><strong>S3 Bucket</strong>: The script interacts with AWS S3 to create a bucket if it doesn’t exist and store the fetched weather data in a structured JSON format.</li></ul><p>To run the script, use the following command:</p><pre>python3 src/weather_dashboard.py</pre><h3>What it does:</h3><ul><li>Executes the Python script to get weather data for the cities.</li><li>Saves the data as JSON files to your S3 bucket.</li></ul><p>This command completes the process of collecting and storing weather data.</p><p>After running the command, you should see the output similar to the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*AN0lXqcaXj9nYcIoUkMoSg.png" /></figure><p>Run the command:</p><pre>pip install matplotlib</pre><p>This command installs Matplotlib, a popular Python library used for creating a wide variety of data visualizations. With Matplotlib, you can turn raw data into insightful charts, such as line graphs, bar charts, scatter plots, and more. It’s a powerful tool for making complex information easier to understand and visually appealing.</p><p>Next, run the command: python3 src/weather_dashboard.py.</p><p>This will execute the script and display a bar chart, as illustrated in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0n0SCG28wh0-A94JmriMw.png" /></figure><h3>Conclusion</h3><p>This Weather Dashboard project demonstrates how to integrate Python with APIs, AWS S3, and data visualization tools to create a practical, real-world application. By leveraging the OpenWeather API, the script fetches weather data for multiple cities, stores it securely in an AWS S3 bucket, and visualizes the information using Matplotlib. This not only highlights the power of automation but also emphasizes the importance of organizing and securing sensitive data using environment variables and cloud storage.</p><p>Running the command python3 src/weather_dashboard.py completes the process by fetching the weather data, saving it to S3, and displaying a bar chart to help interpret the results.</p><p>Thank you for following along! Don’t forget to like, comment, and follow for more insightful articles on DevOps and Python automation. 🚀</p><p><strong>Connect with me on:</strong></p><ul><li><a href="https://www.linkedin.com/in/joshua-adeyemi-5676b2213?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=android_app">LinkedIn</a></li><li><a href="https://x.com/iamjoshlite?t=NylKpX_a8lWF0PVnqORumQ&amp;s=09">Twitter</a></li><li><a href="http://hellojoshlite@gmail.com/">Email</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61810a167f83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Terraform Module Usage]]></title>
            <link>https://medium.com/@adeyemijoshua/mastering-terraform-module-usage-feaa01bb85b7?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/feaa01bb85b7</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[hashicorp]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 14:29:43 GMT</pubDate>
            <atom:updated>2025-02-23T14:29:43.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qM0iygUWvejt5cnC3BMXAQ.png" /></figure><p>In the realm of Infrastructure as Code (IaC), <strong>Terraform</strong> stands out as one of the most popular tools for provisioning and managing cloud infrastructure. One of the key features that enhance Terraform’s usability and scalability is <strong>Terraform Modules</strong>. Whether you are a novice or a seasoned DevOps professional, understanding and effectively utilizing Terraform modules will significantly streamline your infrastructure management, improve reusability, and ensure consistency across projects.</p><p>This article explores Terraform modules, demonstrating how they streamline your infrastructure as code.</p><h3>What are terraform modules?</h3><p>At its core, a <strong>Terraform module</strong> is a container for multiple resources that are used together. A module allows you to group related resources, making your Terraform configurations cleaner, reusable, and easier to manage. Instead of writing the same code repeatedly, you can define a module once and reference it as needed throughout your infrastructure.</p><p>By using modules, you encapsulate parts of your Terraform code into logical units, which improves readability and reduces errors, especially as your infrastructure grows. Modules also allow you to version and distribute reusable components, helping you scale across multiple environments with minimal changes.</p><p><a href="https://www.terraform.io/docs/modules/index.html">Learn more about Terraform modules in the official documentation</a>.</p><h3>Why use modules?</h3><p>Using Terraform modules offers several advantages:</p><ol><li><strong>Reusability</strong>: Modules enable you to reuse the same code across different projects or environments, saving time and ensuring consistency.</li><li><strong>Abstraction</strong>: They abstract complex logic into simple, callable units, making it easier to manage infrastructure at scale.</li><li><strong>Collaboration</strong>: With a modular approach, multiple teams can work on different parts of the infrastructure independently, promoting collaboration and reducing conflicts.</li><li><strong>Maintainability</strong>: Modular code is easier to update and maintain, as you can modify a module once, and all references to it automatically reflect the changes.</li></ol><h3>Understanding terraform module structure</h3><p>A Terraform module can consist of several files, but the essential structure includes:</p><ul><li><strong>main.tf</strong>: Defines the resources within the module.</li><li><strong>variables.tf</strong>: Contains variable definitions that allow customization of the module.</li><li><strong>outputs.tf</strong>: Specifies the values that the module will return when it’s used.</li><li><strong>README.md</strong>: A documentation file that explains the purpose of the module and how to use it.</li></ul><p>Consider the following simple example: a module for creating an AWS EC2 instance.</p><pre># main.tf<br>resource &quot;aws_instance&quot; &quot;example&quot; {<br>  ami           = var.ami<br>  instance_type = var.instance_type<br>}<br><br># variables.tf<br>variable &quot;ami&quot; {<br>  description = &quot;The AMI to use for the instance.&quot;<br>  type        = string<br>}<br>variable &quot;instance_type&quot; {<br>  description = &quot;The type of the instance.&quot;<br>  type        = string<br>}<br><br># outputs.tf<br>output &quot;instance_id&quot; {<br>  description = &quot;The ID of the created EC2 instance.&quot;<br>  value       = aws_instance.example.id<br>}</pre><p>In this example:</p><ul><li>The <strong>main.tf</strong> file defines the EC2 instance resource.</li><li>The <strong>variables.tf</strong> file specifies the input variables such as ami and instance_type.</li><li>The <strong>outputs.tf</strong> file exposes the instance ID as an output value.</li></ul><p>By organizing your code in this way, you ensure modularity and make it easier to maintain and scale.</p><h3>Types of modules</h3><p>When using Terraform, you will encounter two types of modules:</p><ol><li>Root Modules</li><li>Child Modules</li></ol><h3>Root module</h3><p>The <strong>root module</strong> is the top-level module that Terraform executes when you run commands like terraform plan or terraform apply. It typically contains the main configuration and may include references to child modules.</p><p>For example, the root module might be the one containing your high-level infrastructure configuration (e.g., the VPC, security groups, and EC2 instances) and can call child modules to organize and manage complex components.</p><h3>Child modules</h3><p>A <strong>child module</strong> is any module that is called by another module, usually the root module. Child modules allow you to break down complex configurations into smaller, manageable units. You can have as many child modules as necessary, and each one can contain its own resources, variables, and outputs.</p><h3>Using community modules</h3><p>Terraform’s community module registry is a rich source of pre-built modules created by the Terraform community. You can take advantage of these pre-built modules to save time, but it’s important to assess the quality and suitability of the modules for your environment.</p><p>For example, instead of writing your own module for deploying an AWS S3 bucket, you can use the community-provided module:</p><pre>module &quot;s3&quot; {<br>  source = &quot;terraform-aws-modules/s3-bucket/aws&quot;<br>  bucket = &quot;my-bucket&quot;<br>}</pre><p>By using community modules, you can leverage best practices and avoid reinventing the wheel, but always ensure that the module meets your specific requirements. The <a href="https://registry.terraform.io/">Terraform Registry</a> is the best place to find and share reusable modules.</p><h3>Creating your own terraform module</h3><p>Now that you understand the importance of modules, let’s look at how to create your own. The first step is structuring your module correctly, ensuring that it is maintainable.</p><h3>Basic structure of a terraform module</h3><p>A simple example of creating a module to launch an AWS EC2 instance might look like this:</p><p><strong>1.Define the resources</strong> (in main.tf):</p><pre>resource &quot;aws_instance&quot; &quot;example&quot; {   <br>ami           = var.ami   <br>instance_type = var.instance_type }</pre><p><strong>2. Specify input variables</strong> (in variables.tf):</p><pre>variable &quot;ami&quot; {   <br>description = &quot;The AMI to use for the instance.&quot;   <br>type        = string }  <br><br>variable &quot;instance_type&quot; {   <br>description = &quot;The type of the instance.&quot;   <br>type        = string }</pre><p><strong>3. Define outputs</strong> (in outputs.tf):</p><pre>output &quot;instance_id&quot; {   <br>description = &quot;The ID of the created EC2 instance.&quot;   <br>value       = aws_instance.example.id }</pre><p><strong>4. Document the module</strong> (in README.md): The README file should provide a description of the module, including how to use it and any important details about the variables and outputs.</p><h3>Best practices for writing modules</h3><ul><li><strong>Keep modules simple and generic</strong>: Design modules so they can be reused in various contexts. Avoid hardcoding values.</li><li><strong>Use clear and descriptive variable names</strong>: This makes it easier for others (and yourself) to understand how to use the module.</li><li><strong>Document your module</strong>: Every module should include a README with a clear explanation of its purpose, usage instructions, and examples.</li><li><strong>Version control</strong>: Always version your modules, especially if they are being shared or reused across projects.</li></ul><p><a href="https://www.terraform.io/docs/modules/write.html">Check the Terraform documentation for more about writing modules</a>.</p><h3>Using modules in terraform</h3><p>Once you’ve defined your modules, you can reference them in your Terraform configuration. Here’s how you can use a module to create an EC2 instance:</p><h4>Calling a module</h4><p>To call the EC2 instance module you created earlier, you would add the following to your root configuration:</p><pre>module &quot;ec2_instance&quot; {<br>  source         = &quot;./modules/ec2_instance&quot;<br>  ami            = &quot;ami-0c55b159cbfafe1f0&quot;<br>  instance_type  = &quot;t2.micro&quot;<br>}</pre><h4>Passing variables to modules</h4><p>Modules can accept input variables, which allow you to pass different values when calling the module:</p><pre>module &quot;ec2_instance&quot; {<br>  source         = &quot;./modules/ec2_instance&quot;<br>  ami            = var.ami<br>  instance_type  = var.instance_type<br>}</pre><p>In this example, var.ami and var.instance_type are input variables passed to the module. This allows you to reuse the module with different parameters for different environments.</p><h4>Receiving outputs from modules</h4><p>Modules can return outputs, which can be accessed using the module.&lt;module_name&gt;.&lt;output_name&gt; syntax. For example:</p><pre>output &quot;instance_id&quot; {<br>  value = module.ec2_instance.instance_id<br>}</pre><p>This allows you to extract information from the module and use it elsewhere in your configuration.</p><h3>Advanced module features</h3><p>As you grow more comfortable with modules, you’ll want to explore some of the advanced features Terraform offers.</p><h3>Nested modules</h3><p>Modules can call other modules, which enables the creation of complex infrastructures. For example, you could have a “network” module that contains sub-modules for VPC, subnets, and security groups.</p><pre>module &quot;network&quot; {<br>  source = &quot;./modules/network&quot;<br><br># Call other modules inside the network module<br>  module &quot;vpc&quot; {<br>    source = &quot;./modules/vpc&quot;<br>    cidr_block = var.vpc_cidr<br>  }<br>}</pre><h3>Managing module dependencies</h3><p>Terraform handles dependencies between modules automatically, ensuring that resources are created in the correct order. However, you can use the depends_on attribute to explicitly specify dependencies between modules.</p><pre>module &quot;ec2_instance&quot; {<br>  source = &quot;./modules/ec2_instance&quot;<br>  depends_on = [module.vpc]<br>}</pre><p>This ensures that the EC2 instance is created only after the VPC module is successfully applied.</p><h3>Module versioning</h3><p>Versioning modules is crucial for managing infrastructure at scale. You can specify which version of a module to use by defining a version constraint:</p><pre>module &quot;ec2_instance&quot; {<br>  source  = &quot;terraform-aws-modules/ec2-instance/aws&quot;<br>  version = &quot;~&gt; 2.0&quot;<br>}</pre><p>This ensures that Terraform uses the correct version of the module and prevents breaking changes from affecting your infrastructure.</p><h3>Testing and debugging terraform modules</h3><p>Testing your modules is essential before deploying them in production environments. Use terraform plan to review what changes will be made, and terraform apply to apply the changes.</p><p>If you encounter any issues, review the error messages carefully, as they often provide insight into what went wrong.</p><p><a href="https://www.terraform.io/docs/commands/plan.html">Learn more about testing Terraform modules here</a>.</p><h3>Common use cases for terraform modules</h3><p>Modules are incredibly useful in a variety of scenarios. Some common use cases include:</p><h4>1. Multi-Environment deployments</h4><p>You can create separate modules for different environments (e.g., dev, staging, prod), and use variables to customize the configuration for each environment.</p><h4>2. Multi-Cloud deployments</h4><p>Modules allow you to standardize infrastructure across multiple cloud providers. For example, you could create separate modules for AWS, Azure, and Google Cloud, then call them as needed.</p><h4>3. Large-Scale infrastructure</h4><p>For large infrastructure projects, modules help you break down the architecture into manageable pieces, reducing complexity and increasing maintainability.</p><h3>Conclusion</h3><p>Terraform modules are an essential tool for creating maintainable, and scalable infrastructure code. By abstracting common configurations into modules, you can significantly improve the efficiency and consistency of your Terraform workflows. With the added benefits of community modules, version control, and best practices, using Terraform modules enables you to build infrastructure faster while minimizing errors and maintenance overhead.</p><p>By following the best practices outlined above, you can master the art of modularizing. I hope this article provided valuable insights into Terraform modules. If you found this helpful, don’t forget to clap, follow, and stay tuned for more articles like this. Thank you for reading!.</p><p><strong>Connect with me on:</strong></p><ul><li><a href="https://www.linkedin.com/in/joshua-adeyemi-5676b2213?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=android_app">LinkedIn</a></li><li><a href="https://x.com/iamjoshlite?t=NylKpX_a8lWF0PVnqORumQ&amp;s=09">Twitter</a></li><li><a href="http://hellojoshlite@gmail.com/">Email</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feaa01bb85b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game Day Alerts: Creating a Real-Time NBA Score Notification System with AWS Tools]]></title>
            <link>https://medium.com/@adeyemijoshua/game-day-alerts-creating-a-real-time-nba-score-notification-system-with-aws-tools-8cb6a7718778?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cb6a7718778</guid>
            <category><![CDATA[nba]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 16:03:45 GMT</pubDate>
            <atom:updated>2025-02-23T13:46:31.803Z</atom:updated>
            <content:encoded><![CDATA[<h3>Technical Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*u7Dc6IXwm0w84MS-_yEYVA.png" /></figure><p>This project focuses on creating an alert system designed to deliver real-time NBA game scores to subscribers via SMS or email. By leveraging services like Amazon SNS, AWS Lambda, and EventBridge, alongside Python and the NBA API, the system ensures fans stay informed with timely updates.</p><p>The system works by retrieving live game scores, formatting the data, and sending notifications directly to users through Amazon SNS. Automation is seamlessly integrated using EventBridge, allowing updates to be scheduled and delivered regularly without manual intervention.</p><p>Security remains a core aspect of the design, with IAM roles configured to enforce the principle of least privilege, ensuring access is restricted to only what is necessary. This project demonstrates the practical application of cloud computing technologies to create a robust and efficient notification service tailored for sports enthusiasts.</p><h3>Project Structure</h3><p>Let’s take a closer look at how the project is organized:</p><pre>game-day-notifications/<br>├── src/<br>│   ├── gd_notifications.py          # Main Lambda function code<br>├── policies/<br>│   ├── gb_sns_policy.json           # SNS publishing permissions<br>│   ├── gd_eventbridge_policy.json   # EventBridge to Lambda permissions<br>│   └── gd_lambda_policy.json        # Lambda execution role permissions<br>├── .gitignore<br>└── README.md                        # Project documentation</pre><h3>Technologies Used</h3><p>This project leverages the following technologies:</p><ul><li><strong>Cloud Provider</strong>: AWS</li><li><strong>Core Services</strong>: SNS, Lambda, and EventBridge</li><li><strong>External API</strong>: NBA Game API (provided by SportsData.io)</li><li><strong>Programming Language</strong>: Python 3.x</li><li><strong>IAM Security</strong>: We’ve implemented least privilege policies for Lambda, SNS, and EventBridge to ensure secure access.</li></ul><h3>Prerequisites</h3><p>Before you begin, make sure you have the following:</p><ul><li>A personal AWS account, along with a basic understanding of AWS services and Python</li><li>Familiarity with Linux commands</li><li>A free account with a subscription and an API key from <a href="https://sportsdata.io/members/subscriptions">SportsData.io</a></li></ul><blockquote>Let’s get into it</blockquote><h3>Creating an SNS Topic</h3><p>Head over to the AWS Management Console and find the SNS service. Click on “Create Topic” and choose “Standard” as the topic type. Give your topic a name (for example, GameAlerts), and make sure to note down the <strong>ARN</strong>. You can choose any name that fits your project. Once you’re ready, click “Create Topic” to finish.</p><p>Once you’ve created the topic, click on its name from the list. Go to the “Subscriptions” tab and click on “Create subscription.” For the protocol, select “Email” if you want to send notifications via email, and enter a valid email address (e.g., tolu123@gmail.com). If you want to use SMS, choose “SMS” and enter a phone number in international format (e.g., +1234567890). Afterward, click “Create Subscription.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLQaGoW6N8hYInSUfkpcew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Unn54RoGYFF8mKt3cyYCbg.png" /></figure><p>If you selected Email, check the inbox of the provided email address and confirm the subscription by clicking the link in the email. For SMS, the subscription will be active right away.</p><h3>Creating the SNS Publish Policy</h3><p>In the AWS Management Console, open the IAM service. Go to “Policies” and click “Create Policy.” Choose the <strong>“JSON”</strong> tab and paste the JSON policy from the gamesalerts_sns_policy.json file you downloaded from the repository.</p><p>Be sure to replace REGION and ACCOUNT_ID with your specific AWS region and account ID.</p><p>Click “Next: Tags” (you can skip adding tags). Then click “Next: Review.” Give your policy a name, like gamesalerts_sns_policy, review the details, and finally, click &quot;Create Policy.&quot;<strong> </strong>The gamesalerts_sns_policy has been successfully set up, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ms57xycSTDOSnzsqyYl3w.png" /></figure><h3>Setting Up an IAM Role for Lambda</h3><p>To set up the role in the AWS Management Console, navigate to the <strong>IAM</strong> service and click on <strong>Roles</strong>, then select <strong>Create Role</strong>. Choose <strong>AWS Service</strong> as the trusted entity and pick <strong>Lambda</strong> from the list. Next, attach the required policies: the <strong>SNS Publish Policy</strong> (e.g., gamesalerts_sns_policy, which you created earlier) and the <strong>Lambda Basic Execution Role</strong> (AWSLambdaBasicExecutionRole, an AWS-managed policy) shown in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7DgTY-g0I6p-2k26zuWPw.png" /></figure><p>Click <strong>Next: Tags</strong> (you can skip this step), followed by <strong>Next: Review</strong>. Give the role a descriptive name, such as Game_Notification_Role as shown in the image below. After reviewing the details, click <strong>Create Role</strong>. Finally, copy and save the role&#39;s ARN, as you&#39;ll need it for the Lambda function setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNm1WwmSgQBlm6KTZ6bhkw.png" /></figure><h3>How to Deploy a Lambda Function</h3><p>Go to the <strong>Lambda</strong> service and click <strong>Create Function</strong>. Select <strong>Author from scratch</strong> and provide a name for your function (e.g., Game_Notification_Handler or any name you prefer). Choose <strong>Python 3.x</strong> as the runtime. Under the execution role settings, select <strong>Change default execution role</strong> and choose <strong>Use an existing role</strong>. Assign the IAM role you created earlier (Game_Notification_Role) to the function. Finally, click <strong>Create Function</strong>, as illustrated in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4turTBdndpplylhhZkfJg.png" /></figure><p>Scroll down to the <strong>Code</strong> section in your Lambda function. Open the lambda_function.py file, delete the existing code, and replace it with the contents of the src/game_notification.py file from the repository. Paste the code into the inline editor and click <strong>Deploy</strong>.</p><p>Next, retrieve your NBA API key from <a href="https://sportsdata.io/members/subscriptions"><strong>sportsdata.io</strong></a> (as shown in the image).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHEuzTeKTOYH6xwb6A-oUQ.png" /></figure><p>Navigate to the <strong>Environment Variables</strong> section and click <strong>Edit</strong>. Add the following key-value pairs:</p><ul><li>NBA_API_KEY: Your NBA API key</li><li>SNS_TOPIC_ARN: The ARN of the SNS topic you created earlier</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*3N2haqiIw4Tm5u4RneEivQ.png" /></figure><p>Once done, click <strong>Save</strong> to apply the changes.</p><p>Next, go to the <strong>Test</strong> tab and name the event test1. Save the test configuration and click <strong>Test</strong> to execute it. The function should run successfully, as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HpiNi-mbgL2Y0uiYt2xKw.png" /></figure><p>Afterward, you’ll receive an email notification containing NBA game scores and other details, confirming that everything ran successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxLQQ3IP7SqENk3Li75k6Q.png" /></figure><h3>Automating Updates with EventBridge</h3><p>Go to the <strong>EventBridge</strong> service in the AWS Management Console and navigate to <strong>Rules</strong> → <strong>Create Rule</strong>. Choose <strong>Event Source</strong> as <strong>Schedule</strong> and proceed with the Continue in EventBridge scheduler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3Og5NnKKTgti4hFQs39dQ.png" /></figure><p>Select <strong>Recurring Schedule</strong> and configure the cron schedule based on when you want updates (e.g., specific hours, days of the week, or year).</p><p>Under the <strong>Targets</strong> section, select the Lambda function (GameNotificationHandler) and click <strong>Create Schedule</strong>. Finally, save your changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obnDC6zLkTNGbUeoyVakuw.png" /></figure><h3>Conclusion</h3><p>This project demonstrates how to leverage AWS services and Python to create a robust and efficient alert system for real-time NBA game updates. By combining Amazon SNS, Lambda, EventBridge, and the NBA API, we’ve built a solution that delivers timely notifications to subscribers via SMS or email.</p><p>Through careful integration of automation and security best practices, the system ensures updates are consistent, reliable, and protected. From setting up the SNS topic to deploying the Lambda function and automating updates with EventBridge, each step highlights the power and flexibility of cloud computing in solving real-world problems.</p><p>I hope this article has been insightful and inspires you to explore more possibilities with AWS and Python. If you found this helpful, don’t forget to clap, follow, and stay tuned for more articles like this. Thank you for reading!</p><p><strong>Connect with me on:</strong></p><ul><li><a href="https://www.linkedin.com/in/joshua-adeyemi-5676b2213?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=android_app">LinkedIn</a></li><li><a href="https://x.com/iamjoshlite?t=NylKpX_a8lWF0PVnqORumQ&amp;s=09">Twitter</a></li><li><a href="http://hellojoshlite@gmail.com/">Email</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cb6a7718778" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Apache2 Web Hosting on Ubuntu EC2 with HTTPS and a Free SSL Certificate]]></title>
            <link>https://medium.com/@adeyemijoshua/how-to-set-up-apache2-web-hosting-on-ubuntu-ec2-with-https-and-a-free-ssl-certificate-08ecc3750e73?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/08ecc3750e73</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 14:03:04 GMT</pubDate>
            <atom:updated>2024-12-16T14:03:04.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tl2nrbchzsEoV-zGo6qZwg.png" /></figure><h3>Introduction</h3><p>Although we often refer to Apache as a web server, it’s important to note that it’s not a physical server. Instead, Apache is a software that operates on an HTTP server. Its main role is to establish a connection between the server and the browsers of website visitors — whether it’s Firefox, Google Chrome, Safari, or others — by delivering files back and forth in a client-server structure. What makes Apache even more versatile is its compatibility with virtually any operating system, from Windows to Unix, making it a go-to solution for many web developers.</p><p>When a visitor wants to load a page on your website, like the homepage or the “About Us” page, their browser sends a request to your server. Apache then responds by sending back all the necessary files — such as text, images, and other content — that make up the requested page.</p><p>This communication happens through the HTTP protocol, and Apache plays a key role in ensuring smooth and secure interaction between the server and the client. It acts as the middleman, making sure the connection is established and the content is delivered efficiently.</p><p>In this article, we will walk you through the process of setting up Apache2 web hosting on an Ubuntu EC2 instance and configuring HTTPS using a free SSL certificate. By following this guide, you will be able to deploy a secure and reliable web server on your EC2 instance, ensuring both accessibility and protection for your website. Let’s dive into the steps to get your web server up and running with HTTPS encryption.</p><h3>Prerequisites</h3><p>To successfully complete this project, it’s important to have a solid understanding of the following basics:</p><ul><li>Basic knowledge of Linux commands</li><li>Understanding how to set up an EC2 instance with the correct security groups</li><li>Gitbash or Visual Studio Code (VSCode) can be used as your development environment</li></ul><blockquote>Let’s begin</blockquote><h3>Part 1: Launching the Ubuntu WebPage-01 Instance</h3><p>Go to the AWS Console, click “Launch Instance,” name it <strong>“webpage-01,”</strong> choose Ubuntu for the OS, and ensure the instance type is free-tier eligible to prevent extra charges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*7MSyCOz-wDnL_xalgUjw9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*nrB9lQFjA6eGtGFdLVfPXw.png" /></figure><p>Create a new key pair named “webapage-key-pair” and, under the network settings, enable HTTP and HTTPS traffic from the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*eDLUD8NhYVBe5syi_su_zw.png" /></figure><p>Click “Launch Instance,” and your instance will be up and running, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFOyPge41dWB9hCD6TjpEQ.png" /></figure><h3>Part 2: Updating the Instance and Installing Apache2 Web Server</h3><p>SSH into your instance using your preferred terminal, whether it’s Gitbash or Visual Studio Code or Termius. Your instance should now be connected, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*ItxSC4PdS3ZVUCR3I-cMTA.png" /></figure><p>Next, run the following command to update your instance and install Apache2. Make sure Apache2 was installed successfully.</p><pre>sudo apt update -y<br><br>sudo apt install apache2 -y </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*JvyKq59BEYq5xERtQOEiyA.png" /></figure><p>To check if Apache2 is running correctly, use the command below:</p><pre>sudo systemctl status apache2 </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*hqMGlGoZSk7-ICnO8FPp_g.png" /></figure><p>To confirm if the Apache2 webpage is working, copy your instance’s public IP address and paste it into your Chrome browser’s URL bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*jirQVpQAr30ahPxOrw7V_Q.png" /></figure><p>The webpage should now be displayed as shown above.</p><h3>Part 3: Clone the repository and assign the required permissions.</h3><p>Use the git clone command to clone the repository containing your HTML, CSS, and other files that will serve as your landing page.</p><p>Use the ls command to verify that your repository was downloaded, then navigate into it with cd to confirm that the HTML and other files were cloned successfully.</p><p>We’ll move the cloned repository to /var/www/. In this case, the repository I cloned is named altschool-assignment-1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*_qmSL301bbKKe4zZndDE4w.png" /></figure><p>Navigate to the sites-available folder and duplicate the default configuration file to create one for your repository. Run the command below to achieve this:</p><pre>cd /etc/apache2<br><br>cd sites-available<br><br>ls<br><br>sudo cp 000-default.conf altschool-assignment-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*Xe8JNIGuyTmyMUlMkv61tg.png" /></figure><p>As shown above, you can now see the sites-available folder.</p><p>Next, edit the altschool-assignment-1.conf configuration file using the command below:</p><pre>sudo nano altschool-assignment-1.conf</pre><p>Be sure not to edit my configuration file. Instead, make changes to your own.</p><p>When editing the configuration file, make sure to add the following configuration where necessary:</p><pre>ServerName altschool-assignment-1.com<br><br>ServerAlias www.altschool-assignment-1.com<br><br>DocumentRoot /var/www/altschool-assignment-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*0stzLjlLA2G88wj41V-aUQ.png" /></figure><p>Next, apply the necessary permissions and disable the default configuration file using the following commands:</p><pre> sudo chown -R $USER:$USER /var/www/altschool-assignment-1<br><br> sudo chown -R 755 /var/www<br><br> sudo a2dissite 000-default.conf</pre><ul><li>sudo chown -R $USER:$USER /var/www/altschool-assignment-1: This command changes the ownership of the altschool-assignment-1 directory and its contents to the current user, ensuring that you have the necessary permissions to modify the files.</li><li>sudo chown -R 755 /var/www: This command sets the correct permissions for the /var/www directory, allowing read, write, and execute access for the owner, and read and execute access for others.</li><li>sudo a2dissite 000-default.conf: This command disables the default Apache site configuration, ensuring that only your custom site configuration (in this case, altschool-assignment-1) is active.</li></ul><p>Set a password for the instance by running the commandsudo passwd ubuntu.</p><p>Next, run the following command to ensure the cloned repository, containing the index.html and other files, is uploaded successfully.</p><pre> sudo a2ensite altschool-assignment-1</pre><p>The command sudo a2ensite altschool-assignment-1 is used to activate a specific site configuration in Apache2. When you run this command, it creates a symbolic link between the site configuration file (like altschool-assignment-1.conf) in the sites-available directory and the sites-enabled directory, instructing Apache to recognize and serve the site.</p><p>After that, reload Apache2, then restart, start, and check its status using the following commands.</p><pre>systemctl reload apache2<br><br>sudo systemctl restart apache2<br><br>sudo systemctl start apache2<br><br>sudo systemctl status apache2</pre><h3>Part 4: Verify IP and Configure HTTPS with a Free SSL Certificate</h3><p>Verify by copying the IP address of your instance and pasting it into any browser of your choice to ensure the cloned webpage displays successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3sugZwxbfxpaD_AazZ5-1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*oVEhXq2ZlW00eR5uYiV6AA.png" /></figure><p>Next, create a domain for your webpage by clicking this <a href="https://freedns.afraid.org/subdomain/">link</a> and connecting it to your instance’s IP address. For example, my domain is web.josh.mooo.com, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*2WCB8qB8sgLTQ1T9pjTn0g.png" /></figure><p>Next, set up HTTPS for your web server using a free SSL certificate from Let’s Encrypt. Start by running the following commands:</p><pre>sudo apt update<br><br>sudo apt install certbot python3-certbot-apache -y</pre><ul><li>The first command, sudo apt update, refreshes your package lists to ensure you’re downloading the latest versions of software.</li><li>The second command, sudo apt install certbot python3-certbot-apache -y, installs Certbot (the tool for managing SSL certificates) and its Apache plugin, which automates the configuration process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBMJgNpSocN6JBKbClrehw.png" /></figure><p>To obtain an SSL certificate and automatically configure HTTPS for your domain, run the following command:</p><pre>sudo certbot --apache -d web.josh.mooo.com</pre><p>Here’s what happens when you run this command:</p><ul><li>Certbot interacts with the Apache server to set up the SSL certificate for your domain.</li><li>You’ll be prompted to provide an email address for important notifications, such as renewal reminders, and to agree to Let’s Encrypt’s terms of service.</li><li>Certbot then verifies your domain ownership and fetches the SSL certificate.</li><li>Once the certificate is retrieved, Certbot automatically configures your Apache server to enable HTTPS for your domain.</li></ul><p>This process ensures that your website is secured and accessible via HTTPS.</p><p>Once you run the command above, the SSL certificate should be successfully deployed, as demonstrated in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*WES916zF-aVxanahLgrbJw.png" /></figure><p>Open your browser and go to https://web.josh.mooo.com. Check that the connection is secure by looking for the padlock icon in the address bar.</p><p>As shown in the image below, the connection is secure, and the webpage is displayed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlB0HTcH6UxY1LCntwNGxQ.png" /></figure><p><strong>Note: </strong>This uses the domain name I created, so be sure to create your own and avoid using mine when following this article.</p><h3>Conclusion</h3><p>You’ve now completed the process of launching your Ubuntu web server on AWS, cloning your repository, configuring Apache2, and securing your website with HTTPS using a free SSL certificate from Let’s Encrypt. This guide has equipped you with the knowledge and skills to set up a secure and efficient web server, ensuring your site is both accessible and protected.</p><p>Thank you for reading. Don’t forget to like, comment, and follow for more insightful articles on DevOps topics.</p><p><strong>Connect with me on:</strong></p><ul><li><a href="https://www.linkedin.com/in/joshua-adeyemi-5676b2213?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=android_app">LinkedIn</a></li><li><a href="https://x.com/iamjoshlite?t=NylKpX_a8lWF0PVnqORumQ&amp;s=09">Twitter</a></li><li><a href="http://hellojoshlite@gmail.com/">Email</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08ecc3750e73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying and Monitoring Full-Stack Applications with Docker, Nginx, and Grafana in the Cloud]]></title>
            <link>https://medium.com/@adeyemijoshua/deploying-and-monitoring-full-stack-applications-with-docker-nginx-and-grafana-in-the-cloud-2e469648866a?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e469648866a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[domains]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 22:32:46 GMT</pubDate>
            <atom:updated>2024-12-02T14:11:58.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Vhez1nCHN9IxLJ7m9jGfg.png" /></figure><h3>Introduction</h3><p>In this article, we’ll explore how to deploy a full-stack application using Docker Compose while also setting up monitoring and logging tools to keep track of the application’s health and extract meaningful insights from the logs.</p><p><strong>Prometheus</strong> is an exceptional technology designed to collect and store time series data. Time series data is at the heart of Prometheus, and its data model is structured around two key elements:</p><ul><li><strong>Metrics</strong>, which consist of a timestamp and a numeric sample value — like the number of disk bytes read or the current stock price.</li><li><strong>Labels</strong>, which add context to the metrics. Labels act as dimensions, such as <em>job</em> or <em>device</em>, helping you better understand the data.</li></ul><p>On the other hand, <strong>Grafana</strong> takes this data to the next level. It enables you to collect, correlate, and visualize metrics and logs through stunning dashboards. As an open-source visualization and monitoring solution, Grafana empowers you to make informed decisions, improve system performance, and simplify troubleshooting with ease.</p><p>And let’s not forget <strong>Nginx Proxy Manager</strong> — a game-changer in the realm of reverse proxy configurations. This open-source tool simplifies the process of managing NGINX with a user-friendly, web-based interface. Whether you’re handling multiple domains or subdomains, this project is perfect for streamlining the deployment and maintenance of web applications and services through a centralized, intuitive platform.</p><h3>Foundational Requirements</h3><p>To ensure the successful setup of this project, you’ll need the following foundational knowledge:</p><ul><li>A basic understanding of Linux commands</li><li>Knowledge of how to set up an EC2 instance with the appropriate security groups</li><li>Familiarity with <strong>Prometheus</strong> and <strong>Grafana</strong></li><li>Essential Docker commands and how to install <strong>Docker</strong> on an<strong> EC2 instance</strong></li><li>A registered domain name for custom deployment.</li><li>Gitbash or Visual Studio Code (VSCode) for your development environment</li></ul><h3>Project Overview: Full-Stack Deployment and Monitoring Setup</h3><p>We’ll be deploying a full-stack application and a monitoring stack with a focus on automation, scalability, and real-time monitoring.</p><p>We’ll containerize a <strong>React frontend</strong>, <strong>FastAPI backend</strong>, and <strong>PostgreSQL database</strong> using Docker. This ensures portability and ease of management across environments.</p><p>We’ll implement <strong>Prometheus</strong> for metrics scraping, <strong>Grafana</strong> for dashboard visualization, <strong>Loki</strong> for log management, and <strong>cAdvisor</strong> for container monitoring. These tools will provide insights into the health and performance of the application.</p><p>Instead of Traefik, we’ll configure <strong>Nginx Proxy Manager</strong> to handle reverse proxying, SSL encryption, and routing between the services.</p><p>We’ll set up shared Docker networks for seamless communication between containers, ensuring everything works together without issues.</p><p>Once the system is set up and tested, we’ll deploy it to the cloud using a <strong>custom domain</strong>. The domain will be obtained from <a href="https://freedns.afraid.org/subdomain/"><strong>FreeDNS</strong></a> for easy, free DNS management.</p><p>By the end of this project, you’ll have a scalable, secure, and monitored full-stack application running smoothly in the cloud.</p><h3>Setting Up EC2 and Containerizing a Full-Stack Application</h3><p>We’ll begin by setting up an Ubuntu EC2 instance. First, we’ll provide a name for the instance and choose the instance type as <strong>t2.small</strong> to meet our resource requirements. Once these selections are made, we’ll proceed to launch the instance, as shown in the steps below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXzNmqzjaxLpGjTPk-5aEg.png" /></figure><p>To connect to the instance, you can use either <strong>Gitbash</strong> or <strong>Visual Studio Code</strong>. First, navigate to the directory where your key pair was downloaded using the cd command. Once you&#39;re in the correct directory, you can proceed to launch the Ubuntu instance and establish a secure connection.</p><p>Next, we’ll clone the repository to your local machine. Once the cloning process is complete, navigate into the project directory using the command below.</p><pre>git clone https://github.com/The-DevOps-Dojo/cv-challenge01<br><br>cd cv-challenge01</pre><p>Use the ls command to list the contents of the repository you just cloned. This will help you see all the files and directories inside the project.</p><p>Navigate into the <strong>backend</strong> directory using the cd command. Once you&#39;re inside, create a <strong>Dockerfile</strong> for the backend API and add the following configuration to it. This will help containerize the backend application for easier deployment.</p><pre># Use Python 3.10 image as base<br>FROM python:3.10<br># Set the working directory in the container<br>WORKDIR /app<br># Install curl and bash<br>RUN apt-get update -y &amp;&amp; \<br>    apt-get install -y --no-install-recommends \<br>    curl \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br># Install Poetry<br>RUN curl -sSL https://install.python-poetry.org | python3 -<br># Add Poetry to the PATH<br>ENV PATH=&quot;/root/.local/bin:$PATH&quot;<br># Copy the rest of the application code into the container<br>COPY . /app<br># Install the dependencies using Poetry<br>RUN poetry install<br># Make sure the prestart script is executable<br>RUN chmod +x ./prestart.sh<br># Expose the port the app runs on<br>EXPOSE 8000<br># Run the prestart script and start the server<br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;poetry run bash ./prestart.sh &amp;&amp; poetry run uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload&quot;]</pre><p>Navigate into the <strong>frontend</strong> directory using the cd command. Once you&#39;re there, create a <strong>Dockerfile</strong> for the React frontend and insert the configuration provided below. Be sure to carefully review the contents of the Dockerfile and understand its structure before proceeding to the next steps. This will ensure everything is set up correctly for containerizing the frontend.</p><pre># Use the latest official Node.js image as a base<br>FROM node:latest<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy the application files<br>COPY . .<br><br># Install dependencies<br>RUN npm install<br><br># Expose the port the development server runs on<br>EXPOSE 5173<br><br># Run the development server<br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;dev&quot;, &quot;--&quot;, &quot;--host&quot;]</pre><p>We’ll containerize the <strong>React frontend</strong>, <strong>FastAPI backend</strong>, and <strong>PostgreSQL database</strong> by creating a <strong>docker-compose.yml</strong> file in the root directory. Add the configurations provided below, and take your time to review them carefully.</p><p>If you’re not familiar with Docker or need more clarification, feel free to check out the resource <a href="https://medium.com/@adeyemijoshua/how-to-get-started-with-docker-2eddd740ceac">link</a>.</p><pre>include:<br>  - compose.monitoring.yml<br>services:<br>  frontend:<br>    build:<br>      context: ./frontend<br>    env_file:<br>      - frontend/.env<br>    depends_on:<br>      - backend<br>    ports:<br>      - &quot;5173:5173&quot;<br>    networks:<br>      - frontend-network<br>  backend:<br>    build:<br>      context: ./backend<br>    env_file:<br>      - backend/.env<br>    networks:<br>      - frontend-network<br>      - backend-network<br>    depends_on:<br>      - db<br>    secrets:<br>      - postgres_password<br>    ports:<br>      - &quot;8000:8000&quot;<br>  db:<br>    image: postgres:13<br>    environment:<br>      POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password<br>      POSTGRES_USER: app<br>      POSTGRES_DB: app<br>    secrets:<br>      - postgres_password<br>    networks:<br>      - backend-network<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>  adminer:<br>    image: adminer<br>    ports:<br>      - &quot;8080:8080&quot;  # Exposes Adminer on port 8080<br>    restart: always<br>    environment:<br>      ADMINER_DEFAULT_SERVER: db<br>    networks:<br>      - backend-network<br>  nginx:<br>    image: &#39;jc21/nginx-proxy-manager:2.10.4&#39;<br>    ports:<br>      - &#39;80:80&#39;<br>      - &#39;443:443&#39;<br>      - &#39;8090:81&#39;<br>    environment:<br>      DB_SQLITE_FILE: &quot;/data/database.sqlite&quot;<br>    volumes:<br>      - data:/data<br>      - letsencrypt:/etc/letsencrypt<br>      #- ./nginx/nginx.conf:/data/nginx/custom/http_top.conf<br>    restart: always<br>    depends_on:<br>      - frontend<br>      - backend<br>      - adminer<br>      - prometheus<br>      - grafana<br>    networks:<br>      - frontend-network<br>      - backend-network<br>networks:<br>  frontend-network:<br>  backend-network:<br>volumes:<br>  postgres_data:<br>  data:<br>  letsencrypt:<br>secrets:<br>   postgres_password:<br>     file: ./POSTGRES_PASSWORD.txt</pre><h3>Deploying the Monitoring Stack</h3><p>In this section, we’ll set up the configuration files for <strong>Prometheus</strong>, <strong>Promtail</strong>, and <strong>Loki</strong>. These configurations are essential for ensuring that our monitoring stack runs smoothly.</p><p>Once everything is configured, we’ll add these settings to the <strong>compose.monitoring.yml</strong> file to integrate them into our Docker Compose setup. This will help us effectively monitor our application and services.</p><p>Create a <strong>prometheus.yml</strong> file by including the following configurations. This file will define how Prometheus scrapes and stores metrics, allowing us to monitor the performance of our application and services effectively. Make sure to add the configurations carefully to ensure everything is set up correctly.</p><pre>global:<br>  scrape_interval: 15s<br>scrape_configs:<br>  - job_name: &quot;prometheus&quot;<br>    metrics_path: &quot;/prometheus/metrics&quot;<br>    static_configs:<br>      - targets: [&quot;prometheus:9090&quot;]<br>  - job_name: &quot;cadvisor&quot;<br>    static_configs:<br>      - targets: [&quot;cadvisor:8080&quot;]</pre><p>Next, create a <strong>promtail-config.yml</strong> file and add the configurations provided below. This file will enable Promtail to collect logs from your containers and send them to Loki for centralized logging and analysis. Make sure to configure it correctly to ensure smooth log monitoring.</p><pre>server:<br>  http_listen_port: 9080<br>  grpc_listen_port: 0<br>positions:<br>  filename: /tmp/positions.yaml<br>clients:<br>  - url: http://loki:3100/loki/api/v1/push<br>scrape_configs:<br>- job_name: system<br>  static_configs:<br>  - targets:<br>      - &quot;localhost&quot;<br>    labels:<br>      job: varlogs<br>      __path__: /var/log/*log<br>    labels:<br>      job: docker_logs<br>      __path__: /var/lib/docker/containers/*/*-json.log</pre><p>Now, create the <strong>loki-config.yml</strong> file and add the configurations provided below. This file will define how Loki handles log collection and storage, ensuring that your logs are efficiently managed and accessible for analysis. Be sure to follow the configuration steps carefully.</p><pre>auth_enabled: false<br>server:<br>  http_listen_port: 3100<br>  grpc_listen_port: 9096<br>common:<br>  instance_addr: 127.0.0.1<br>  path_prefix: /tmp/loki<br>  storage:<br>    filesystem:<br>      chunks_directory: /tmp/loki/chunks<br>      rules_directory: /tmp/loki/rules<br>  replication_factor: 1<br>  ring:<br>    kvstore:<br>      store: inmemory<br>query_range:<br>  results_cache:<br>    cache:<br>      embedded_cache:<br>        enabled: true<br>        max_size_mb: 100<br>schema_config:<br>  configs:<br>    - from: 2020-10-24<br>      store: tsdb<br>      object_store: filesystem<br>      schema: v12<br>      index:<br>        prefix: index_<br>        period: 24h</pre><p>Make sure to place all the configuration files into the <strong>monitoring</strong> directory that you’ll create. This will help keep your monitoring setup organized and ensure that all the configuration files are in the right place for easy access and management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*Fwbkf1vstiszrxH9YL4Sdg.png" /></figure><p>Create the <strong>compose.monitoring.yml</strong> file and add the configurations provided below. This file will define the services and networks for your monitoring stack, integrating Prometheus, Grafana, Loki, and Promtail.</p><pre>services:<br>  prometheus:<br>    image: prom/prometheus<br>    ports:<br>      - &quot;9090:9090&quot;<br>    command:<br>      - &#39;--config.file=/etc/prometheus/prometheus.yml&#39;<br>      - &#39;--web.external-url=/prometheus&#39;<br>    volumes:<br>      - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml<br>    networks:<br>      - frontend-network<br>    depends_on:<br>      - cadvisor<br>  grafana:<br>    image: grafana/grafana-oss<br>    expose:<br>      - &quot;3000&quot;<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      - GF_SERVER_ROOT_URL=http://localhost:3000/grafana<br>      - GF_SERVER_SERVE_FROM_SUB_PATH=true<br>    volumes:<br>      - grafana:/var/lib/grafana<br>    networks:<br>      - frontend-network<br>    depends_on:<br>      - loki<br>  cadvisor:<br>    image: gcr.io/cadvisor/cadvisor:v0.47.0<br>    ports:<br>      - &quot;8081:8080&quot;<br>    volumes:<br>      - /:/rootfs:ro<br>      - /var/run:/var/run:rw<br>      - /sys:/sys:ro<br>      - /var/lib/docker/:/var/lib/docker:ro<br>    networks:<br>      - frontend-network<br>      - backend-network<br>    depends_on:<br>      - backend<br>      - frontend<br>      - adminer<br>      - db<br>  loki:<br>    image: grafana/loki:latest<br>    ports:<br>      - 3100:3100<br>    networks:<br>      - frontend-network<br>    volumes:<br>      - ./monitoring/loki-config.yml:/etc/loki/loki-config.yaml<br>  promtail:<br>    image: grafana/promtail:latest<br>    networks:<br>      - frontend-network<br>      - backend-network<br>    volumes:<br>      - ./monitoring/promtail-config.yml:/etc/promtail/promtail-config.yaml<br>    depends_on:<br>      - loki<br>volumes:<br>  grafana:</pre><p>Make sure to input the configurations accurately to ensure everything works seamlessly. This will launch the containers for the monitoring stack. By doing this, you’ll have Prometheus, Grafana, Loki, and Promtail running in your environment.</p><p>Additionally, this challenge requires us to use two Docker Compose files. I highly recommend reviewing the contents of the GitHub repository before starting the project to get a better understanding of how everything fits together.</p><p>Next, we’ll configure Docker to send container logs directly to Loki by installing the Loki log driver. You can do this by running the following command:</p><pre>docker plugin install grafana/loki-docker-driver:2.9.1 --alias loki --grant-all-permissions</pre><p>Now, let’s edit the <strong>/etc/docker/daemon.json</strong> file and add the configuration provided below. This will enable Docker to use the Loki log driver for capturing and sending container logs.</p><pre>{<br>     &quot;log-driver&quot;: &quot;loki&quot;,<br>     &quot;log-opts&quot;: {<br>       &quot;loki-url&quot;: &quot;http://localhost:3100/loki/api/v1/push&quot;,<br>       &quot;loki-batch-size&quot;: &quot;400&quot;<br>     }<br>   }</pre><h3>Configuring Environment Files for the Frontend and Backend</h3><p>Navigate to the <strong>backend</strong> directory and open the <strong>.env</strong> file. Find the <strong>Backend_CORS</strong> setting and update it by adding your IP address and the backend’s port number, as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RKZ03hNWwnd5OqcYy6Mfw.png" /></figure><p>To securely access your PostgreSQL database when the URL loads, run the command echo &quot;changethis123&quot; &gt; POSTGRES_PASSWORD.txt. This will set the password, which you can change after logging in. Additionally, make sure that the database credentials in the <strong>backend .env</strong> file match the PostgreSQL credentials to ensure proper connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ZQERlTqbkL7jenh4Ii0geQ.png" /></figure><p>Navigate to the <strong>frontend .env</strong> file and update the configuration by replacing <strong>“localhost” </strong>with your IP address. This will ensure the frontend connects correctly to the backend.</p><p>Next, deploy the application by running docker compose up -d. Once the deployment is complete, verify that the Docker containers are running by using the command docker ps -a.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JZ7_AS-JAUUquQX7aPM1A.png" /></figure><p>Check to ensure that none of your containers are in an exited state by verifying their status. If any container is exited, troubleshoot the issue by examining its logs with the docker logs command. As shown above, all containers are running smoothly.</p><h3>Verifying Your Containers Are Running on the URL</h3><p>Open your web browser and navigate to your URL to confirm that your containers are running without any issues. Additionally, make sure the port numbers are properly configured in your security groups for seamless access.</p><p>Visit the<strong> Grafana</strong> container’s URL in your browser. It should display the application interface as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJJ9Dfz-qRiQ66w_SXoK_A.png" /></figure><p>Verify that the <strong>Prometheus</strong>, <strong>Database</strong>, <strong>cAdvisor</strong>, <strong>Backend</strong>, <strong>NPM</strong> and <strong>Frontend</strong> containers are running correctly by accessing their URLs with the respective port numbers configured in the <strong>compose.monitoring.yml</strong> and <strong>docker-compose.yml</strong> files. Ensure each service is functioning as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avCjjX2sLl65t4vew8v3tg.png" /></figure><p>This confirms that <strong>Prometheus</strong> is active and running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7CZEqpuEQwmQQBG1m0Osg.png" /></figure><p><strong>PostgreSQL</strong> is up and running, displaying its application interface successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n--7dcDF0xUZoL6pH-5mlw.png" /></figure><p>The <strong>React frontend</strong> is also displaying the application interface correctly after entering the email and password, which are retrieved from the backend’s <strong>.env</strong> file.</p><p><strong>Note: </strong>If the <strong>docker logs</strong> command doesn’t reveal the issue behind the container exiting, start with the command below to view more about the logs and troubleshoot further.</p><pre>docker compose up</pre><h3>Setting Up Nginx Proxy Manager for Reverse Proxy with a Custom Domain</h3><p>To log in to Nginx Proxy Manager, open your browser and go to <strong>&lt;your_public_ip&gt;:8090</strong>. Use the default credentials: <strong>admin@example.com</strong> for the username and <strong>changeme</strong> for the password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99Rq-qb9Xu_gIZ25TdQgaQ.png" /></figure><p>Click on <strong>Proxy Hosts</strong> in the Nginx Proxy Manager dashboard, then select <strong>Add Proxy Host</strong> to begin setting up your reverse proxy.</p><p>Click on the <a href="https://freedns.afraid.org/subdomain/">link</a> to create your subdomains, which you’ll later configure in the <strong>Add Proxy Host</strong> section. This will link your subdomains to the appropriate services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qG8Ca1vFojFAopmUbol0QQ.png" /></figure><p>Configure the subdomains you created in the <strong>Proxy Hosts</strong> section by adding the necessary SSL certificates, port numbers, and locations for services like <strong>Grafana</strong>, <strong>Prometheus</strong>, <strong>Backend</strong>, and <strong>Frontend</strong>. Ensure to set up the forwarding names where needed. Repeat this for any remaining subdomains to complete the setup.</p><p>Once you’ve finished configuring everything, it should show as online, as indicated in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BX3TPoi56ocRAn4BTvQZVw.png" /></figure><p>Before starting the applications, open your <strong>frontend .env</strong> file and set the <strong>VITE_API_URL</strong> to your domain with <strong>HTTPS</strong>, like this: VITE_API_URL=https://joshlite.mooo.com. Next, open the <strong>backend .env</strong> file and set <strong>DOMAIN=&lt;your_domain&gt;</strong> and <strong>ENVIRONMENT=production</strong>. This will ensure your application uses the correct domain and environment settings.</p><p>Stop the containers and then restart them to apply the changes made in the <strong>.env</strong> file. You can do this using the following command:</p><pre>docker compose down <br><br>docker compose up -d</pre><h3>Verifying the Deployment</h3><p>Check that each subdomain for the <strong>frontend</strong>, <strong>backend</strong>, <strong>database</strong>, and monitoring services is up and running as expected. Ensure that all services are securely accessible through their respective subdomains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGpRtFHijPMH-Ubm7mAH_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xNYri2yQ_c81DaBITvpkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaCV366sf7aAV_TqspCywA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YrSKpuqU9er_EEFdxXCKA.png" /></figure><h3>Building a Comprehensive Container Logs Dashboard with Grafana</h3><p>Grafana is an incredible tool for visualizing metrics and logs, offering valuable insights into the health of your applications.</p><p>Start by logging into Grafana and setting up your data sources: <strong>Prometheus</strong> and <strong>Loki</strong>. From the left sidebar, select <strong>Connections</strong> and click on <strong>Data Sources</strong>. Search for <strong>Prometheus</strong> and add it as a data source.</p><p>You’ll end up with a stunning dashboard filled with visualizations that provide clear insights into a wide range of container metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nx82ySmuZMhlYUagw3gq7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6dK1oJl34FF8kPwZSYlwQ.png" /></figure><p>Let’s create a logs dashboard from scratch! Here’s how to get started with Loki query language to make it insightful and dynamic.</p><p>First, create a new dashboard. In the upper-right corner, click <strong>Settings</strong>, set the dashboard name to <strong>“Logs Dashboard”</strong>, and navigate to the <strong>Variables</strong> tab. Here, you’ll define the variables that make the dashboard interactive and tailored to your needs.</p><p>Next, add a new variable. Set the <strong>Name</strong> to <strong>container</strong>, the <strong>Display Name</strong> to <strong>container</strong>, and choose <strong>Query</strong> as the <strong>Variable Type</strong>. For the <strong>Label Value</strong>, use <strong>container_name</strong> to ensure it pulls the correct data dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k77CrX_YWPHW4fjFvHe5_Q.png" /></figure><p>Now, let’s create additional variables and save them to the dashboard.</p><p>Each variable serves a unique purpose and will enhance the flexibility and usability of your dashboard.</p><p>In the code tab, insert the following Loki query to set up the container logs visualization. This query lets you select specific container logs, filter them by severity (info, warn, or error), and search through the filtered results for added flexibility.</p><pre>{job=&quot;containers&quot;} | logfmt level | (level =~ `$severity` or level=&quot;&quot;) |~ `$container_search`</pre><p>Next, let’s create the <strong>Node Logs</strong> visualization for server logs.</p><p>Add another visualization using this Loki query:</p><pre>{job=&quot;varlogs&quot;} |~ `$varlog_search`</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*qOQwXQQTdJXdGB7Sa0HV5w.png" /></figure><p>This query allows you to choose any server logs and filter them based on your chosen keywords.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*tZ3XphEMpMapHVwdzXS9lA.png" /></figure><p>Double-check that all the variables you’ve set up are arranged in the correct order as outlined below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AY7bMiLmqx6F0F9BfOShgQ.png" /></figure><p>Your logs dashboard is now fully functional! Take a moment to test it and confirm that the filters and search options are working seamlessly.</p><h3>Conclusion</h3><p>Deploying a full-stack application in the cloud with Docker Compose, enhanced by robust monitoring and logging tools, is an empowering journey. By integrating technologies like Prometheus, Grafana, and Nginx Proxy Manager, you’ve not only ensured seamless deployment but also established a proactive system for monitoring application health and performance.</p><p>This project represents more than just deploying software — it’s about creating a scalable, efficient, and resilient ecosystem. <strong>Prometheus</strong> delivers unparalleled precision in gathering metrics, while <strong>Grafana</strong> transforms those metrics into beautiful, insightful dashboards. Together, they offer a powerful monitoring duo. Meanwhile, <strong>Nginx Proxy Manager</strong> takes the complexity out of reverse proxy configurations, making domain and SSL management a breeze.</p><p>Take a moment to reflect on how far you’ve come. You’ve tackled cloud deployment, containerized services, set up secure communication, and ensured smooth operations across subdomains. These are skills that will serve you well in any technical challenge you take on next.</p><p>Don’t forget to like, comment, and follow for more insightful articles on DevOps topics.</p><p><strong>Connect with me on:</strong></p><ul><li><a href="https://www.linkedin.com/in/joshua-adeyemi-5676b2213?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=android_app">LinkedIn</a></li><li><a href="https://x.com/iamjoshlite?t=NylKpX_a8lWF0PVnqORumQ&amp;s=09">Twitter</a></li><li><a href="http://hellojoshlite@gmail.com/">Email</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e469648866a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up a Website on Amazon S3]]></title>
            <link>https://medium.com/@adeyemijoshua/how-to-set-up-a-website-on-amazon-s3-d6e049b14e0a?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e049b14e0a</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 16:53:41 GMT</pubDate>
            <atom:updated>2024-11-18T16:53:41.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoK8W4XR4U8-bNRdbDJCTA.png" /></figure><h3>Introduction</h3><p>Let’s dive into why Amazon Simple Storage Service (Amazon S3) should be on your radar if you’re in the DevOps field.</p><p>Imagine you have the power to store and retrieve <strong>any amount of data</strong>, at <strong>any time</strong>, from <strong>anywhere</strong> in the world. That’s what Amazon S3 delivers — a reliable, scalable storage solution that serves as the backbone for internet storage.</p><h3>What Makes Amazon S3 Essential?</h3><ul><li><strong>Object-Based Storage</strong>: Unlike traditional storage, S3 treats your data as complete, discrete objects. It’s all about simplicity and efficiency.</li><li><strong>Data Replication</strong>: Your data is automatically replicated across multiple facilities. This means <strong>built-in protection</strong> without any extra setup.</li><li><strong>Unlimited Storage</strong>: No more stress about running out of space — Amazon S3 offers virtually unlimited storage capacity.</li><li><strong>Buckets and Objects</strong>: Data in S3 is stored as objects within <strong>buckets</strong>. These buckets help you organize your storage. Just keep in mind: each bucket name needs to be <strong>unique</strong> globally!</li></ul><h3>Different Storage Classes for Different Needs</h3><p>Amazon S3 isn’t one-size-fits-all. It offers a variety of storage classes to suit various use cases:</p><ul><li><strong>S3 Standard</strong>: Ideal for frequently accessed data.</li><li><strong>S3 Infrequent Access (IA)</strong>: A lower-cost option for data that isn’t accessed often but still needs to be quickly available.</li><li><strong>S3 One Zone-IA</strong>: Even more cost-effective, but stores data in a single Availability Zone. Great for non-critical data.</li><li><strong>S3 Intelligent-Tiering</strong>: Automatically moves your data to the most cost-effective storage tier based on access patterns. It’s all about optimizing your costs.</li><li><strong>S3 Glacier &amp; S3 Glacier Deep Archive</strong>: Perfect for archiving data you don’t need frequently. These are your go-to options for long-term storage.</li></ul><p>Amazon S3 is versatile and secure, making it an excellent fit for:</p><ul><li><strong>Data Lakes and Big Data Analytics</strong></li><li><strong>Websites and Mobile Applications</strong></li><li><strong>Enterprise Applications</strong></li><li><strong>Archival and Compliance Needs</strong></li></ul><h3>Key Requirements</h3><p>To successfully finish this project, make sure your lab has all the necessary tools in place.</p><ul><li>Make sure your AWS account is set up, as we’ll be working with EC2 instances and S3 buckets.</li></ul><h3><strong>Important Steps</strong></h3><p><strong>Step 1: </strong>A lot of static websites are hosted using S3 buckets. In this project, we’ll generate an HTML template by clicking the <a href="https://www.tooplate.com/view/2089-meteor">link</a> and downloading it.</p><p>Once downloaded, the file will be saved in your Downloads folder. You’ll need to extract it, as it will be in a ZIP format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XktfVzn188sETjUsJYflQ.png" /></figure><p>All the extracted files, as shown in the screenshot above, will be uploaded to the S3 bucket.</p><p><strong>Step 2:</strong> Log in to your AWS account, search for S3, and click on “Create Bucket.” Name your bucket <strong>“meteorwebsite,”</strong> as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sp-LCaFpLMwFxL9DG9Q7Sg.png" /></figure><p>Make sure to enable versioning and create bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1rWwBLarLGAxnwT8PNgUQ.png" /></figure><p>As you can see, the bucket has been created. Click on the bucket, then select “Upload” and drag your files and folders into the upload window and click on upload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85gk1yWmv7-Xz8YXS2uMBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Cemdlxh0lj18C2eEO1bOw.png" /></figure><p>Make sure the files upload successfully without any errors.</p><p><strong>Step 3:</strong> Next, we’ll create another bucket to store the access logs for our website.</p><p>The bucket name will be<strong> “meteora105accesslogs.”</strong> After that, click on <strong>“Create Bucket.”</strong></p><p>To make your objects publicly accessible, go to the meteorwebsite and navigate to the “Permissions” section. From there, find the option to block public access, uncheck it, and then save your changes.</p><p>Next, update the object ownership settings and turn on ACLs (Access Control Lists) and save changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXDxy7J2IyCJNmtuMixfIA.png" /></figure><p>Next, go to all your objects, select them all, and click on<strong> “Action.”</strong> From the options, choose <strong>“Make Public using ACL,”</strong> then confirm by selecting<strong> “Make Public,”</strong> since that’s your goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-tLw7NZBd7-3UwHX65XeA.png" /></figure><p><strong>Step 4: </strong>S3 now offers a simple option to host a static website. To set it up, go to the<strong> “Properties”</strong> section, scroll down to <strong>“Static Website Hosting,”</strong> and enable it by selecting the “Enable” option. For the index document, use <strong>“index.html.”</strong> Even though we don’t have an<strong> “error.html”</strong> file, you can still enter that name and save the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRcazebUvApMBatH1zcSgQ.png" /></figure><p>In S3, you can enable server access logging to store all access logs. To do this, go to the<strong> “Server Access Logging”</strong> section and select the “Enable” option. Then, browse for the bucket you created earlier, select it, and save your changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgAPrbkruC-JNsioZ7ecpw.png" /></figure><p>Head to the <strong>“Static Website Hosting”</strong> section and copy the URL listed in the “Properties” tab. Paste the URL into any browser’s address bar and press Enter. As you’ll see, the website is now live and hosted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NI2fhHByCizK1AJnlu_a4A.png" /></figure><p><strong>Step 5: </strong>Next, go to the bucket and click on the<strong> “Access Logs”</strong> that was created. Click the “Permissions” section, scroll down until you find the <strong>“Bucket Policy.”</strong> You’ll notice an adjacent policy that was automatically created when you selected this bucket as the destination for the access logs. This policy allows the logs to be stored in the S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyvnfFaod6cD7wMcZwqsFA.png" /></figure><p>Next, return to the main bucket where your website is hosted. When we created this bucket earlier, we enabled versioning. Now, click on the <strong>“Show versions” </strong>option, and you’ll be able to see the version IDs for the files stored in the bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgNIDH6EhWpU6pbjzU8dXw.png" /></figure><p>For now, let’s toggle off the “Show Versions” option. Next, take the file <strong>ABOUT THIS TEMPLATE.txt</strong> as an example. Check the box next to it, then select the “Delete” option. Scroll down, and you’ll see an option that says “delete.” Click on the tag that says <strong>“Delete objects”</strong> to confirm.</p><p>When you delete a file from your object storage, it may seem like it’s gone. However, if you enable “Show Versions,” you’ll notice a delete marker has been added on top of it. This marker simply hides the file from view, but the actual data is still there in the previous version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rWRfVNiLug3aU0v2rFAaw.png" /></figure><p>To fully remove the file, you’ll need to delete the delete marker itself. Just select the delete marker, choose the delete option again, and confirm by selecting “permanently delete.” This will erase the file entirely from your storage. After that, simply turn off “Show Versions” to go back to the regular view.</p><p>Once you turn off “Show Versions,” you’ll see the file restored and back in your main view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6yzx03jjr5Z7MiCDkrMeg.png" /></figure><p><strong>Step 6: </strong>Next, let’s try overwriting the index.html file. Open WordPad or Notepad, type “This is my website on S3,” and save it as index.html.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRkSs9273NXl6RycO3ggqA.png" /></figure><p>Now, let’s go ahead and upload the new index.html file. Ensure it is uploaded successfully as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMNIeJ2h07yWxOmg21VjyA.png" /></figure><p>Now, let’s make the updated index.html file public. Click on &quot;Actions,&quot; then select &quot;Make public using ACL&quot; to grant access.</p><p>Next, access the website again by navigating to the properties section, copying the URL, and pasting it into your browser. You’ll be able to see the updated content displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJ_zJiWfQkXQzQ7WSUN6Ow.png" /></figure><p><strong>Step 7:</strong> To restore the previous version of your website, go to the objects list, enable “Show Versions,” and delete the latest version of index.html. Choose the delete option and confirm with &quot;permanently delete.&quot;</p><p>After deleting the latest version, revisit the URL, and you’ll see the previously uploaded website content restored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJBFlfOVm1mKEukmSzwHcA.png" /></figure><p>Once you’ve finished, empty the bucket and then delete it. Don’t forget to also delete any access logs created to prevent unnecessary costs from accumulating.</p><p><strong>Conclusion</strong></p><p>Setting up a website on Amazon S3 is a simple yet powerful way to host static content while benefiting from the scalability and reliability of AWS. With S3, you can easily store your files, make them publicly accessible, and manage them with features like versioning and lifecycle policies.</p><p>By following the steps outlined, you’ve learned how to upload and manage website files, handle permissions, and even implement version control to keep your content updated. Whether you’re hosting a personal project or a business landing page, Amazon S3 offers a cost-effective and flexible solution.</p><p>Remember to clean up any test files and buckets you created to avoid unexpected costs. With your website now live on Amazon S3, you’re ready to share it with the world and explore more advanced configurations as your needs grow.</p><p>Don’t forget to like, comment, and follow for more insightful articles on DevOps topics.</p><p><strong>Connect with me on:</strong></p><ul><li><a href="https://www.linkedin.com/in/joshua-adeyemi-5676b2213?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=android_app">LinkedIn</a></li><li><a href="https://x.com/iamjoshlite?t=NylKpX_a8lWF0PVnqORumQ&amp;s=09">Twitter</a></li><li><a href="http://hellojoshlite@gmail.com/">Email</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e049b14e0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Task 3: Deploying a Python App with Nginx, RabbitMQ, and Celery for Email Sending and Logging]]></title>
            <link>https://python.plainenglish.io/task-3-deploying-a-python-app-with-nginx-rabbitmq-and-celery-for-email-sending-and-logging-991a2a09d6a3?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/991a2a09d6a3</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 16:50:22 GMT</pubDate>
            <atom:updated>2024-10-30T02:46:04.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*gm299zC5wX645De3RQ1w4g.png" /></figure><h3>Introduction</h3><p>In this article, we’ll utilize Ngrok to expose our application’s endpoint externally, allowing us to test its performance and reliability. Additionally, we’ll configure Nginx as a reverse proxy to route traffic directly to the application.</p><p>RabbitMQ functions as a message broker, enabling seamless communication within the application by routing messages between producers. It receives tasks from Celery, queues them, and allows Celery workers to retrieve and execute these tasks as they become available.</p><p>Celery is a distributed task queue system designed to handle background tasks and distribute them across multiple workers. In this setup, Celery takes email-sending tasks from the Flask application, converts them into messages, and passes them to RabbitMQ, where they are queued for processing.</p><p>By integrating these powerful tools, we can create an efficient web application that seamlessly manages background tasks without compromising user experience.</p><h3>Essential Requirements</h3><ul><li>Basic Knowledge of Linux Commands</li><li>You will need to have a Vagrant Ubuntu virtual machine up and running.</li><li>Make sure you have a Gmail account and create an App password using that same account in your Chrome browser.</li></ul><h3>How to Install RabbitMQ</h3><p><strong>Step 1: </strong>Make sure your Vagrant Ubuntu is up and running. Execute the command sudo apt update -y. This command updates the package list on your Ubuntu system, ensuring you have the latest information about available software and updates.</p><p>Now, let’s move on to installing RabbitMQ. To set it up and make sure it runs smoothly in your browser, execute the following commands:</p><pre>sudo apt install rabbitmq-server -y<br><br>sudo systemctl start rabbitmq-server<br><br>sudo systemctl enable rabbitmq-server<br><br>sudo rabbitmq-plugins enable rabbitmq_management<br><br>sudo systemctl status rabbitmq-server</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8NJpsi67s91lBNTOmYy9Q.png" /></figure><p>Next, we can access the RabbitMQ management interface by navigating to http://localhost:15672/. If you&#39;re prompted for credentials, use the default username and password, which are both &quot;guest.&quot;</p><p>As shown below, the RabbitMQ management interface is up and running smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REOJSE80WdDNP_SCyI5UtQ.png" /></figure><h3>Celery Setup and Directory Creation</h3><p><strong>Step 2: </strong>Next, we’ll execute the command displayed below:</p><pre>pip install celery</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWopBjaY3RM7PgWyA0Htjg.png" /></figure><p>This will install the Celery library, which helps manage tasks and run them in the background. If you encounter any issues with this command, make sure that Python is installed on your system first.</p><p>Now, let’s create a directory named <strong>messaging_system</strong>. To do this, execute the following commands:</p><pre>mkdir messaging_system<br><br>cd messaging_system</pre><p>Run the command python3 -m venv venv to create a virtual environment named <strong>venv</strong>. Then, activate the environment by executing:</p><pre>source venv/bin/activate</pre><p>This will allow you to manage dependencies for your project without affecting your global Python installation.</p><p>After that, install Flask, Celery, and Eventlet by running:</p><pre>pip install Flask celery eventlet</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*7K8MRgMU9MumHwd7kuSXuQ.png" /></figure><p>These packages will help you build your web application and manage tasks efficiently. Make sure you’re inside the <strong>messaging_system/</strong> directory before running the commands to activate the virtual environment. This ensures that the environment is set up correctly for your project.</p><h3>Setting Up Nginx to Serve Your Python Application</h3><p><strong>Step 3: </strong>This command will automatically install Nginx on your system without needing further prompts. Run the command:</p><pre> sudo apt install nginx -y</pre><p>Use the following command to create a new Nginx site configuration file for your application:</p><pre>sudo nano /etc/nginx/sites-available/messaging_system</pre><p>Copy the configuration code provided below and paste it into the newly created file.</p><pre>server {<br>    listen 80;<br>    server_name localhost;<br><br>    location / {<br>        proxy_pass http://127.0.0.1:5000;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*PJT0oCLznTXQ6PzsUaXBOA.png" /></figure><p>Activate the configuration by creating a symbolic link in the sites-enabled directory.</p><pre>sudo ln -s /etc/nginx/sites-available/messaging_system /etc/nginx/sites-enabled/</pre><p>Verify the Nginx configuration for any syntax errors, then restart Nginx by running the following commands:</p><pre>sudo nginx -t<br><br>sudo systemctl restart nginx</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISmUtnR9fHGih1Bv72Le0Q.png" /></figure><p>Afterward, execute the command sudo apt update -y.</p><h3>Let’s Build the Python Application</h3><p><strong>Step 4: </strong>Create a Flask application and name the file app.py and insert the content provided below:</p><p>In the smtp.login(&quot;your_email@gmail.com&quot;, &quot;your_app_password&quot;) line, replace &quot;your_email@gmail.com&quot; with your Gmail address and &quot;your_app_password&quot; with the App Password you generated for Gmail.</p><p>Similarly, in smtp.sendmail(&quot;your_email@gmail.com&quot;, to_email, message), use your Gmail address where it says &quot;your_email@gmail.com&quot;. This setup will allow you to log in and send emails from your Gmail account through the script.</p><pre>from flask import Flask, request, Response<br>from celery import Celery<br>from smtplib import SMTP, SMTPException<br>import logging<br>from datetime import datetime<br><br>app = Flask(__name__)<br><br># Celery configuration<br>app.config[&#39;CELERY_BROKER_URL&#39;] = &#39;amqp://guest:guest@localhost:5672//&#39;<br>app.config[&#39;CELERY_RESULT_BACKEND&#39;] = &#39;rpc://&#39;<br>celery = Celery(app.name, broker=app.config[&#39;CELERY_BROKER_URL&#39;])<br>celery.conf.update(app.config)<br><br># Setup logging<br>logging.basicConfig(filename=&#39;/var/log/messaging_system.log&#39;, level=logging.INFO)<br><br>@celery.task<br>def send_email_task(to_email):<br>    try:<br>        with SMTP(&quot;smtp.gmail.com&quot;, 587) as smtp:<br>            smtp.starttls()<br>            smtp.login(&quot;hellojoshlite@gmail.com&quot;, &quot;pzfeesmdbrxkrrib&quot;)<br>            smtp.sendmail(&quot;hellojoshlite@gmail.com&quot;, to_email, &quot;Test email from Flask app with Celery&quot;)<br>            logging.info(f&quot;Email sent to {to_email}&quot;)<br>    except SMTPException as e:<br>        logging.error(f&quot;Failed to send email to {to_email}. Error: {str(e)}&quot;)<br><br>@app.route(&#39;/&#39;)<br>def index():<br>    sendmail = request.args.get(&#39;sendmail&#39;)<br>    talktome = request.args.get(&#39;talktome&#39;)<br><br>    if sendmail:<br>        try:<br>            send_email_task.delay(sendmail)<br>            return f&quot;Email sending task queued for {sendmail}&quot;<br>        except Exception as e:<br>            logging.error(f&quot;Failed to queue email sending task for {sendmail}. Error: {str(e)}&quot;)<br>            return &quot;Failed to queue email sending task.&quot;, 500<br><br>    elif talktome:<br>        logging.info(f&quot;Current time logged: {datetime.now()}&quot;)<br>        return &quot;Current time logged.&quot;<br><br>    return &quot;No action specified.&quot;<br><br>@app.route(&#39;/logs&#39;)<br>def get_logs():<br>    try:<br>        with open(&#39;/var/log/messaging_system.log&#39;, &#39;r&#39;) as f:<br>            logs = f.read()<br>        return Response(logs, mimetype=&#39;text/plain&#39;)<br>    except Exception as e:<br>        return f&quot;Failed to read log file. Error: {str(e)}&quot;, 500<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=5000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*9qP8mOr22cHfkQyftInnPQ.png" /></figure><p>In this setup, we’re creating a simple Python web application with Flask that uses Celery to handle background tasks. Our app has two main features: it can send an email and log the current time upon request.</p><p><strong>Breaking Down the Setup</strong></p><p><strong>1. Initial Setup and Imports</strong><br>The app starts by importing necessary modules: Flask to create the web application, Celery to handle background tasks, datetime for managing timestamps, smtplib to send emails, and logging to save logs.</p><p><strong>2. Configuring Flask and Celery</strong><br>The app first creates a Flask instance (app = Flask(__name__)). Then, it configures Celery by defining CELERY_BROKER_URL and CELERY_RESULT_BACKEND. These settings tell Celery to use RabbitMQ (configured here to use the default credentials) for queuing tasks and to store task results directly in the app&#39;s memory.</p><p>Once the configuration is set, we initialize Celery with:</p><pre>celery = Celery(app.name, broker=app.config[&#39;CELERY_BROKER_URL&#39;])<br>celery.conf.update(app.config)</pre><p>This links the Celery instance with Flask’s configuration, so they work together smoothly.</p><p><strong>3. Creating the Email Task with Celery</strong><br>The send_email function, decorated with @celery.task, is defined to handle email sending as a background task. Here’s how it works:</p><ul><li>The function connects to Gmail’s SMTP server, starts a secure TLS connection, and logs into Gmail using the email and app password.</li><li>It then sends a simple test email with a subject line and body text to the provided recipient’s email.</li></ul><p>Since it’s defined as a Celery task, this function can be queued and processed in the background, letting our app stay responsive even while tasks like email sending are handled separately.</p><p><strong>4. Setting Up the </strong><strong>/message Route</strong><br>The main /message endpoint listens for GET requests. It looks for two optional query parameters: sendmail and talktome.</p><ul><li><strong>If </strong><strong>sendmail is provided</strong>: The function sends an email to the address specified in sendmail, passing the task to Celery with send_email.delay(sendmail). The .delay method tells Celery to handle it in the background so our app can keep running without waiting for the email to send. After the task is queued, the app responds with &quot;Email queued for sending!&quot;</li><li><strong>If </strong><strong>talktome is provided</strong>: The function logs the current time into a file located at /var/log/messaging_system.log. This happens right away since logging is quick, so it doesn’t need to be a background task. Once the time is logged, the app responds with &quot;Logged the current time.&quot;</li><li><strong>If neither parameter is provided</strong>: The app responds with “Invalid parameters!” to let users know they need to include one of the query parameters for it to work.</li></ul><p><strong>5. Starting the Application</strong><br>The last part of the code simply tells Python to run the Flask app if this script is the main program being executed.</p><p>Now, proceed to test the Celery worker. First, activate the virtual environment, then type in the command below.</p><pre>celery -A app.celery worker --loglevel=info</pre><p>After running the command above, you should see the output shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Drw4pWTtdwCBzlMRMO-OA.png" /></figure><h3>Downloading Ngrok to Expose Your Application</h3><p><strong>Step 5: </strong>We’re going to use Ngrok to expose our local application endpoint to the internet. This setup allows us to test the performance, accessibility, and reliability of our application while it runs locally.</p><p>Ngrok provides an external URL that tunnels requests securely to the port where our application is hosted. While we have Ngrok running, using it for an extended time requires an authentication token.</p><p>To obtain the auth token, simply sign up at <a href="https://ngrok.com/">ngrok.com</a>.</p><p>We would install Ngrok on our system using the Snap package manager. After installing, we can check the version of Ngrok, which confirms that Ngrok is installed correctly and allows you to see which version you’re currently using by running the following command:</p><pre>sudo snap install ngrok<br><br>ngrok version</pre><p>This command initiates Ngrok and authenticates it with your unique authentication token, which you receive after signing up on ngrok.com. Your authentication token can be found in your Ngrok account settings, as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCm2lXG8Ftv4MltPykLB9Q.png" /></figure><p>however, I can’t display mine because it’s personal. The command looks like this:</p><pre>ngrok &lt;authtoken&gt;</pre><p>By executing this command, you connect your local Ngrok installation to your Ngrok account. This connection allows you to set up secure tunnels to your local application, facilitating external access and monitoring. Just remember to replace &lt;authtoken&gt; with your actual token to ensure it functions correctly.</p><h3>Configuring Tmux and Sending Email Notifications</h3><p><strong>Step 6: </strong>Next, let’s run sudo apt update -y to update the package list automatically without prompts.</p><p>Now, let’s set up multiple terminal sessions in a single window, which makes it easier to run and monitor various processes at once without opening multiple terminal windows. To do this, simply run the following command:</p><pre>sudo apt install tmux<br><br>tmux</pre><p>Next, press Ctrl + b, followed by Shift + : to open the command prompt within the session. Then, type split-window -v and hit enter.</p><p>Repeat this process until your screen matches the setup shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugNBTWOrej8bNVjTsVwWCA.png" /></figure><p>To navigate between the different terminal windows, press Ctrl + b followed by the <strong>⬆️ up arrow</strong> key to move upwards. To move downwards, simply use the <strong>⬇️ down arrow</strong> key. This setup lets you easily switch between each terminal session.</p><p>Now, let’s proceed to execute the following commands:</p><pre>celery -A app.celery worker --loglevel=info<br><br>python app.py<br><br>ngrok http 5000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*ZUbKbNKOdG6UCHyJg4jT2A.png" /></figure><p>Copy the URL displayed in your Ngrok interface. For example, mine is <a href="https://7bdb-105-112-194-108.ngrok-free.app/">https://7bdb-105-112-194-108.ngrok-free.app/</a>. Next, append the following to your Ngrok URL: /message?sendmail=hellojoshlite@gmail.com. This will create a complete link that looks like this:</p><pre>https://7bdb-105-112-194-108.ngrok-free.app/message?sendmail=hellojoshlite@gmail.com</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*Aj4eAEInj8vsborfZGmkkg.png" /></figure><p>This will send an email message to the specified Gmail account. By using the complete link, you trigger the application to send an email to the address provided in the query string.</p><p>As you can see, a message has successfully been sent to my email account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tgVJguOScKBO0lTWJQNJA.png" /></figure><p>To activate the talktome feature, which records the current time, simply use your ngrok link with the URL below. This will initiate the logging process:</p><pre>https://7bdb-105-112-194-108.ngrok-free.app/?talktome=true</pre><p>Before running the talktome feature, make sure to create the log file and set the correct permissions by executing the following commands:</p><pre>sudo mkdir -p /var/log<br><br>sudo touch /var/log/messaging_system.log<br><br>sudo chown vagrant:vagrant /var/log/messaging_system.log<br><br>sudo chmod u+w /var/log/messaging_system.log</pre><p>Once you use the URL to initiate logging, you should see a result similar to the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgIkYO2VGkpGLtY2JW0MeA.png" /></figure><h3>Conclusion</h3><p>In conclusion, deploying a Python application using Nginx, RabbitMQ, and Celery for email sending and logging creates a highly efficient and responsive web app.</p><p>With this setup, you benefit from an application that effectively handles background tasks. When a user accesses the endpoint /message?sendmail=email@example.com, Celery takes charge of sending the email, allowing Flask to remain free and responsive to other requests. If the user visits /message?talktome, the application promptly logs the current time. This separation of functions ensures that the app maintains its speed, even when performing longer tasks, such as sending emails.</p><p>By combining Flask for handling web requests with Celery for managing background tasks, we achieve a powerful and efficient application. It processes tasks asynchronously while remaining attentive to user interactions, providing a smooth and seamless experience.</p><p>Thank you for exploring this topic on deploying a Python app with Nginx, RabbitMQ, and Celery. I hope you found it insightful and are inspired to implement these techniques in your own projects.</p><p>Don’t forget to like, comment, and follow for more insightful articles on DevOps topics.</p><p><strong>Connect with me on:</strong></p><ul><li><a href="https://www.linkedin.com/in/joshua-adeyemi-5676b2213?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=android_app">LinkedIn</a></li><li><a href="https://x.com/iamjoshlite?t=NylKpX_a8lWF0PVnqORumQ&amp;s=09">Twitter</a></li><li><a href="http://hellojoshlite@gmail.com/">Email</a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=991a2a09d6a3" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/task-3-deploying-a-python-app-with-nginx-rabbitmq-and-celery-for-email-sending-and-logging-991a2a09d6a3">Task 3: Deploying a Python App with Nginx, RabbitMQ, and Celery for Email Sending and Logging</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up an Application with AWS Elastic Load Balancer]]></title>
            <link>https://medium.com/@adeyemijoshua/setting-up-an-application-with-aws-elastic-load-balancer-9cbeea4d1f65?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cbeea4d1f65</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[application]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[elastic-load-balancer]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 15:47:42 GMT</pubDate>
            <atom:updated>2024-10-17T15:47:54.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*L-5fytvqMr0ltPRHOyI24g.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>Elastic Load Balancing automatically distributes incoming traffic across multiple targets, such as EC2 instances, containers, and IP addresses, within one or more Availability Zones. It continuously monitors the health of these registered targets and ensures that traffic is only routed to healthy targets. As traffic fluctuates over time, Elastic Load Balancing adjusts your load balancer’s capacity, allowing it to scale automatically to handle varying workloads.</p><p>There are four types of load balancers supported by Elastic Load Balancing: Application Load Balancers, Network Load Balancers, Gateway Load Balancers, and Classic Load Balancers. Each type is designed to meet different needs, so you can choose the one that best fits your application requirements.</p><p>A load balancer acts as a single point of contact for clients, distributing incoming traffic across multiple targets, such as EC2 instances, spread across various Availability Zones. This not only increases the availability of your application but also improves reliability. You can add one or more listeners to your load balancer to manage this traffic flow.</p><p>Each target group directs traffic to one or more registered targets, like EC2 instances, based on the protocol and port number you specify. You can even register a target with multiple target groups, giving you more flexibility in managing your resources.</p><p>Health checks, which are configurable per target group, are performed on all targets registered to the target group specified in a listener rule. This ensures that traffic is only routed to healthy instances, improving the performance and reliability of your application.</p><h3>Core Prerequisite:</h3><p>To successfully complete this Elastic Load Balancer project, it’s important to ensure your lab is equipped with all the required tools:</p><p>● <strong>Gitbash</strong> or <strong>Visual Studio Code (VSCode)</strong> for development.</p><p>● Ensure you have an <strong>AWS account</strong> set up, as we’ll be working with <strong>EC2 instances</strong>.</p><p>● Familiarize yourself with <strong>essential Linux commands</strong> for smooth execution.</p><blockquote><strong>Let’s get started!</strong></blockquote><h3>Sections</h3><p><strong>First Section: Launching Amazon Linux Virtual Machine</strong></p><p>For this Elastic Load Balancer project, we’ll be using <strong>Amazon Linux</strong>, which is an <strong>RPM-based operating system</strong>. To begin, go to the EC2 Management Console and select <strong>“Launch Instances” </strong>to get started.</p><p>For the Name and Tags section, we’ll set the name as <strong>“site01.” </strong>However, feel free to choose any name that suits your preference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xeA5zwy_NZBXMkdL5AJRjw.png" /></figure><p>We’ll choose Amazon Linux as our AMI and make sure to select the <strong>t2.micro</strong> instance type, which is eligible for the free tier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EI6yw7M2uosAQg2JPurnCw.png" /></figure><p>We’ll create a new key pair for the project, naming it <strong>health-prod-nvir</strong>. After that, simply click “Create key pair.”</p><p>We’ll also set up a new security group named <strong>wavecafe-web</strong>, and for the description, we’ll use the same name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVr912qXvBpa7HkjNZ_xLQ.png" /></figure><p>Next, we’ll add a security group rule. Set the port range to <strong>80</strong>, and allow access only from your IP address. Leave everything else as it is.</p><p>Scroll down to the <strong>Advanced details</strong> section, and we’ll insert a specific script. Copy and paste it exactly as shown.</p><pre>#!/bin/bash<br><br># Variable Declaration<br>#PACKAGE=&quot;httpd wget unzip&quot;<br>#SVC=&quot;httpd&quot;<br>URL=&#39;https://www.tooplate.com/zip-templates/2098_health.zip&#39;<br>ART_NAME=&#39;2098_health&#39;<br>TEMPDIR=&quot;/tmp/webfiles&quot;<br><br>yum --help &amp;&gt; /dev/null<br><br>if [ $? -eq 0 ]<br>then<br>   # Set Variables for CentOS<br>   PACKAGE=&quot;httpd wget unzip&quot;<br>   SVC=&quot;httpd&quot;<br><br>   echo &quot;Running Setup on CentOS&quot;<br>   # Installing Dependencies<br>   echo &quot;########################################&quot;<br>   echo &quot;Installing packages.&quot;<br>   echo &quot;########################################&quot;<br>   sudo yum install $PACKAGE -y &gt; /dev/null<br>   echo<br><br>   # Start &amp; Enable Service<br>   echo &quot;########################################&quot;<br>   echo &quot;Start &amp; Enable HTTPD Service&quot;<br>   echo &quot;########################################&quot;<br>   sudo systemctl start $SVC<br>   sudo systemctl enable $SVC<br>   echo<br><br>   # Creating Temp Directory<br>   echo &quot;########################################&quot;<br>   echo &quot;Starting Artifact Deployment&quot;<br>   echo &quot;########################################&quot;<br>   mkdir -p $TEMPDIR<br>   cd $TEMPDIR<br>   echo<br><br>   wget $URL &gt; /dev/null<br>   unzip $ART_NAME.zip &gt; /dev/null<br>   sudo cp -r $ART_NAME/* /var/www/html/<br>   echo<br><br>   # Bounce Service<br>   echo &quot;########################################&quot;<br>   echo &quot;Restarting HTTPD service&quot;<br>   echo &quot;########################################&quot;<br>   systemctl restart $SVC<br>   echo<br><br>   # Clean Up<br>   echo &quot;########################################&quot;<br>   echo &quot;Removing Temporary Files&quot;<br>   echo &quot;########################################&quot;<br>   rm -rf $TEMPDIR<br>   echo<br><br>   sudo systemctl status $SVC<br>   ls /var/www/html/<br><br>else<br>    # Set Variables for Ubuntu<br>   PACKAGE=&quot;apache2 wget unzip&quot;<br>   SVC=&quot;apache2&quot;<br><br>   echo &quot;Running Setup on CentOS&quot;<br>   # Installing Dependencies<br>   echo &quot;########################################&quot;<br>   echo &quot;Installing packages.&quot;<br>   echo &quot;########################################&quot;<br>   sudo apt update<br>   sudo apt install $PACKAGE -y &gt; /dev/null<br>   echo<br><br>   # Start &amp; Enable Service<br>   echo &quot;########################################&quot;<br>   echo &quot;Start &amp; Enable HTTPD Service&quot;<br>   echo &quot;########################################&quot;<br>   sudo systemctl start $SVC<br>   sudo systemctl enable $SVC<br>   echo<br><br>   # Creating Temp Directory<br>   echo &quot;########################################&quot;<br>   echo &quot;Starting Artifact Deployment&quot;<br>   echo &quot;########################################&quot;<br>   mkdir -p $TEMPDIR<br>   cd $TEMPDIR<br>   echo<br><br>   wget $URL &gt; /dev/null<br>   unzip $ART_NAME.zip &gt; /dev/null<br>   sudo cp -r $ART_NAME/* /var/www/html/<br>   echo<br><br>   # Bounce Service<br>   echo &quot;########################################&quot;<br>   echo &quot;Restarting HTTPD service&quot;<br>   echo &quot;########################################&quot;<br>   systemctl restart $SVC<br>   echo<br><br>   # Clean Up<br>   echo &quot;########################################&quot;<br>   echo &quot;Removing Temporary Files&quot;<br>   echo &quot;########################################&quot;<br>   rm -rf $TEMPDIR<br>   echo<br><br>   sudo systemctl status $SVC<br>   ls /var/www/html/<br>fi </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xT7kg2DCcde3symcVFeMg.png" /></figure><p>After launching the instance, copy the public IP address. Paste it into your browser, and you should see the website, which features a health-related template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6MtN3tLUr7amYhM5gTbGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ro8BBjaSK2RD32-vF-ZfuQ.png" /></figure><p><strong>Second Section: Creating an AMI for the EC2 Instance</strong></p><p>Next, we’ll create an AMI from this instance. Select your instance, go to “Actions,” choose “Image templates,” and then click on “Create image.”</p><p>Name the image “health-ami,” and leave everything else as default. Then, click on “Create image.”</p><p>Head over to the AMI section to check for your image. It may take some time to become available, so make sure to refresh the page. With AMI you can launch an Instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLP8RZzKqs714YZGFcJKDA.png" /></figure><p>Next, go to the<strong> “Launch Templates” </strong>section and click on <strong>“Create Launch Template.”</strong> A launch template contains all the necessary information for launching an instance.</p><p>Launch template name will be health-template. For the version description, enter “V1.” Then, select your AMI, which should be listed under “Owned by me.” Finally, choose the instance type as t2.micro. For the key pair, select “health-prod-nvir,” and for the security group, choose the one you created earlier.</p><p>Add a tag with the value <strong>“site02”</strong>. Once done, create the launch template. It’s that simple!</p><p>Navigate to the template section and locate your template. Select it, then go to “Actions” and choose “Launch instance from template.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-pczAz7PSuykS3foAhQMw.png" /></figure><p>At this point, we’ve accomplished two things: we’ve created an AMI and built a launch template using our custom AMI.</p><p><strong>Third Section: Creating a Target Group in AWS</strong></p><p>Navigate to the target group section. A target group is essentially a collection of instances. We will create a target group and select instances for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FC-KVlxKw6tIY-lmyF4ew.png" /></figure><p>Name the target group as <strong>healthy-tg</strong>. In the advanced health checks section, you’ll configure the target group to monitor the health of the instances. If an instance is unhealthy, the target group will prevent routing any requests to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kphicbhlx8a48CnFjVCJcQ.png" /></figure><p>Set the healthy threshold to 2, meaning it will check twice to confirm if the instance is healthy. Do the same for the unhealthy threshold, ensuring it checks twice before marking the instance as unhealthy. Then, click <strong>Next</strong> to proceed.</p><p>We have two instances, so select both and click <strong>Include as pending</strong> below. You’ll see your instances listed on port 80. Once that’s done, create the target group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJchiFG0ySBtItIIqc-ZWg.png" /></figure><p><strong>Fourth Section: Configuring Our Load Balancer</strong></p><p>Next, go to the load balancer section and click <strong>Create Load Balancer</strong>. We’ll choose an <strong>Application Load Balancer</strong> for handling HTTP and HTTPS traffic. Then, click <strong>Create</strong> to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgyPwuRZ652vT3eHHQ9AKg.png" /></figure><p>Name the load balancer <strong>health-elb</strong>. In the network mapping section, select all the available availability zones.</p><p>For the security group, create a new one specifically for the load balancer. Name it <strong>health-elb-sg</strong> and use the same name for the description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hupN1P5RaCfmRn3sXqkEqg.png" /></figure><p>For the inbound rules, allow access on port 80 from any IPv4 address. Do the same for IPv6. Once that’s done, create the security group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brYXrtbdnrd3c4NVV3K5EQ.png" /></figure><p>Go back to the load balancer tab, refresh the security group section, and add the newly created security group while removing the default one. For the listeners and routing, make sure it’s set to route traffic to the target group “health-tg.” Finally, create the load balancer and view its status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyzdAxJgnN7O45J_N2rmmA.png" /></figure><p>As shown in the image below, our load balancer is now active and running smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsQlT14U81lNegXV_Jk5FA.png" /></figure><p>To access the website, copy the DNS name from the load balancer and paste it into your Chrome browser’s URL bar. However, you might encounter a <strong>504 Gateway Timeout error</strong> instead of the website loading. This error indicates a server-side issue, but when we check the website using the IP address, it is running and displaying properly.</p><p>This means there’s something between the load balancer and the instance that’s blocking the traffic. Want to know what it is? It’s the security group.</p><p>Every instance is protected by a security group. But before we dive into that, let’s first check if the target group is marked as healthy or unhealthy.</p><p>As shown in the image below, the target group is marked as unhealthy. This means the traffic won’t be routed because it can’t access the instance through port 80.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PiCRzQWdTBu6y5G9i8TA0Q.png" /></figure><p>Head over to your security group and edit the inbound rule. Add a new rule allowing port 80 from the load balancer’s security group. You can add a description like “Allow port 80 from ELB.” Once done, save the rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRu-cuPZT5XaTseJbL3izg.png" /></figure><p>We’ll wait for about a minute since the target group performs health checks every 30 seconds to 1 minute. This will allow time to see if the instance becomes healthy. After a minute, as shown below, the instance is now marked as healthy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjOlQYiKIXGL0vyeCH5I2Q.png" /></figure><p>Now, let’s go back, copy the DNS name of the load balancer, paste it into your browser, and you’ll see the website displayed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bo-XVcvcxm5DVZR5LHqbDA.png" /></figure><p>Once you’re finished, it’s important to clean everything up. Start by deleting the load balancer first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmRdlJUnxsB5yGHwiaTHsw.png" /></figure><p>Next, delete the target group and then head over to your instances to terminate them. Make sure to terminate all instances to avoid incurring unnecessary costs on your AWS account.</p><h3>Conclusion</h3><p>In conclusion, setting up an application with AWS Elastic Load Balancer (ELB) is a powerful way to ensure your application’s high availability, fault tolerance, and scalability. ELB distributes traffic across multiple EC2 instances, monitors their health, and routes traffic only to healthy instances, optimizing performance and reliability.</p><p>By effectively using target groups, security groups, and AMIs, you gain full control over your infrastructure while making sure your system scales seamlessly as needed.</p><p>If you encounter any issues along the way, feel free to send me a direct message on any of my social media handles.</p><p>Don’t forget to like, comment, and follow for more valuable insights on DevOps topics. Feel free to share this article with friends or anyone who might be interested in learning more about AWS!</p><p><strong>Connect with me on:</strong></p><ul><li><a href="https://www.linkedin.com/in/joshua-adeyemi-5676b2213?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=android_app">LinkedIn</a></li><li><a href="https://x.com/iamjoshlite?t=NylKpX_a8lWF0PVnqORumQ&amp;s=09">Twitter</a></li><li><a href="http://hellojoshlite@gmail.com/">Email</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cbeea4d1f65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create, Partition, Format, and Mount an EBS Volume via a Web Service: A Step-by-Step Guide]]></title>
            <link>https://awstip.com/how-to-create-partition-format-and-mount-an-ebs-volume-via-a-web-service-a-step-by-step-guide-89266682fe60?source=rss-8cf5586b479d------2</link>
            <guid isPermaLink="false">https://medium.com/p/89266682fe60</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[web-services]]></category>
            <category><![CDATA[ebs-volume]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Joshua Adeyemi]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 16:50:04 GMT</pubDate>
            <atom:updated>2024-10-14T17:24:25.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUJw8qWqZomPb4QzGV7frQ.png" /></figure><h3><strong>Introduction</strong></h3><p>Amazon Elastic Block Store (EBS) is a block-based storage solution that provides scalable and high-performance storage resources for Amazon Elastic Compute Cloud (EC2) instances. EBS enables you to run your EC2 operating system, store database data, and manage file data efficiently.</p><p>When creating an EBS volume, you must specify the availability zone, ensuring that your EC2 instances reside in the same zone as your EBS volume. EBS volumes act like virtual hard drives that you can attach to your EC2 instances, allowing you to store files or install applications just like you would with a local hard drive.</p><p>EBS offers two essential features: EBS volumes and snapshots. An EBS volume serves as a virtual hard disk, while snapshots provide point-in-time backups of your EBS volumes, allowing you to restore new volumes from those backups at any time. These snapshots are independent of the original volume, making them a reliable backup solution.</p><p>Amazon EBS supports multiple volume types, enabling you to optimize storage performance and cost for various applications. The volume types are categorized into two main groups:</p><ol><li><strong>General Purpose (SSD)</strong>: This type is ideal for a wide range of workloads and utilizes solid-state drives (SSDs) for enhanced performance.</li><li><strong>Provisioned IOPS</strong>: Designed for large databases, this type offers consistent and high input/output operations per second (IOPS) to meet demanding performance needs.</li><li><strong>Throughput Optimized HDD</strong>: Suitable for big data applications and data warehouses, this type is optimized for high throughput.</li><li><strong>Cold HDD</strong>: This low-cost option is primarily used for file servers, providing a budget-friendly storage solution.</li><li><strong>Magnetic</strong>: A very economical choice, this type is generally recommended for backups and archival storage.</li></ol><p>With its various volume types and features, Amazon EBS is a versatile solution for managing storage in cloud environments.</p><h3>Prerequisites:</h3><ul><li>Gitbash or Visual Studio Code (Vscode)</li><li>Make sure you have an AWS account set up, as we’ll be launching and configuring an EC2 instance during the process</li><li>Essential Linux Commands</li><li>If you don’t have an AWS account yet, sign up <a href="https://signin.aws.amazon.com/signup?request_type=register">here </a>before proceeding</li></ul><h3>Project Setup and EC2 Instance Launch</h3><p><strong>Step 1: </strong>For this project, we’ll be using a CentOS instance with our website running on it, which we’ll set up as we go through the steps. Next, head over to the EC2 Management Console and click on <strong>“Launch Instances”</strong> to get started.</p><p>For the<strong> Name and Tags</strong>, I used <strong>“app01,”</strong> as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wInoEQtt0TlH5iDIWHtWg.png" /></figure><p>Then, click on <strong>“Browse More AMIs,”</strong> select <strong>“AWS Marketplace AMIs (0),”</strong> and search for CentOS, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYeX6lTNJh162_E65FE3EA.png" /></figure><p>Select <strong>“CentOS Stream 9 (x86_64)” </strong>and then click on <strong>“Subscribe Now” </strong>or any option that appears afterward.</p><p>Make sure to select the T2 micro instance type to help avoid unnecessary costs for the services we’ll be using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdejDd6chnsGHgSA71i87Q.png" /></figure><p>Next, we’ll create a new key pair called<strong> “app-dev-key.”</strong> Be sure to select the option shown in the picture below, then click on “Create New Pair.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_bIQX7VS7auXVXW9L9tNw.png" /></figure><p>Now, let’s go to the network settings and edit them to create a new security group name. Click on<strong> “Edit,”</strong> then scroll down to the security group name section. Remove the existing name and replace it with <strong>“app-sg-name,”</strong> and do the same for the Description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxQMfvjV_FQ09a8wKRHPLw.png" /></figure><p>Leave everything else as it is, then click on <strong>“Launch Instance.”</strong></p><p>You’ll be directed to a new page where your instance shows successfully initiated, as shown in the image below. Simply scroll down and click on “View All Instances.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsU5ievVjUffix7tCgv63Q.png" /></figure><p>You’ll then see that your instance, <strong>“app01,”</strong> was successfully created. Click on it to view its details. Take a moment to review and understand the information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_algEG4dy5e15IFrGGV_HA.png" /></figure><p>After the instance is launched, click on <strong>“Connect,”</strong> make sure it’s set to <strong>“SSH client,”</strong> and copy the command, which should look something like this:</p><pre>ssh -i &quot;app-dev-key.pem&quot; ec2-user@ec2-34-203-222-76.compute-1.amazonaws.com</pre><p><strong>Step 2:</strong> Next, open Git Bash and navigate to the folder where your key pair (downloaded during the CentOS instance setup) is saved.</p><p>As shown in the image below, I successfully logged into my CentOS server. Make sure to navigate to the folder where your key pair was downloaded; otherwise, the SSH connection won’t work. Mine was kept in a folder called Awskey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4yMLy5gE4FcUrMDdB3oDg.png" /></figure><p>Once you’re logged in, switch to the root user by using the command sudo -i.</p><h3>Setting Up Our Web Application</h3><p><strong>Step 3:</strong> We’ll run the command yum update -y.</p><p>Next, run the command</p><pre>yum install httpd wget unzip -y</pre><p>This command will install the Apache web server (httpd), the wget tool for downloading files, and unzip for extracting compressed files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7yU6y35iNKA3UQdPyg7kg.png" /></figure><p>After that, we’ll run systemctl start httpd and systemctl enable httpd. The first command starts the Apache web server, while the second command ensures that it automatically starts up whenever the server is rebooted.</p><p>Next, we’ll check the status of httpd to see if it’s running by using the command:</p><pre>systemctl status httpd</pre><p>As shown in the images below, this command confirms that our Apache web server is running smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xf3pzmIkGp0FWktLBx30cw.png" /></figure><p>Next, change directories to the tmp folder by running cd /tmp.</p><p>Use the command wget https://www.tooplate.com/zip-templates/2119_gymso_fitness.zip to download the zip file. Then, run unzip -o 2119_gymso_fitness.zip to extract its contents. The -o option ensures that any existing files are overwritten during the extraction process, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTsnL0Tt7TyH5j03KiEIcQ.png" /></figure><p>Next, use the command cp -r 2119_gymso_fitness/* /var/www/html/ to copy all the files from the downloaded template to the Apache web server&#39;s root directory. After that, restart the Apache web server with systemctl restart httpd. Finally, confirm that the server is running smoothly by checking its status with systemctl status httpd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vivys6BvjXPewIrivcIAxQ.png" /></figure><p>You can check for your files by running ls /var/www/html. To specifically look for images, use ls /var/www/html/images, as those are the files we’ll be using.</p><p><strong>Step 4:</strong> Return to the instance and navigate to the Storage tab, where you’ll see the Volume ID and Volume Size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3X_YlsvY-K8q5y5JUM3_JQ.png" /></figure><p>Click on the Volume ID, which will take you to the volume section. From there, edit the volume name to <strong>“app01-ROOT-volume.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlegC8GkEU4ue-UEGRIZPw.png" /></figure><p>Always name your volumes for easy identification, especially when you have multiple instances. Take a moment to review the details about it.</p><p>Scroll horizontally to check the Availability Zone and Volume State. Remember that your instance and volume should be in the same zone so that the volume can be attached to the instance.</p><p>Now, we’ll assign 5 GB of storage for the web server images. Keep in mind that using more than 30 GB in EBS will exceed the free tier limit.</p><h3>Creating a Volume</h3><p><strong>Step 5:</strong> Click on<strong> “Create Volume,”</strong> select<strong> “gp2”</strong> for the volume type, set the size to 5 GB, and choose the Availability Zone as us-east-1c, which should match your instance. Make sure to select the appropriate zone for your setup, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1W8sSJ6FK4mDceqD6lkPg.png" /></figure><p>Add a tag by entering<strong> “Name”</strong> as the key and setting the volume name to <strong>“gymso-app01-img.” </strong>Click on create volume.</p><p>Click on<strong> “Actions” </strong>and then select <strong>“Attach Volume.”</strong> You should see all the instances in the same zone. For the device name, choose /dev/sdf, and then click &quot;Attach Volume.&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTdtvzeuFv3XrJ3hTCTa9g.png" /></figure><p><strong>Step 6: </strong>Navigate to cd /var/www/html, where our website files are located. I want to place the images in a separate storage directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KM_omk1B5MCUh4-xy1tmQw.png" /></figure><p>Now, we’ll use Linux commands to partition, format, and mount the storage. The first command, fdisk -l, will list all your disks. In this case, /dev/xvda1 is the partition. Linux uses partition numbers instead of partition names.</p><p>Run the command df -h, and you should see that /dev/xvda1 is mounted to the root directory. This means that everything in your operating system is stored in this partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgwNOJWiYFfJHOHPolrP2A.png" /></figure><p>The next disk is /dev/xvdf, which is the second disk we attached. It has about 5 GB of space and currently has no partitions.</p><h3>Creating a Partition</h3><p><strong>Step 7:</strong> We’ll use the fdisk utility by running the command fdisk /dev/xvdf, which points to the hard disk path. Press Enter, and this will open the fdisk utility. Press m to view the help menu and see all the available options. We’ll start by adding a new partition.</p><p>Press n to create a new partition, then p for a primary partition. Enter 1 for the partition number and press Enter. It will automatically find the free sectors. Just hit Enter again to use the entire disk for the partition.</p><p>Press p to print the partition table, then press w to write the changes. This will create the partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMLA_w010Ty0WVAqSd_UPQ.png" /></figure><p>Run the command fdisk -l, and you&#39;ll see the newly created partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*IJCO6cZ0w5vuKdvdYNPXRg.png" /></figure><h3>Formatting It</h3><p><strong>Step 8:</strong> Linux offers several utilities for formatting. The mkfs command is used for this, and if you press Tab twice, you&#39;ll see a list of available formatting options, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*6DsoC075cnf6wXYYH59tLw.png" /></figure><p>We’ll use the ext4 format and specify the path /dev/xvdf1. Run the command:</p><pre>mkfs.ext4 /dev/xvdf1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*Zb83v2ccXxtFNBooBqFkFA.png" /></figure><p>The partition is now formatted using the ext4 format.</p><h3>Mounting it</h3><p><strong>Step 9:</strong> We’re going to mount the partition to the images folder. First, navigate to cd /var/www/html and then run ls to list the contents.</p><p>We’ll create a directory using mkdir /tmp/img-backups, then move all the data from the images directory to /tmp/img-backups with the command:</p><pre>mv images/* /tmp/img-backups</pre><p>Now it’s time to mount the partition. First, we’ll do a temporary mount using the command:</p><pre>mount /dev/xvdf1 /var/www/html/images/</pre><p>Then, run df -h to confirm it&#39;s mounted. You’ll see the size and other details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgW76Bpxo-qAx2kD54Kb-w.png" /></figure><p>To unmount it, use the command umount /var/www/html/images, and it will be unmounted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*huewZZfcV7iYy0C0CHR1EQ.png" /></figure><p>Run df -h, and you&#39;ll see that it&#39;s no longer listed, as shown above. Keep in mind that this was a temporary mount.</p><p>To set up a permanent mount, we will open the /etc/fstab file using the command:</p><pre>vi /etc/fstab</pre><p>Next, edit the file as shown in the image below.</p><ul><li>The first column will contain the partition path, which in this case is /dev/xvdf1.</li><li>The second column specifies where the partition will be mounted, /var/www/html/images. Ensure the path exists and is correct.</li><li>In the third column, you will provide the format type, which is ext4.</li><li>In the options column, input defaults, followed by 0 0 for the last two columns.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmPJYa4mGTG-iS8qUlbTOw.png" /></figure><p>Once you’ve made these changes, save the file and exit.</p><p>Next, run mount -a to mount all the entries from the fstab file. Then, run df -h to confirm that it has been successfully mounted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-diwUsv2oazbeypDYlg_oA.png" /></figure><p>Next, we’ll move our data from the backup using the command:</p><pre>mv /tmp/img-backups/* /var/www/html/images/</pre><p>Since there is a web service running, I’ll restart it using the command systemctl restart httpd, and then check its status with systemctl status httpd. Ensure that the status shows as <strong>“running.”</strong></p><p>Next, we’ll check if the images were copied successfully by running the command ls /var/www/html/images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-yXkAn7teQBEPFiwL9qHw.png" /></figure><p><strong>Step 10:</strong> Now it’s time to check through your browser. Open Chrome or Firefox, copy the Public IPv4 address of your server, and paste it into the address bar. You should see all the images displayed, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_zn82omDdJRXEwSxdal9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hKvxJ-ppgl03P5pq_RS1Tg.png" /></figure><p>Next, we will go back to our instance to terminate it. Simply click on “Instance State” and select “Terminate.” Make sure to terminate your instance to avoid any unwanted charges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMgcB7a_Z4i5c1HjaPg1fw.png" /></figure><p>After that, navigate to the “Volumes” section and delete the volume that was created earlier, or any other volumes that may still be present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUG0UM2IbpqixjLvJJ19UA.png" /></figure><h3>Conclusion</h3><p>In conclusion, by using a CentOS EC2 instance, we successfully created, partitioned, formatted, and mounted an EBS volume via a web service. Following this step-by-step guide, we were able to integrate additional storage and display our web service images on the server.</p><p>This process not only enhances your cloud management skills but also ensures you can efficiently handle storage and resources in a cloud environment.</p><p>If you encounter any issues, make sure you have a stable network connection and that port 80 (HTTP) is open in your security group. If it’s not, you’ll need to add an inbound rule to allow traffic on port 80. Feel free to leave a comment if you run into any problems!</p><p>Be sure to like, comment, and follow for more insightful articles on DevOps topics. Feel free to share this article with friends or anyone interested in learning about AWS!</p><p><strong>Connect with me on:</strong></p><ul><li><a href="https://www.linkedin.com/in/joshua-adeyemi-5676b2213?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=android_app">LinkedIn</a></li><li><a href="https://x.com/iamjoshlite?t=NylKpX_a8lWF0PVnqORumQ&amp;s=09">Twitter</a></li><li><a href="http://hellojoshlite@gmail.com/">Email</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89266682fe60" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/how-to-create-partition-format-and-mount-an-ebs-volume-via-a-web-service-a-step-by-step-guide-89266682fe60">How to Create, Partition, Format, and Mount an EBS Volume via a Web Service: A Step-by-Step Guide</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>