<?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 Jeremy Smith on Medium]]></title>
        <description><![CDATA[Stories by Jeremy Smith on Medium]]></description>
        <link>https://medium.com/@jsantoine24?source=rss-4b472d64fc0a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EKC82KweTdrvQ-BGxDQiWw@2x.jpeg</url>
            <title>Stories by Jeremy Smith on Medium</title>
            <link>https://medium.com/@jsantoine24?source=rss-4b472d64fc0a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:18:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jsantoine24/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[Container Monitoring with Prometheus & Grafana]]></title>
            <link>https://medium.com/@jsantoine24/container-monitoring-with-prometheus-grafana-375ec4e9effc?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/375ec4e9effc</guid>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 06:37:15 GMT</pubDate>
            <atom:updated>2025-02-04T15:31:10.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3bBiN24O-CUtLhGB.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ki4bD7VDx1A5fKZUmSFQLw.png" /></figure><h3>Introduction</h3><p>As someone diving more into cloud-based monitoring, I wanted to set up a <strong>container monitoring solution</strong> using <strong>Prometheus and Grafana</strong> on AWS. My goal was to create a system where I could <strong>monitor container activity, track performance metrics, and visualize data</strong> through an interactive dashboard.</p><p>In this article I will be walking through my experience setting up <strong>Prometheus and Grafana on an AWS EC2 instance</strong>, testing different artificial metrics to simulate container activity, and troubleshooting common issues along the way. Let’s rock!</p><h4><strong>Pre-reqs</strong></h4><ul><li>AWS Account</li><li>Docker foundational knowledge</li><li>CLI knowledge</li><li>Docker Compose basics</li></ul><h3>Step 1: Setting Up the Cloud Environment</h3><p>To start, I launched an <strong>EC2 instance</strong> in AWS. I opted for a <strong>t3.micro</strong> instance because Prometheus and Grafana require a good chunk of memory and processing power. Here’s how I set up my ec2 instance:</p><ul><li><strong>AMI:</strong> Amazon Linux 2023</li><li><strong>Instance type:</strong> t3.micro (2 vCPUs, 4GB RAM)</li><li><strong>Security Group:</strong> Create a new one</li><li><strong>Security Group Rules:</strong></li><li>Allow <strong>SSH (22)</strong> from my IP</li><li>Allow <strong>Prometheus (9090)</strong>, <strong>Grafana (3000)</strong>, and <strong>Node Exporter (9100)</strong> from anywhere or my IP for better security.</li></ul><p>Once my instance was up and running I had to <strong>SSH</strong> into it. Once connected I installed <strong>Docker and Docker Compose</strong> to manage my containers easily and automatically:</p><pre>sudo yum update -y  # For Amazon Linuz<br>sudo yum install -y docker.io docker-compose<br>sudo systemctl start docker<br>sudo systemctl enable docker</pre><p>Then I moved on to deploying Prometheus and Grafana.</p><h3>Step 2: Deploying Prometheus and Grafana Using Docker Compose</h3><p>I created a directory for my project <strong><em>mkdir monitoring-project</em></strong> and set up <strong>docker-compose.yml</strong> to define my monitoring stack. I also created another directory <strong><em>mkdir prometheus</em></strong> for my Prometheus config file. I ran the following commands respectively:</p><pre>mkdir ~/monitoring-project &amp;&amp; cd ~/monitoring-project<br>nano docker-compose.yml</pre><pre><br># Copy and paste this into the docker-compose.yml file<br>version: &#39;3.8&#39;<br><br>services:<br>  prometheus:<br>    image: prom/prometheus:latest<br>    container_name: prometheus<br>    ports:<br>      - &quot;9090:9090&quot;<br>    volumes:<br>      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml<br>      - prom-data:/etc/prometheus<br>    restart: always<br><br>  node-exporter:<br>    image: prom/node-exporter:latest<br>    container_name: node-exporter<br>    ports:<br>      - &quot;9100:9100&quot;<br>    restart: always<br><br>  grafana:<br>    image: grafana/grafana-oss:latest<br>    container_name: grafana<br>    ports:<br>      - &quot;3000:3000&quot;<br>    restart: always<br><br>volumes:<br>  prom-data:</pre><p>After you paste it hit <strong>ctl^+X</strong> then <strong>Y</strong> then <strong>Enter</strong>. I configured the docker-compose.yml file to include Prometheus, Node Exporter, and Grafana. The <strong>node-exporter agent </strong>is responsible for collecting system-level metrics from my server (like CPU usage, memory, disk space, network stats, etc.) that Prometheus can easily scrape and store.</p><p>I ran the following command to start everything:</p><pre>docker-compose up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDdorbBn2wdi-Ok92I_FOA.png" /><figcaption>All container successfully started (nginx optional)</figcaption></figure><p>With Prometheus and Grafana running, I accessed <strong>Grafana at </strong><strong>http://my-ec2-ip:3000</strong> and configured Prometheus as the data source. I verified <strong>Prometheus</strong> <strong>at </strong><a href="http://my-ec2-ip:3000/"><strong>http://my-ec2-ip:</strong></a><strong>9090 </strong>as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L64qrVwc3tpuFVGTqaRy9w.png" /><figcaption>Sign with default credentials in Grafana user: admin | pass: admin — It will then prompt you to change password after initial login.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nou71g2k8E8p1eSMgqN8PA.png" /><figcaption>From here you can follow the instruction on the Home page if you desire.</figcaption></figure><p>Prometheus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMuMIdp7rJ8JnJl1CPu8-g.png" /><figcaption>Both the Prometheus and node exporter endpoints are up.</figcaption></figure><p>Next I needed to set up the Grafana dashboard.</p><h3>Step 3: Setting up the Grafana dashboard with metrics from Prometheus</h3><p>So there are two ways to do this in Grafana. I could either create my own dashboard from scratch or I could import one. Let’s look at both options. But first we need to choose a data source in Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mHY0vEs9Me3V8Apr3dssw.png" /><figcaption>Choose Prometheus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_M16dPlTXDbtnwxGlgalyQ.png" /><figcaption>Input your URL (http://prometheus:9090) that’s the name of my container and it’s port.</figcaption></figure><p>Then click save &amp; test.</p><p>Go to Dashboards on the left side and click ‘Add Visual’. You can start creating and modifying your own metrics by searching for them under the metrics section to run the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9CYBaLJG59d82BV4UDomQ.png" /></figure><p>Now in order to do this efficiently you would most likely need to learn the PromQL (Prometheus Query Language). Or we could work smarter not harder and import a specked out board from the GrafanaLabs homepage:) You can navigate to <a href="https://grafana.com/grafana/dashboards/">https://grafana.com/grafana/dashboards/</a> to check out some templates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlDa0v7-nqIZ7h68Al6V-w.png" /><figcaption>I chose Node Exporter Full (very good by the way).</figcaption></figure><p>All you need is to copy the import ID and paste it in the Grafana Dashboard import section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sD3LN3gTyymGM8WmFr5zDQ.png" /><figcaption>Copy Import ID for Node Exporter Full.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwNGZFx3Z-gpGbN2Xgb8ag.png" /><figcaption>After pasting the ID click Load.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwyA3B_aAoo3b1ih2YRW6A.png" /><figcaption>Then select Prometheus as the data source and click Import.</figcaption></figure><p>And voila! Our Dashboard is up and running with a ton of metrics to look at too! Well not yet, but check it out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QI-0zeCDW8BohhJFFATq1w.png" /><figcaption>No action just yet.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nutQBrR1rtHBckH3fRBx4Q.png" /><figcaption>A ton of tabs with multiple panels to view in each!</figcaption></figure><p>The only thing left to do now is test it out. To do this I’m going to run a few commands in my terminal to generate some artificial stress in my network.</p><h3>Step 4: Creating artificial metrics for Prometheus</h3><p>You can choose from the following commands to run in your EC2 terminal to generate artificial stress, and adjust them to your liking:</p><h4>1. Simulating High CPU Usage</h4><p>I installed stress to simulate high CPU usage (<strong>I used this one</strong>):</p><pre>sudo apt install -y stress  # Ubuntu<br>stress --cpu 2 --timeout 60  # Simulate CPU load for 60 seconds</pre><p>This increased <strong>CPU usage</strong>, which Prometheus captured, and my Grafana dashboard displayed as a spike in system load.</p><h4>2. Generating High Memory Usage</h4><p>To create a <strong>memory stress test</strong>:</p><pre>stress --vm 1 --vm-bytes 500M --timeout 60</pre><p>This allocated <strong>500MB of RAM</strong>, causing memory usage to increase temporarily.</p><h4>3. Creating Disk I/O Activity</h4><p>To simulate <strong>high disk read/write operations:</strong></p><pre>dd if=/dev/zero of=/tmp/testfile bs=1M count=1000</pre><p>This generated <strong>1GB of disk activity</strong>, which you could monitor using:</p><pre>node_disk_io_time_seconds_total</pre><h4>4. Generating HTTP Traffic on a Sample Web App (Optional)</h4><p>I deployed an <strong>NGINX container</strong> to simulate real traffic (I tested this on also on my nginx container). I used ab (Apache Benchmark) to send <strong>10,000 requests</strong>:</p><pre>ab -n 10000 -c 100 http://localhost:80/</pre><p>This created <strong>a surge in network traffic</strong>, which Prometheus captured and visualized in Grafana. And lastly…</p><h4>5. Custom Prometheus Metrics with Python</h4><p>Here’s a simple <strong>Python script</strong> to expose custom metrics. Create a python file <strong>nano metrics.py</strong> and copy the script into the file:</p><pre>from prometheus_client import start_http_server, Counter<br>import random<br>import time<br><br>REQUEST_COUNT = Counter(&#39;app_requests_total&#39;, &#39;Total number of requests&#39;)<br><br>def generate_requests():<br>    while True:<br>        REQUEST_COUNT.inc(random.randint(1, 5))<br>        time.sleep(2)<br><br>if __name__ == &quot;__main__&quot;:<br>    start_http_server(8000)<br>    generate_requests()</pre><p>Run <strong>python3 metrics.py</strong></p><p><strong>What happens?</strong></p><ul><li>Exposes http://localhost:8000/metrics for Prometheus.</li><li>Prometheus scrapes <strong>app_requests_total</strong>.</li><li>Grafana shows <strong>request spikes</strong>.</li></ul><p>You could run this script on your EC2 instance and add <strong>http://localhost:8000/metrics</strong> to Prometheus’ scrape configs. And lastly…</p><h3>Step 5: Analyzing the Data in Grafana</h3><p>After running these artificial stress tests, I checked my Grafana dashboard. I could see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28bybIp8q3zD457wbGRKTA.png" /><figcaption>Idle at 0% and Normal processes at 99.3% CPU is COOKED</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1sbWw4nw4mJkV5RVNEF9-Q.png" /><figcaption>Big SPIKES going on here!</figcaption></figure><p>You could go through and check out the other panels as well and play around with the artificial stress. Keep in mind how much resources your EC2 instance has. You can use commands like the <strong>df -h</strong> or <strong>top</strong> commands to manually see <em>CPU, Disk I/O, Memory</em>, etc to identify potential bottlenecks. I did go in a little deeper myself with a couple of other commands after the network spikes to train my eyes some. But this was a fairly smooth project and not really much troubleshooting during the setup had to be done. For a project like this the only thing I would say that needs to be done is learning how to read dashboards and recognizing what you’re looking at. In due time though my friend in due time. I’ll see you for the next one! Peace✌🏽☁️</p><h4>Documentation</h4><p><a href="https://hub.docker.com/r/prom/prometheus">https://hub.docker.com/r/prom/prometheus</a></p><p><a href="https://hub.docker.com/r/grafana/grafana">https://hub.docker.com/r/grafana/grafana</a></p><ul><li><a href="https://grafana.com/docs/grafana/latest/datasources/prometheus/configure-prometheus-data-source/">Configure the Prometheus data source | Grafana documentation</a></li><li><a href="https://prometheus.io/docs/prometheus/latest/getting_started/">Getting started | Prometheus</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*qBRuWVJ4U0X_1hAtCgZQXA.png" /></figure><p>Let’s Connect! <a href="https://www.linkedin.com/in/jeremy-smith-o3/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=375ec4e9effc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetching Weather Data using API’s (AWS)]]></title>
            <link>https://medium.com/@jsantoine24/fetching-weather-data-using-apis-aws-f1396944a859?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1396944a859</guid>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[api-integration]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 23:56:30 GMT</pubDate>
            <atom:updated>2025-01-14T00:06:14.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*iISB5C9uHWa5cHffkjObDQ.png" /></figure><p>Building out a Weather Dashboard</p><p>To kick off the 30-day All-Star DevOps challenge, I built a <strong>Weather Dashboard</strong>. This project combines Python and AWS to fetch real-time weather data from the OpenWeather API and store it securely in an Amazon S3 bucket.</p><p>This was a practical way to explore Python’s API integration and AWS automation capabilities while learning to handle environment variables securely and package dependencies for cloud deployment. This project sets the foundation for deeper exploration of cloud-based workflows as I progress through the challenge.</p><h4>Pre-reqs</h4><ul><li><strong>AWS Account</strong></li><li><strong>IDE of your choice (eg. VSCode, PyCharm)</strong></li><li><strong>OpenWeather account (free)</strong></li><li><strong>Basic CLI knowledge</strong></li><li><strong>GitHub Account/Repository</strong></li><li><strong>Pre-configured S3 Bucket</strong></li></ul><h3>Phase 1: Setting up our environment</h3><p>1. Getting started I first had to set up my environment from the terminal in my VSCode for my GitHub Repository. I ran the commands below respectively to get it set up.</p><pre>echo &quot;-env&quot; &gt;&gt; gitignore<br><br>echo &quot;__pycache__/&quot; &gt;&gt; gitignore<br><br>echo &quot;boto3==1.26.137&quot; &gt;&gt; requirements.txt<br><br>echo &quot;python-dotenv=1.0.0&quot; &gt;&gt; requirements.txt<br><br>echo &quot;requests=2.28.2&quot; &gt;&gt; requirements.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*APKlrKDbToVlIS07PVZQ1A.png" /><figcaption>Requirements verification</figcaption></figure><p>2. Next, in order to get weather data from <strong>OpenWeather </strong>we would need to sign up and retrieve our api key. Navigate over to <a href="https://openweathermap.org/">https://openweathermap.org/</a> and create a free account. Afterward click on your username in the top right and click <strong>‘My API Keys’</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKns2oIw9lZ2qtnGEI0QyQ.png" /><figcaption>My OpenWeather api key.</figcaption></figure><p>3. From here we would now need to set our key and our bucket name in our terminal so the location for the weather data will know where to be stored.</p><pre>echo &quot;OPENWEATHER_API_KEY=&lt;your_api_key&gt;&quot; &gt;&gt; .env<br><br>echo &quot;AWS_BUCKET_NAME=&lt;your_s3bucket_name&gt;&quot; &gt;&gt; .env</pre><h3>Phase 2: Setting up our code using Python3</h3><p>Now that our environments are set up I then retrieved a Python template and tweaked it a little bit. We could write this out from scratch which would take a little bit, but in this case I had one and decided to add a couple more locations also.</p><p>Here is the python code I used in my <strong><em>weather_dashboard.py</em></strong> file:</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><br># Load environment variables<br>load_dotenv()<br><br>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;)<br><br>    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>            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;)<br><br>    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<br><br>    def save_to_s3(self, weather_data):<br>        &quot;&quot;&quot;Save weather data to S3 bucket&quot;&quot;&quot;<br>        if not weather_data:<br>            return False<br><br>        file_name = &quot;weather-dashboard/data.json&quot;<br>        <br>        try:<br>            # Load existing data if it exists<br>            existing_data = []<br>            try:<br>                response = self.s3_client.get_object(Bucket=self.bucket_name, Key=file_name)<br>                existing_data = json.loads(response[&#39;Body&#39;].read())<br>            except self.s3_client.exceptions.NoSuchKey:<br>                pass<br><br>            # Append new data<br>            existing_data.append(weather_data)<br><br>            # Save updated data<br>            self.s3_client.put_object(<br>                Bucket=self.bucket_name,<br>                Key=file_name,<br>                Body=json.dumps(existing_data),<br>                ContentType=&#39;application/json&#39;<br>            )<br>            print(&quot;Successfully saved data to S3&quot;)<br>            return True<br>        except Exception as e:<br>            print(f&quot;Error saving to S3: {e}&quot;)<br>            return False<br><br>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;Texas&quot;, &quot;Arizona&quot;, &quot;Montana&quot;]<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>            # 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>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Let’s break down each section of the code to help us gain some understanding. 😉</p><h4>1. Imports</h4><ul><li><strong>os</strong>: Access environment variables to securely manage sensitive data (e.g., API keys).</li><li><strong>json</strong>: Handles JSON data for serialization and deserialization.</li><li><strong>boto3</strong>: AWS SDK for Python, used to interact with AWS services like S3.</li><li><strong>requests</strong>: Makes HTTP requests to the OpenWeather API to fetch weather data.</li><li><strong>datetime</strong>: Handles date and time for timestamping weather data.</li><li><strong>dotenv</strong>: Loads environment variables from a .env file for local development.</li></ul><p>These modules are essential for interacting with APIs, AWS S3, and managing secure configurations.</p><h4>2. Load Environment Variables</h4><ul><li><strong>load_dotenv() : </strong>This loads the environment variables from a .env file into the script. It&#39;s crucial for securely managing API keys and AWS bucket names without hardcoding them into the codebase.</li></ul><h4>3. WeatherDashboard Class Initialization</h4><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><ul><li><strong>api_key</strong>: Retrieves the OpenWeather API key from environment variables.</li><li><strong>bucket_name</strong>: Retrieves the AWS S3 bucket name from environment variables.</li><li><strong>s3_client</strong>: Initializes the S3 client using boto3 to perform bucket and object operations.</li></ul><p>This setup ensures the class is reusable and doesn’t rely on hardcoded configurations which is great when dealing with confidential info.</p><h4>4. Create S3 Bucket if Not Exists</h4><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>        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><ul><li><strong>Purpose</strong>: Ensures the required S3 bucket exists before saving data.</li><li><strong>head_bucket</strong>: Checks if the bucket exists.</li><li><strong>create_bucket</strong>: Creates the bucket if it doesn’t exist.</li></ul><p>This function is essential for preventing errors when trying to upload data to a non-existent bucket.</p><h4>5. Fetch Weather Data</h4><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>    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><ul><li><strong>Purpose</strong>: Retrieves weather data for a given city using the OpenWeather API.</li><li><strong>Error Handling</strong>: Ensures the program doesn’t crash if the API request fails. (super kewl huh?😏)</li></ul><p><strong>Parameters</strong>:</p><ul><li>q: Specifies the city.</li><li>appid: API key for authentication.</li><li>units: Fetches data in imperial units (e.g., Fahrenheit).</li></ul><p>This method is crucial for obtaining the real-time data needed for the dashboard.</p><h4>6. Save Weather Data to S3</h4><pre>def save_to_s3(self, weather_data):<br>    &quot;&quot;&quot;Save weather data to S3 bucket&quot;&quot;&quot;<br>    if not weather_data:<br>        return False<br>    file_name = &quot;weather-dashboard/data.json&quot;<br>    try:<br>        # Load existing data if it exists<br>        existing_data = []<br>        try:<br>            response = self.s3_client.get_object(Bucket=self.bucket_name, Key=file_name)<br>            existing_data = json.loads(response[&#39;Body&#39;].read())<br>        except self.s3_client.exceptions.NoSuchKey:<br>            pass<br>        # Append new data<br>        existing_data.append(weather_data)<br>        # Save updated data<br>        self.s3_client.put_object(<br>            Bucket=self.bucket_name,<br>            Key=file_name,<br>            Body=json.dumps(existing_data),<br>            ContentType=&#39;application/json&#39;<br>        )<br>        print(&quot;Successfully saved data 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><ul><li><strong>Purpose</strong>: Stores weather data in a JSON file on S3.</li></ul><p><strong>Steps</strong>:</p><ol><li>Checks if the file exists and loads its content.</li><li>Appends the new weather data.</li><li>Uploads the updated data back to S3.</li></ol><p>This function ensures the data is persisted and easily accessible.</p><h4>7. Main Function</h4><pre>def main():<br>    dashboard = WeatherDashboard()  # Initializes the WeatherDashboard object to access its methods.<br>    <br>    # Create bucket if needed<br>    dashboard.create_bucket_if_not_exists()  # Ensures the S3 bucket exists to avoid errors during data saving.<br>    <br>    cities = [&quot;Philadelphia&quot;, &quot;Seattle&quot;, &quot;New York&quot;, &quot;Texas&quot;, &quot;Arizona&quot;, &quot;Montana&quot;]  # List of cities to fetch weather data for.<br><br>    for city in cities:  # Loops through each city to fetch and process weather data.<br>        print(f&quot;\nFetching weather for {city}...&quot;)  # Logs the start of data fetching for a city.<br>        weather_data = dashboard.fetch_weather(city)  # Fetches weather data from the OpenWeather API.<br>        <br>        if weather_data:  # Proceeds only if valid data is retrieved.<br>            temp = weather_data[&#39;main&#39;][&#39;temp&#39;]  # Extracts the temperature.<br>            feels_like = weather_data[&#39;main&#39;][&#39;feels_like&#39;]  # Extracts the &#39;feels like&#39; temperature.<br>            humidity = weather_data[&#39;main&#39;][&#39;humidity&#39;]  # Extracts humidity data.<br>            description = weather_data[&#39;weather&#39;][0][&#39;description&#39;]  # Extracts a brief description of the weather.<br>            <br>            print(f&quot;Temperature: {temp}°F&quot;)  # Displays the temperature.<br>            print(f&quot;Feels like: {feels_like}°F&quot;)  # Displays the &#39;feels like&#39; temperature.<br>            print(f&quot;Humidity: {humidity}%&quot;)  # Displays the humidity percentage.<br>            print(f&quot;Conditions: {description}&quot;)  # Displays a brief description of the weather conditions.<br>            <br>            # Save to S3<br>            success = dashboard.save_to_s3(weather_data)  # Saves the data to the S3 bucket.<br>            if success:  # Confirms successful save and logs a message.<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;)  # Logs an error message if data fetching fails.<br><br>if __name__ == &quot;__main__&quot;:<br>    main()  # Runs the main function when the script is executed directly.</pre><p><strong>Initialization and Workflow</strong>:</p><ul><li>The WeatherDashboard object is initialized for accessing weather data and interacting with AWS.</li><li>A loop processes each city, ensuring all cities are covered.</li></ul><p><strong>Error Handling</strong>:</p><ul><li>Verifies that weather data exists before processing.</li><li>Logs errors for failed API calls to aid debugging.</li></ul><p><strong>Flexibility</strong>:</p><ul><li>Cities are stored in a list, which can be modified or made configurable.</li></ul><p><strong>8. Lambda Handler (**Optional)</strong></p><p>Realistically you would only need this Lambda Handler if you planned on serving content via static website hosting to display the weather data on a webpage. You would need a custom <strong>“index.html”</strong> file for this as well. This section of the code would replace the (main function) from above in the template. This would be configured in the Lambda section of AWS where you could run tests also. Checkout the AWS documentation on Lambda <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html">https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html</a> :</p><pre>def lambda_handler(event, context):<br>    dashboard = WeatherDashboard()<br>    dashboard.create_bucket_if_not_exists()<br>    cities = [&quot;Philadelphia&quot;, &quot;Seattle&quot;, &quot;New York&quot;]<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>            simplified_data = {<br>                &quot;city&quot;: city,<br>                &quot;temperature&quot;: weather_data[&#39;main&#39;][&#39;temp&#39;],<br>                &quot;feels_like&quot;: weather_data[&#39;main&#39;][&#39;feels_like&#39;],<br>                &quot;humidity&quot;: weather_data[&#39;main&#39;][&#39;humidity&#39;],<br>                &quot;conditions&quot;: weather_data[&#39;weather&#39;][0][&#39;description&#39;],<br>                &quot;timestamp&quot;: datetime.now().strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>            }<br>            dashboard.save_to_s3(simplified_data)</pre><p><strong>Purpose</strong>: Orchestrates the workflow.</p><p><strong>Flow</strong>:</p><ol><li>Ensures the S3 bucket exists.</li><li>Iterates over a list of cities to fetch weather data.</li><li>Saves the data to S3 in a simplified format.</li></ol><p>This is the main entry point when the code is deployed to AWS Lambda.</p><h3>Results</h3><p>And lastly we will verify all is well by running the code in our IDE, fingers crossed…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hG4l0kgxRCQ-FjfLs38HXQ.png" /><figcaption>Success</figcaption></figure><p>Code ran with 0 issues and we can see our real-time weather data populated in the terminal, chilly🥶. Let’s go verify if the data is being stored in the S3 bucket in the AWS console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-0evWROMOMEdAcBpZTQHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LB9NLxKAbvmqtvesMwlgIg.png" /></figure><p>Cinématique! And there you have it, weather dashboard with real time weather data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*qBRuWVJ4U0X_1hAtCgZQXA.png" /></figure><p>Let’s Connect! <a href="https://www.linkedin.com/in/jeremy-smith-o3/">LinkedIn</a></p><p>My GitHub: <a href="https://github.com/jeremysmith24/My-Personal-DevOps-projects/tree/main/weather-dashboard">https://github.com/jeremysmith24/My-Personal-DevOps-projects/tree/main/weather-dashboard</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1396944a859" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ansible vs. Terraform]]></title>
            <link>https://medium.com/@jsantoine24/ansible-vs-terraform-9c7108d41f30?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c7108d41f30</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-engineering]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 23:25:56 GMT</pubDate>
            <atom:updated>2024-12-30T23:25:56.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_LNmUdl7HSZivuNz.png" /></figure><p>Educational Purposes</p><h3>Terraform vs. Ansible: Key Differences, Features, and Use Cases</h3><p>As the DevOps landscape evolves, automation tools like <strong>Terraform</strong> and <strong>Ansible</strong> have become essential for efficiently managing infrastructure and applications. While they share similarities in purpose — streamlining processes — they are fundamentally different in how they achieve it. Understanding these differences can help you choose the right tool for your specific needs.</p><h3>What is Terraform?</h3><p>Terraform is an <strong>open-source Infrastructure as Code (IaC)</strong> tool developed by HashiCorp. It focuses on provisioning and managing infrastructure resources across various providers using a <strong>declarative approach</strong>. With Terraform, you define the desired state of infrastructure in code, and Terraform ensures that the actual state matches it.</p><h4>Key Features of Terraform</h4><p><strong>1. Declarative Configuration</strong>:</p><ul><li>You define <strong>what you want</strong>, not how to achieve it. For example, specifying a desired number of virtual machines rather than writing detailed steps to create them.</li></ul><p><strong>2. State Management</strong>:</p><ul><li>Terraform uses a <strong>state file</strong> to track the real-world infrastructure. This file is critical for understanding the current setup and applying changes incrementally without affecting unrelated components.</li></ul><p><strong>3. Provider Plugins</strong>:</p><ul><li>Terraform supports a wide range of <strong>providers</strong> (AWS, Azure, GCP, Kubernetes, VMware, etc.), allowing seamless integration with different platforms. This is known as being <strong>cloud agnostic</strong>.</li></ul><p><strong>4. Dependency Graphing</strong>:</p><ul><li>Automatically determines resource dependencies and ensures resources are created in the correct order.</li></ul><p><strong>5. Infrastructure Reusability</strong>:</p><ul><li>Through <strong>modules</strong>, you can create reusable, shareable templates for common setups, saving time and reducing errors.</li></ul><h4>When to Use Terraform</h4><p><strong>— Multi-Cloud Infrastructures</strong>:</p><ul><li>You need a tool that can manage resources across different cloud providers consistently.</li></ul><p><strong>— Environment as Code</strong>:</p><ul><li>Use Terraform to define and version control infrastructure so teams can replicate setups (e.g., dev, staging, production).</li></ul><p><strong>— Complex Resource Management</strong>:</p><ul><li>Terraform excels at creating intricate environments with multiple interdependent components, such as load balancers, VPCs, and autoscaling groups.</li></ul><h3>What is Ansible?</h3><p>Ansible, developed by Red Hat, is an <strong>open-source IT automation tool</strong> primarily designed for <strong>configuration management</strong>, <strong>application deployment</strong>, and <strong>orchestration</strong>. Unlike Terraform, which focuses on infrastructure, Ansible handles the setup and management of software and systems.</p><h4>Key Features of Ansible</h4><p><strong>1. Agentless Architecture</strong>:</p><ul><li>Ansible communicates with managed nodes over <strong>SSH</strong> or <strong>WinRM</strong>. This eliminates the need for agents, simplifying management.</li></ul><p><strong>2. Procedural Syntax</strong>:</p><ul><li>Unlike Terraform’s declarative approach, Ansible tasks are defined step-by-step, specifying <strong>how</strong> to achieve a desired state.</li></ul><p><strong>3. Dynamic Inventory</strong>:</p><ul><li>Supports dynamic discovery of resources using inventory plugins, allowing you to manage environments that change frequently.</li></ul><p><strong>4. Extensive Module Library</strong>:</p><ul><li>Ansible provides modules for managing operating systems, databases, applications, and even cloud resources.</li></ul><p><strong>5. Idempotency</strong>:</p><ul><li>Ensures tasks can be run repeatedly without causing unintended side effects.</li></ul><h4>When to Use Ansible</h4><p><strong>— Configuration and Application Management</strong>:</p><ul><li>Ideal for configuring software, managing files, installing packages, or deploying applications.</li></ul><p><strong>— Ad-Hoc Automation</strong>:</p><ul><li>Quickly execute one-off tasks, such as restarting services or updating configurations.</li></ul><p><strong>— Hybrid Environments</strong>:</p><ul><li>Manage and configure diverse environments, such as Linux, Windows, and network devices.</li></ul><h3>Key Differences Between Terraform and Ansible</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*J5RxH5Shz_zRzdg5pEaT3Q.png" /></figure><h3>Deep Dive: Terraform and Ansible together in Action</h3><h4>Example Use Case: Deploying a Web Application</h4><p>Let’s break down how Terraform and Ansible complement each other in a real-world scenario.</p><p><strong>1. Provisioning Infrastructure with Terraform</strong>:</p><ul><li>Define the desired infrastructure:</li><li>A load balancer for traffic distribution.</li><li>A virtual machine to host the application.</li><li>A managed database for storage.</li><li>Terraform handles dependencies, ensuring the database is ready before the application VM starts.</li></ul><p><strong>2. Configuring Systems with Ansible</strong>:</p><ul><li>Once Terraform provisions the infrastructure:</li><li>Ansible installs and configures the web server (e.g., Apache or Nginx).</li><li>Deploys the application code and sets environment variables.</li><li>Configures monitoring tools and ensures proper logging.</li></ul><p>By using Terraform for provisioning and Ansible for configuration, you create a seamless pipeline from infrastructure to application delivery. The combination between the two works well in <strong>hybrid environments.</strong></p><h3>When to Use Terraform, Ansible, or Both</h3><p><strong>1. Terraform Only</strong>:</p><ul><li>You’re building infrastructure from scratch (e.g., VPCs, EC2 instances, S3 buckets).</li><li>You need <strong>repeatable, version-controlled</strong> infrastructure for dev, staging, and production environments.</li></ul><p><strong>2. Ansible Only</strong>:</p><ul><li>You need to manage configurations, install software, or update applications on existing systems.</li><li>You want a <strong>lightweight, agentless solution</strong> for quick tasks or ongoing maintenance.</li></ul><p><strong>3. Terraform and Ansible Together</strong>:</p><ul><li>Use Terraform to provision infrastructure.</li><li>Use Ansible to configure the software, deploy code, and maintain systems over time.</li><li>Again, this combination works well in <strong>hybrid environments</strong> where infrastructure and software management overlap.</li></ul><h3>Choosing the Right Tool for Your Needs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*FRX3GgTy0gRtNoketQyoTg.png" /></figure><h3>Conclusion</h3><p>Terraform and Ansible serve different but complementary purposes in the DevOps ecosystem. While Terraform shines in creating, managing, and scaling infrastructure, Ansible is the go-to tool for configuring and managing the applications and systems running on that infrastructure.</p><p>For many teams, the optimal solution is a combination of the two. Terraform lays the foundation by provisioning the resources, and Ansible builds upon it by ensuring systems are correctly configured and applications are deployed. Together, these tools can automate your entire pipeline, making your operations more efficient, reliable, and scalable.</p><p><strong>For my visual learners here is a more in depth comparison between Ansible and Terraform from IBM:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Frx4Uh3jv1cA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Drx4Uh3jv1cA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Frx4Uh3jv1cA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0433107b219ff4da0e34b65ec72394c9/href">https://medium.com/media/0433107b219ff4da0e34b65ec72394c9/href</a></iframe><p>Peace!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c7108d41f30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying an AWS Auto-Scaling Group with Terraform (pt.1)]]></title>
            <link>https://medium.com/@jsantoine24/deploying-an-aws-auto-scaling-group-with-terraform-pt-1-059d0f1ba0e7?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/059d0f1ba0e7</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 19:55:39 GMT</pubDate>
            <atom:updated>2024-12-20T19:55:39.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vnmlJ2UqXzcyMJVJ.jpg" /></figure><p>Foundational Use Case</p><h4>Scenario</h4><p>The e-commerce company wants to handle a surge in traffic during the holiday season by using an Auto Scaling group for high availability and fault tolerance. The group spans two subnets in the default VPC and adjusts its size based on traffic, ensuring the website remains responsive. Security is ensured by creating a security group that allows internet traffic, and an Apache web server is launched via a script in the user data. The Auto Scaling group is configured with a minimum of two instances and a maximum of five to handle traffic surges while minimizing costs. To verify functionality, public IPs are checked, and one instance is manually terminated to ensure another spins up. Additionally, an S3 bucket is used as a remote backend for Terraform, allowing for version control and easy rollback of the infrastructure.</p><h4>Objectives</h4><p><strong>— Foundational</strong></p><ul><li>Launch an Auto Scaling group that spans 2 <strong>subnets</strong> in your <strong>default vpc.</strong></li><li>Launch an <strong>Auto Scaling group</strong> that spans <strong>2 subnets</strong> in your <strong>custom vpc</strong>. -Create a security group that allows traffic from the internet and associate it with the Auto -Scaling group instances.</li><li>Include a script in your user data to launch an <strong>apache webserver</strong>. The Auto Scaling group should have a <strong>min of 2</strong> and <strong>max of 5</strong>.</li><li>To verify everything is working check the <strong>public ip addresses</strong> of the two instances. Manually terminate one of the instances to verify that another one spins up to meet the minimum requirement of <strong>2 instances</strong>.</li><li>Create an <strong>S3 bucket</strong> and set it as your <strong>remote backend</strong>.</li></ul><h4>Pre-reqs</h4><ul><li>AWS Account</li><li>Create a <strong>project directory</strong> on your local machine</li><li>Terraform fundamentals</li><li>AWS CLI knowledge</li><li>AWS Configured in your terminal</li></ul><h3>Step 1: <strong>Setting Up the Project Directory</strong></h3><p>I started out by creating the necessary Terraform files in my VSCode terminal:</p><ul><li>main.tf for defining the infrastructure.</li><li>variables.tf for input variables.</li><li>backend.tf to configure the remote backend using an S3 bucket.</li><li>providers.tf to specify the AWS provider.</li><li>outputs.tf to define the outputs. <strong>*Optional</strong></li><li>install_apache.sh for the Apache installation script.</li><li>asg_security_group.tf for the autoscaling group security group.</li></ul><h4>variables.tf</h4><p>I began with the defining the variables that I would use throughout the Terraform configuration. This helps in keeping the configuration flexible and reusable.</p><p>Here’s how I defined the <strong>variables</strong>:</p><pre># AWS region to deploy resources<br>variable &quot;region&quot; {<br>  description = &quot;The AWS region to deploy resources&quot;  # Specifies the AWS region where resources will be deployed<br>  type        = string<br>  default     = &quot;us-east-1&quot;<br>}<br><br># The ID of the default VPC for resource deployment<br>variable &quot;default_vpc&quot; {<br>  description = &quot;The ID of the default VPC&quot;  # Provides the VPC ID to use for deploying resources (replace with your VPC ID)<br>  default     = &quot;vpc-09455d2909705cda2&quot;<br>  type        = string<br>}<br><br># List of availability zones to use for resources<br>variable &quot;availability_zones&quot; {<br>  description = &quot;List of availability zones&quot;  # Specifies the availability zones in the chosen region for spreading resources<br>  type        = list(string)<br>  default     = [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;]<br>}<br><br># EC2 key pair name for SSH access to instances<br>variable &quot;key&quot; {<br>  description = &quot;The EC2 key pair name for SSH access&quot;  # Specifies the EC2 key pair name used to connect to instances via SSH<br>  type        = string<br>  default     = &quot;MyEC2TerraformKey&quot;<br>}<br><br># EC2 instance configuration<br>variable &quot;ami_id&quot; {<br>  description = &quot;AMI ID for EC2 instances&quot;  # Specifies the Amazon Machine Image (AMI) ID to use for EC2 instances<br>  type        = string<br>  default     = &quot;ami-0166fe664262f664c&quot;  # Example: Amazon Linux 2 AMI ID (ensure to use a valid AMI ID for your region)<br>}<br><br># EC2 instance type for Auto Scaling Group instances<br>variable &quot;instance_type&quot; {<br>  description = &quot;Instance type for EC2 instances&quot;  # Specifies the EC2 instance type (e.g., t2.micro, t2.small)<br>  type        = string<br>  default     = &quot;t2.micro&quot;  # A common instance type for low-cost testing<br>}<br><br># Desired number of instances in the Auto Scaling Group<br>variable &quot;desired_capacity&quot; {<br>  description = &quot;Desired number of instances in the Auto Scaling Group&quot;  # The initial number of instances to be launched in the ASG<br>  type        = number<br>  default     = 2<br>}<br><br># Minimum number of instances in the Auto Scaling Group<br>variable &quot;min_size&quot; {<br>  description = &quot;Minimum number of instances in the Auto Scaling Group&quot;  # The minimum number of instances the ASG should maintain<br>  type        = number<br>  default     = 2<br>}<br><br># Maximum number of instances in the Auto Scaling Group<br>variable &quot;max_size&quot; {<br>  description = &quot;Maximum number of instances in the Auto Scaling Group&quot;  # The maximum number of instances the ASG should scale up to<br>  type        = number<br>  default     = 5<br>}</pre><h4>Explanation of Key Variables:</h4><ul><li><strong>region</strong>: Defines where the resources will be deployed.</li><li><strong>default_vpc</strong>: The ID of the VPC where the Auto Scaling Group will be deployed.</li><li><strong>availability_zones</strong>: List of availability zones for distributing the EC2 instances.</li><li><strong>ami_id</strong>: The AMI used to launch the EC2 instances (Amazon Linux 2 in this case).</li><li><strong>instance_type</strong>: The type of EC2 instances in the Auto Scaling Group.</li><li><strong>desired_capacity, </strong><strong>min_size, </strong><strong>max_size</strong>: The size parameters for the Auto Scaling Group.</li></ul><p><em>Next…</em></p><h4>backend.tf</h4><p>To manage the state remotely, I set up an <strong>S3 bucket</strong> as the backend to store the Terraform state file. This allows me to manage state securely and work in a team environment. Note that you must create this bucket first in the AWS console in order for it to be referenced in Terraform or it will throw an error.</p><pre># backend.tf<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;my-terraform-state-bucket&quot;  # Replace with your S3 bucket name<br>    key            = &quot;terraform.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>    encrypt        = true<br>    dynamodb_table = &quot;my-lock-table&quot;  # Optional: for state locking<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wldgvbpHhqh-LL3HnDrfpw.png" /><figcaption>My S3 bucket</figcaption></figure><ul><li>The bucket specifies the S3 bucket where the state will be stored.</li><li>The dynamodb_table is used for state locking, ensuring no two people modify the state simultaneously.</li></ul><p><em>Next…</em></p><h4>providers.tf</h4><p>Next, I defined the <strong>AWS provider</strong> in providers.tf, which specifies the region where resources will be deployed.</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.78.0&quot;<br>    }<br>  }<br>}<br><br># AWS Provider<br>provider &quot;aws&quot; {<br>  region = var.region<br>}</pre><ul><li>This file ensures that Terraform will interact with AWS in the region defined by the region variable.</li></ul><p><em>Next…</em></p><h4>install_apache.sh</h4><p>This bash script will be for the user data of the EC2 instances to bootstrap apache webserver to them. Note that I’m using a Linux EC2 and so a Ubuntu EC2 will cause the commands needed to vary (eg. <strong>Linux</strong> = “sudo yum”, <strong>Ubuntu</strong> = “sudo apt”).</p><pre>#!/bin/bash<br><br># Wait until any other yum process finishes<br>while fuser /var/lib/rpm/.rpm.lock; do<br>  echo &quot;Waiting for other yum process to complete...&quot;<br>  sleep 5<br>done<br><br># Update yum and install apache<br>sudo yum clean all<br>sudo yum update -y<br>sudo yum install -y httpd<br><br># Enable and start apache<br>sudo systemctl enable httpd<br>sudo systemctl start httpd<br><br># Check if Apache is running<br>if ! systemctl status httpd | grep &quot;running&quot;; then<br>  echo &quot;Apache installation failed&quot;<br>  exit 1<br>fi<br><br># Ensure the web directory exists and create index.html<br>sudo mkdir -p /var/www/html<br>echo &quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello from $(hostname -f)&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot; &gt; /var/www/html/index.html<br><br># Restart Apache to load the index.html page<br>sudo systemctl restart httpd<br><br>echo &quot;Apache Web Server setup complete&quot;</pre><h3>Step 2: <strong>Creating the Security Group for the ASG</strong></h3><p>To allow internet traffic to the EC2 instances, I created a separate file asg_security_group.tf for the <strong>Security Group</strong>. The security group allows HTTP (port 80) and SSH (port 22) traffic.</p><pre># asg_security_group.tf<br>resource &quot;aws_security_group&quot; &quot;asg_sg&quot; {<br>  name        = &quot;asg-security-group&quot;<br>  description = &quot;Allow traffic for the Auto Scaling Group instances&quot;<br>  <br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]  # Allow HTTP traffic from anywhere<br>  }<br>  <br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]  # Allow SSH traffic from anywhere<br>  }<br>  <br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;  # Allow all outgoing traffic for anny protocol<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><ul><li>This security group allows <strong>HTTP</strong> and <strong>SSH</strong> traffic from any source (0.0.0.0/0), enabling access to the Apache web server and for managing the EC2 instances via SSH.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0akURv8Q4Oaox98_Z5Bpg.png" /><figcaption>SG inbound rules</figcaption></figure><h3>Step 3: Defining the Default VPC main.tf</h3><p>I then went over to the main.tf file I created earlier in the project and began the template by establishing the default <strong>VPC</strong> of my AWS account. Now this isn’t always necessary since Terraform is smart enough to know if you don’t specify the <strong>VPC</strong> it will assume the default one. However I will explain in a moment why it was necessary in this case. Since we are using the default VPC that means that I’m going to need to retrieve data. So I had to use some data blocks in my build to make this possible. I am positive this could have been done numerous ways but during my later trouble shooting I found that this setup is what worked for me. Let’s take it step by step:</p><pre>resource &quot;aws_default_vpc&quot; &quot;default-vpc&quot; {<br>  tags = {<br>    Name = &quot;Default VPC&quot;<br>  }<br>}<br><br>data &quot;aws_vpc&quot; &quot;default-vpc&quot; {<br>  id = var.default_vpc<br>}<br><br>data &quot;aws_subnets&quot; &quot;public_subnets&quot; {<br>  filter {<br>    name   = &quot;vpc-id&quot;<br>    values = [var.default_vpc]<br>  }<br>}<br><br># Retrieve all Subnet IDs in the Default VPC<br>data &quot;aws_subnets&quot; &quot;default_vpc_subnets&quot; {<br>  filter {<br>    name   = &quot;vpc-id&quot;<br>    values = [aws_default_vpc.default-vpc.id]<br>  }<br>}</pre><ol><li><strong>aws_default_vpc resource</strong></li></ol><ul><li>This block creates an <strong>AWS Default VPC</strong> in the region where you are deploying resources. By default, AWS creates a VPC when you set up an account, but if you delete it, you can recreate it using this resource.</li><li>The tags section assigns a name to the VPC for easier identification.</li></ul><p>2. <strong>aws_vpc data source</strong></p><ul><li>This <strong>data source</strong> retrieves information about an existing <strong>VPC</strong> using its ID.</li><li>The id field references a variable var.default_vpc which is assumed to be the VPC ID. It allows Terraform to look up details of the specified VPC, which will be used in other resources, such as subnets and auto scaling groups.</li></ul><p>3. aws_subnets <strong>data source for Public Subnets</strong></p><ul><li>This <strong>data source</strong> fetches information about the <strong>subnets</strong> in a specific <strong>VPC</strong> (referenced by var.default_vpc).</li><li>The filter is applied using the vpc-id, so it returns the subnets associated with the specified VPC.</li></ul><p>4. aws_subnets <strong>data source for Default VPC Subnets</strong></p><ul><li>This <strong>data source</strong> retrieves the <strong>subnets</strong> for the <strong>default VPC</strong> created earlier (using the aws_default_vpc.default-vpc.id).</li><li>It allows you to use the subnets within the default VPC for other resources, such as Auto Scaling Groups or EC2 instances.</li></ul><h3>Step 4: Resources (Creating Subnets) main.tf</h3><p>These resources create <strong>subnets</strong> in specific <strong>Availability Zones</strong> within the VPC. Two subnets are created here, one in <strong>us-east-1a</strong> and one in <strong>us-east-1b</strong>.</p><pre># Subnet for us-east-1a<br>resource &quot;aws_default_subnet&quot; &quot;default_az1&quot; {<br>  availability_zone = &quot;us-east-1a&quot;<br><br>  tags = {<br>    Name = &quot;Default subnet for us-east-1a&quot;<br>  }<br>}<br><br># Subnet for us-east-1b<br>resource &quot;aws_default_subnet&quot; &quot;default_az2&quot; {<br>  availability_zone = &quot;us-east-1b&quot;<br><br>  tags = {<br>    Name = &quot;Default subnet for us-east-1b&quot;<br>  }<br>}<br><br># Optional - fetches all the availability zones in the region that are availabl<br>data &quot;aws_availability_zones&quot; &quot;available&quot; {<br>  state = &quot;available&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxNN8i3r_g-TJwqrBf-8Nw.png" /><figcaption>public subnets for default vpc</figcaption></figure><ul><li>The availability_zone specifies where the subnet will reside.</li><li>tags are used for easier identification of the subnets.</li><li>These subnets will be used by other resources like EC2 instances or Auto Scaling Groups.</li><li>This data source is useful for dynamically determining which availability zones are available to deploy resources, ensuring that your infrastructure is resilient by spreading it across multiple zones.</li></ul><h3>Step 5: Creating the Auto Scaling Group and Lanch Template main.tf</h3><h4>ASG</h4><ol><li>This block defines an <strong>Auto Scaling Group (ASG)</strong> that automatically scales the number of EC2 instances based on the desired capacity and scaling policies. It uses a <strong>launch template</strong> to configure the EC2 instances in the ASG:</li></ol><pre>resource &quot;aws_autoscaling_group&quot; &quot;terraform_asg&quot; {<br>  name               = &quot;my-terraform-asg&quot;  # This is the name of the ASG that will be created in AWS<br>  min_size           = var.min_size  # Reference the variable &#39;min_size&#39; to define the lower bound of the ASG size<br>  max_size           = var.max_size  # Reference the variable &#39;max_size&#39; to define the upper bound of the ASG size<br>  desired_capacity   = var.desired_capacity  # Reference the variable &#39;desired_capacity&#39; to set the number of instances at the start<br>  availability_zones = var.availability_zones  # Reference the variable &#39;availability_zones&#39; to define where to deploy instances in different zones<br><br>  # Define the launch template used by the ASG for creating instances<br>  launch_template {<br>    id      = aws_launch_template.launch-asg.id  # Reference the ID of the launch template defined elsewhere in your configuration<br>    version = &quot;$Latest&quot;  # Use the latest version of the launch template when launching instances<br>  }<br><br>  # Tag the ASG to help identify it in the AWS Management Console<br>  tag {<br>    key                 = &quot;Name&quot;  <br>    value               = &quot;terraform-asg&quot;  # Tag value to be applied to instances launched by the ASG<br>    propagate_at_launch = true  # Ensure that this tag is propagated to instances when they are launched<br>  }<br>}</pre><p>This configuration will help automate the scaling of EC2 instances in your Auto Scaling Group based on the defined parameters and ensures the instances are correctly identified with tags for easier management.</p><h4>ASG Laung Template</h4><p>2. This resource defines the <strong>launch template</strong> that will be used by the <strong>Auto Scaling Group</strong> to launch EC2 instances.It includes configuration for the EC2 instance, such as the AMI, instance type, and SSH key.</p><pre>resource &quot;aws_launch_template&quot; &quot;launch-asg&quot; {<br>  name          = &quot;my-launch-asg&quot;<br>  image_id      = var.ami_id<br>  instance_type = var.instance_type<br>  key_name      = var.key<br>  user_data     = base64encode(file(&quot;install_apache.sh&quot;)) # Explicit encoding of user data<br><br>  network_interfaces {<br>    associate_public_ip_address = true<br>    security_groups             = [aws_security_group.asg_sg.id]<br>  }<br><br>  tag_specifications {<br>    resource_type = &quot;instance&quot;<br>    tags = {<br>      Name = &quot;MyLaunchASGInstance&quot;<br>    }<br>  }<br>}</pre><h4>*Optional</h4><p>This <strong>data source</strong> fetches all instances with a specific tag (Name: my-terraform-asg) that are currently in the <strong>running</strong> state.</p><pre>data &quot;aws_instances&quot; &quot;asg_instances&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [&quot;my-terraform-asg&quot;] # Matches the ASG instance tag<br>  }<br><br>  instance_state_names = [&quot;running&quot;]<br>}</pre><ul><li>The <strong>filter</strong> matches instances by the tag Name and filters them by the value my-terraform-asg which is helpfule when dealing with a ton of instances in the console beforehand.</li><li>instance_state_names ensures that only instances that are currently running are selected.</li></ul><h3>Step 6: Deploying the infrastructure to AWS</h3><p>Now that we have all of our files and configurations complete let’s deploy the infrastructure. But first I made sure that my code was was formatted properly and valid with these commands:</p><pre># This formats your code and makes it neat<br>terraform fmt <br><br># This checks your code and makes sure everything is valid and nothing is missing or off<br>terraform validate </pre><p>If the code is not valid then you will get an error message of where the issue is.</p><p>After formatting and validating it was time to deploy. I ran the following I ran the following command respectively:</p><pre><br>terraform plan<br><br># Preview the changes Terraform will make to your infrastructure<br># Example of what you should see below:<br><br><br># aws_instance.example will be created<br>+ resource &quot;aws_instance&quot; &quot;example&quot; {<br>    + ami           = &quot;ami-0c55b159cbfafe1f0&quot;<br>    + instance_type = &quot;t2.micro&quot;<br>    + subnet_id     = &quot;subnet-1234abcd&quot;<br>    + vpc_security_group_ids = [<br>        + &quot;sg-12345678&quot;,<br>      ]<br>  }<br><br># aws_security_group.example will be created<br>+ resource &quot;aws_security_group&quot; &quot;example&quot; {<br>    + name        = &quot;example-sg&quot;<br>    + description = &quot;Security group for example instance&quot;<br>    + ingress {<br>        + from_port   = 80<br>        + to_port     = 80<br>        + protocol    = &quot;tcp&quot;<br>        + cidr_blocks = [<br>            + &quot;0.0.0.0/0&quot;,<br>        ]<br>    }<br>}<br><br>Plan: 4 to add, 0 to change, 0 to destroy.<br><br>------------------------------------------------------------------------</pre><p>Then apply it:</p><pre><br>terraform apply<br><br># Example of what you should see below<br><br>Plan: 4 to add, 0 to change, 0 to destroy.<br><br>Do you want to perform these actions?<br>Terraform will perform the actions described above.<br>Only &#39;yes&#39; will be accepted to approve.<br>Enter a value: yes<br><br># Input yes<br><br>aws_instance.example: Creating...<br>aws_security_group.example: Creating...<br>...<br>Apply complete! Resources: 4 added, 0 changed, 0 destroyed.</pre><h4>Verify the apache webserver</h4><p>After the infrastructure was deployed I connected to one of the EC2 instances via SSH to verify that the index.html file was created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*sfbwzi0gKoSSiT_dLByLlw.png" /><figcaption>index.html was successfully created</figcaption></figure><p>Next I wanted to verify that the apache webserver was running properly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CP8y3ugBAqZAssT0zPcgcQ.png" /><figcaption>apache webser running properly</figcaption></figure><p>And lastly, I had to make sure the webserver was accessible through the internet. I copied my EC2 instance public ip → <strong>http://&lt;ec2-public-ip-addr&gt;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v9qnFItqZcVCelTiLb-M9Q.png" /><figcaption>Success!</figcaption></figure><h4>Documentation</h4><ul><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#user_data_base64-1">Terraform Registry</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/launch_configuration">Terraform Registry</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/default_subnet">Terraform Registry</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/default_subnet">Terraform Registry</a></li></ul><h4>Troubleshooting</h4><p>You had to know this was coming! Here some things to be mindful of when creating your terraform template:</p><ol><li>Make sure that you’re working with the correct versions (resources, providers, etc).</li><li>If you get an error in your code IDE saying something is <strong>depracated</strong> that means that there is a more up-to-date way to do it.</li><li>When it comes to adding <strong>user_data</strong> in your you must base64encode the file in order for the user data to be executed and added to the instances on their creation. See example below:</li></ol><pre># This wont work <br>user_data     = file(&quot;install_apache.sh&quot;)<br><br># Here is the correct way to do it<br>user_data     = base64encode(file(&quot;install_apache.sh&quot;))<br></pre><ul><li>Also make sure the permission on the “install_apache.sh” file is executable → <strong>chmod +x install_apache.sh</strong> if you’re still having issues<strong>.</strong></li><li>Comparing the <strong>aws_launch_template</strong> and <strong>aws_launch_configuration</strong> really helped me figure it out.</li></ul><p>4. Triple check your <strong>variables.tf</strong> file.</p><p>5. Dont forget to specify you <strong>availability zones </strong>since this project required 2 subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*qBRuWVJ4U0X_1hAtCgZQXA.png" /></figure><p>Let’s Connect! <a href="https://github.com/jeremysmith24/My-Terraform-Projects/tree/main/Terraform_project_2/Foundation">LinkedIn</a></p><p><strong>My GitHub repository</strong>: <a href="https://github.com/jeremysmith24/My-Terraform-Projects/tree/main/Terraform_project_2/Foundation">https://github.com/jeremysmith24/My-Terraform-Projects/tree/main/Terraform_project_2/Foundation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=059d0f1ba0e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying A Jenkins Server With Terraform]]></title>
            <link>https://medium.com/@jsantoine24/deploying-a-jenkins-server-with-terraform-d16dc95ff309?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d16dc95ff309</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-cli]]></category>
            <category><![CDATA[cicd-pipeline]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 00:39:02 GMT</pubDate>
            <atom:updated>2024-12-04T03:19:17.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z_F-1CT-vc5WPoJY.jpeg" /></figure><p>Use Case</p><p>Your team would like to start using Jenkins as their CI/CD tool to create pipelines for DevOps projects. They need you to create the Jenkins server using Terraform so that it can be used in other environments and so that changes to the environment are better tracked. For the Foundational project you are allowed to have all your code in a single <a href="http://main.tf/">main.tf</a> file (known as a monolith) with hardcoded data. Push all your code to GitHub and include the link to your repo in your documentation.</p><h4>Objectives</h4><ol><li>Add a <a href="http://variables.tf/">variables.tf</a> file and make sure nothing is hardcoded in your<a href="http://main.tf/"> main.tf</a>.</li><li>Create separate file for your <a href="http://providers.tf/">providers.tf</a> if you have not already.</li><li>Deploy 1 EC2 Instances in your Default VPC.</li><li>Bootstrap the EC2 instance with a script that will install and start Jenkins.</li><li>Create and assign a Security Group to the Jenkins Security Group that allows traffic on port 22 from your ip and allows traffic from port 8080.</li><li>Create a S3 bucket for your Jenkins Artifacts that is not open to the public.</li><li>Verify that you can reach your Jenkins install via port 8080 in your browser. Be sure to include a screenshot of the Jenkins login screen in your documentation.</li></ol><h4>Pre-reqs</h4><ul><li><strong>AWS Account</strong></li><li><strong>Terraform Setup for Infrastructure Automation</strong></li><li><strong>VSCode with Terraform installed</strong></li><li><strong>Basic CLI knowledge</strong></li><li><strong>Basic GitHub knowledge</strong></li></ul><h3>Step 1: Creating a Variables and Providers file for Terraform Automation</h3><p>The entire infrastructure, including the EC2 instance, security group, IAM roles, and S3 bucket, was provisioned automatically using <strong>Terraform</strong>. Here’s the configuration for the <strong>variables.tf</strong> file to define important variables like <strong>AMI</strong>, <strong>instance type</strong>, and <strong>key name</strong>:</p><pre>variable &quot;region&quot; {<br>  default = &quot;us-east-1&quot;  # The AWS region where resources will be provisioned. Change this if you&#39;re deploying in a different region.<br>  type    = string<br>}<br><br>variable &quot;instance_type&quot; {<br>  default = &quot;t3.micro&quot;   # Specifies the EC2 instance type. Adjust this based on your requirements (e.g., t3.medium for more resources).<br>  type    = string<br>}<br><br>variable &quot;ami&quot; {<br>  default = &quot;ami-0453ec754f44f9a4a&quot;  # The AMI ID for the EC2 instance. Ensure it corresponds to the desired Amazon Linux 2 AMI version.<br>  type    = string<br>}<br><br>variable &quot;key_name&quot; {<br>  default = &quot;jenkinskp&quot;  # The name of the SSH key pair used to access the EC2 instance. Ensure this key exists in your AWS account.<br>  type    = string<br>}<br><br>variable &quot;aws_s3_bucket&quot; {<br>  default = &quot;jenkins-artifacts-bucket007&quot;  # The name of the S3 bucket to store Jenkins artifacts. Make sure the name is unique globally.<br>  type    = string<br>}<br><br>variable &quot;acl&quot; {<br>  default = &quot;private&quot;   # The ACL for the S3 bucket. &quot;private&quot; ensures only authorized users have access. Can be adjusted if necessary.<br>  type    = string<br>}</pre><ul><li>A <strong>variables file</strong> in Terraform is used to define values for configuration parameters, improving flexibility and reusability. It separates infrastructure logic from values, making code cleaner and easier to maintain. By defining variables, you can reuse the same configuration in different environments (e.g., changing AWS regions or instance types). It also allows for secure handling of <strong>sensitive data</strong> and makes scaling your infrastructure easier. Variables can be set through default values, terraform.tfvars files, or environment variables, providing dynamic configuration based on user input or environment needs.</li></ul><p>I also included a <strong>providers.tf</strong> file as well:</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br># Configure the AWS Provider<br>provider &quot;aws&quot; {<br>  region = var.region<br>}</pre><p><em>Next…</em></p><h3>Step 2: Provision EC2 Instance</h3><p>I used <strong>Terraform</strong> to provision an <strong>Amazon Linux 2 EC2 instance</strong> with the necessary configurations. The instance was provisioned with the required <strong>instance type</strong>, <strong>security group</strong>, <strong>IAM role</strong>, and a <strong>user data script</strong> for installing Jenkins automatically located in my <strong>install_jenkins.sh</strong> file.</p><p>Here’s the <strong>install_jenkins.sh </strong>file and<strong> </strong>EC2 configuration code block for provisioning the EC2 instance:</p><pre>#!/bin/bash<br>sudo yum update -y<br>sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo<br>sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key<br>sudo yum upgrade -y # Add required dependencies for the jenkins package<br>sudo yum install java-17-amazon-corretto-devel -y<br>sudo yum install jenkins -y<br>sudo systemctl enable jenkins<br>sudo systemctl start jenkins</pre><ul><li>The bash script above will install the latest version of Jenkins and all of the dependencies needed for it to run. Also notice that I’m using “<strong>sudo yum</strong>” instead of “<strong>sudo apt</strong>” because the OS of my EC2 instance is <strong>Amazon Linux 2</strong> not <strong>Ubuntu</strong>.</li></ul><p>EC2 &amp; Key Pair Configuration:</p><pre>resource &quot;aws_instance&quot; &quot;jenkins&quot; {<br>  ami                         = var.ami<br>  instance_type               = var.instance_type<br>  key_name                    = var.key_name<br>  security_groups             = [aws_security_group.jenkins_sg.name]<br>  associate_public_ip_address = true<br>  user_data                   = file(&quot;install_jenkins.sh&quot;)<br>  tags = {<br>    Name = &quot;JenkinsServer&quot;<br>  }<br>}<br><br>resource &quot;aws_key_pair&quot; &quot;jenkins_key&quot; {<br>  key_name   = &quot;jenkinskp&quot;<br>  public_key = file(&quot;/Users/jeremysmith/.ssh/jenkinskp.pub&quot;) # Path to your existing public SSH key (create one if needed)<br>}</pre><ul><li>As you can see I am referencing my <strong>variables.tf</strong> file with the “<strong>var.</strong>” which allows flexibility in modifying the EC2 instead of meddling with the main code file. And for the key pair I had one created locally since it doesn’t exist just yet. It will then prompt you to create a password. Keep up with it because you will need it for later.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVpuX2sICX6u_OmECGddgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k792yPf_ICJ2zQOXDOTXfw.png" /><figcaption>EC2 Verification</figcaption></figure><p><em>Next…</em></p><h3>Step 3: Security Group Configuration</h3><p>As part of the project, I needed to ensure that my EC2 instance running <strong>Jenkins</strong> was accessible for management and web use while keeping it secure. To do this, I used the <strong>security group</strong> resource in Terraform. This resource defines the rules for controlling <strong>inbound</strong> and <strong>outbound</strong> traffic to the EC2 instance.</p><p>For my setup, I configured the security group to allow <strong>SSH access</strong> on <strong>port 22</strong> (for remote management) and <strong>HTTP access</strong> on <strong>port 8080</strong> (for accessing the Jenkins web interface). Here’s the configuration I used in my main.tf file:</p><pre>resource &quot;aws_security_group&quot; &quot;jenkins_sg&quot; {<br>  name        = &quot;jenkins-security-group&quot;<br>  description = &quot;Allow traffic on ports 22 and 8080&quot;<br><br>  ingress {<br>    description = &quot;Allow SSH Traffic&quot;<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;] #This will be replaced by you EC2 public IP after you deploy this infrastruction<br>  }<br><br>  ingress {<br>    description = &quot;Allow HTTPS Traffic&quot;<br>    from_port   = 443<br>    to_port     = 443<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  ingress {<br>    description = &quot;Allow 8080 Traffic&quot;<br>    from_port   = 8080<br>    to_port     = 8080<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>#Rule for outgoing traffic<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot; <br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAOA3iUD0UON1L7OvUo5iw.png" /><figcaption>SG verification</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGPB-WayfkfZdg-y2yknOg.png" /><figcaption>Ingress and Egress traffic</figcaption></figure><p><em>Next…</em></p><h3>Step 4: <strong>Create S3 Bucket for Jenkins Artifacts and Policies/Roles</strong></h3><p>For storing Jenkins artifacts, I created an <strong>S3 bucket</strong> and <strong>bucket policy</strong> using <strong>Terraform</strong>. The bucket was configured to be <strong>private</strong>, ensuring that only authorized services (like Jenkins) could access the data. I also included a code block to avoid an error involving ACL ownership.</p><p>Here’s the <strong>Terraform code</strong> to create the S3 bucket:</p><pre># Create the S3 bucket<br>resource &quot;aws_s3_bucket&quot; &quot;jenkins_artifacts_s3&quot; {<br>  bucket = var.aws_s3_bucket # Ensure the bucket name is unique<br><br>  tags = {<br>    Name = &quot;Jenkins-Server&quot;<br>  }<br>}<br><br># Resource to avoid error &quot;AccessControlListNotSupported: The bucket does not allow ACLs&quot;<br>resource &quot;aws_s3_bucket_ownership_controls&quot; &quot;s3_bucket_acl_ownership&quot; {<br>  bucket = aws_s3_bucket.jenkins_artifacts_s3.id<br>  rule {<br>    object_ownership = &quot;ObjectWriter&quot;<br>  }<br>}<br><br>#This resource attaches an IAM policy to an IAM role<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;s3-jenkins-access&quot; {<br>  policy_arn = aws_iam_policy.s3-jenkins-policy.arn<br>  role       = aws_iam_role.my-s3-jenkins-role.name<br>}<br><br>#This resource creates an instance profile, which is used to associate an IAM role with an EC2 instance<br>resource &quot;aws_iam_instance_profile&quot; &quot;s3-jenkins-profile&quot; {<br>  name = &quot;s3-jenkins-profile&quot;<br>  role = aws_iam_role.my-s3-jenkins-role.name<br>}<br><br>#Bucket policy <br>resource &quot;aws_iam_policy&quot; &quot;s3-jenkins-policy&quot; {<br>  name   = &quot;s3-jenkins-rw-policy&quot;<br>  policy = &lt;&lt;EOF<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;S3ReadWriteAccess&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:GetObject&quot;,<br>        &quot;s3:PutObject&quot;,<br>        &quot;s3:ListBucket&quot;<br>      ],<br>      &quot;Resource&quot;: [<br>        &quot;arn:aws:s3:::jenkins_artifacts_s3&quot;,<br>        &quot;arn:aws:s3:::jenkins_artifacts_s3/*&quot;<br>      ]<br>    }<br>  ]<br>}<br>EOF<br>}</pre><h4><strong>Explanation:</strong></h4><ul><li>This policy grants the EC2 instance (with the appropriate IAM role attached) full <strong>read and write</strong> access to the specified <strong>S3 bucket</strong> (jenkins_artifacts_s3). It allows Jenkins to:</li></ul><p><strong>— Retrieve objects</strong> from the bucket (for reading logs, reports, etc.),</p><p><strong>— Upload objects</strong> to the bucket (for storing build artifacts, logs, etc.),</p><p><strong>— List the contents</strong> of the bucket to see available objects.</p><ul><li>In short, this policy ensures Jenkins has the necessary permissions to interact with the S3 bucket for storing and retrieving build artifacts.</li></ul><p>— <strong>aws_iam_role_policy_attachment</strong>: Attaches the <strong>S3 permissions policy</strong> to the <strong>IAM role</strong> so that it has the necessary permissions to interact with S3.</p><p>— <strong>aws_iam_instance_profile</strong>: Creates an <strong>instance profile</strong> to allow the <strong>EC2 instance</strong> to assume the <strong>IAM role</strong> and use the permissions granted by the policy.</p><ul><li>These resources together enable your EC2 instance (running Jenkins) to securely interact with AWS S3 using the permissions defined in the IAM role and policy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7T-wWD1fzn6gdUwWhhHHDw.png" /><figcaption>Jenkins S3 bucket</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFx8d1qwdd6eNkb_0BD3dQ.png" /><figcaption>ACL Permissions for owner allows object list/write and bucket read/write</figcaption></figure><p><em>Next…</em></p><h3>Step 5: Deploy infrastructure and verify Jenkins accessibility</h3><ol><li>Let’s use a few Terraform commands to make sure we are ready to go and to deploy.</li></ol><p>Terraform initiation:</p><pre>terraform init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GBnrTW9u29dn70j5zF_mg.png" /><figcaption>This command must be ran first</figcaption></figure><p>Terraform proper formatting:</p><pre>terraform fmt #Fixes the formatting making it more uniform for terraform</pre><p>Terraform validation:</p><pre>terraform validate </pre><p>Terraform plan:</p><pre>terraform plan #This shows you a plan terraform comes up with about what will be built and how</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DyPAA39vYDt3lSKTlrGpQ.png" /><figcaption>Should see a similar output. If it’s your first time doing this you will see a value next to add.</figcaption></figure><p>Terraform apply:</p><pre>terraform apply<br><br>#OR<br><br>terraform apply -auto-aprove #this one avoids the &#39;yes&#39; or &#39;no&#39; confirmation</pre><p>What you should see after running the Terraform apply command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXPsdvuCW0Df7boDBHkXUw.png" /><figcaption>Infrastructure successfully deployed</figcaption></figure><p>2. Let’s verify if we can access the Jenkins dashboard. We will first need to retrieve the InitialAdminPassword and to do that we will need to connect to our EC2 via ssh.</p><p>— Navigate to the AWS dashboard</p><p>— Click on your Jenkins EC2 and click connect</p><p>— In your VSCode terminal input this path to your <strong>.pem</strong> file</p><pre> cd /Users/your-username/.ssh/   </pre><p>— Once there copy the <strong>chmod 400 “&lt;your-file-name&gt;.pem” </strong>and paste it in your VSCode terminal</p><p>— Copy and paste the<strong> ssh -i “jenkinskp.pem” </strong><a href="/service/mailto:ec2-user@ec2-54-227-67-172.compute-1.amazonaws.com"><strong>ec2-user@ec2–54–227–67–172.compute-1.amazonaws.com</strong></a> from AWS into your VSCode terminal and log into your EC2 with the password you made for your local key earlier.</p><p>Run the following command:</p><pre> sudo cat /var/lib/jenkins/secrets/initialAdminPassword  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3OcVosCh27q5IaP9Ku1Gg.png" /><figcaption>Copy the password</figcaption></figure><p>3. Now all we need to do is input <strong>http://&lt;your-ec2-public-ip&gt;:8080</strong> into the url search bar and we should have access to the Jenkins webpage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GOofW-WspS-mdLaGCqCfQ.png" /><figcaption>Paste the password you got from the shell</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfuuUVrqLWEhc6wLDZ3STw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVONo639LfXGHPLbxFHI0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u67rylHcQs6JH8KwyrfRNA.png" /><figcaption>Install suggested plugins then create a profile.</figcaption></figure><p>And BOOM! We have action and Jenkins is ready to be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJyb8SyJcPy4wweS-Kv_oQ.png" /><figcaption>Success!!!</figcaption></figure><h3><strong>Tips to be mindful of:</strong></h3><p>There are some things you want to keep in mind when creating the Terraform template. Here are some things to pay attention based on my troubleshooting and experience:</p><ol><li>Make sure that the user data is applicable to the OS type of your EC2 instance (eg. Amazon Linux 2, Ubuntu, etc.).</li><li>Make sure that the bash script you’re using for your user data has all of the latest versions in it. I used a dated version of java 11 when I actually needed java 17 +.</li><li>Double check your naming conventions in your <strong>variables.tf</strong> file and compare it with your <strong>main.tf</strong> for any discrepancies .</li><li>Double check your formatting and alignments.</li><li>If your Jenkins is not accessible and you check the EC2 shell and it says failed to install or it wont start, double check your EC2 instance storage (<strong>t2.micro</strong> I found is too small for Jenkins). Use a <strong>t3.micro</strong> instead.</li></ol><h3>Documentation</h3><ul><li><a href="https://www.jenkins.io/doc/book/installing/linux/">Linux</a></li><li><a href="https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-build">Build infrastructure | Terraform | HashiCorp Developer</a></li><li><a href="https://developer.hashicorp.com/terraform/language/values/variables#custom-validation-rules">Input Variables - Configuration Language | Terraform | HashiCorp Developer</a></li><li><a href="https://developer.hashicorp.com/terraform/language/style">Style Guide - Configuration Language | Terraform | HashiCorp Developer</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*qBRuWVJ4U0X_1hAtCgZQXA.png" /></figure><p>Let’s connect! <a href="https://www.linkedin.com/in/jeremy-smith-o3/">LinkedIn</a></p><p>My GitHub repo: <a href="https://github.com/jeremysmith24/My-Terraform-Projects">https://github.com/jeremysmith24/My-Terraform-Projects</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d16dc95ff309" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Swarm — Deploying Wordpress and MySQL]]></title>
            <link>https://medium.com/@jsantoine24/docker-swarm-deploying-wordpress-and-mysql-df26374554cb?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/df26374554cb</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[docker-swarm]]></category>
            <category><![CDATA[docker-secrets]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker-services]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 05:18:11 GMT</pubDate>
            <atom:updated>2024-11-26T18:02:56.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9UruT8qhchMeakC1" /></figure><h3>Docker Swarm — Deploying Wordpress and MySQL</h3><h4>Use case</h4><p>Level Up Publications is an online publication that posts blogs about the hottest updates and trends in IT. Level Up Publications is in the process of transitioning its web infrastructure to a containerized environment using Docker Swarm due to the rapid growth of its reader base. In a business landscape that is increasingly digital, efficient and flexible web infrastructure is not just a competitive advantage, but a necessity. The need to quickly adapt to changing customer demands, scale up or down based on traffic, and ensure uninterrupted service availability means businesses need a solution that can manage these requirements effectively and affordably.</p><h4>Objective</h4><p>Implement Docker Swarm to enhance Level Up Publications’ application management and scalability, ensuring the website remains responsive and available during fluctuating traffic. Leverage containerization to improve system resiliency, reduce downtime, and isolate applications for better security. Additionally, secure sensitive data with Docker secrets to protect valuable content and maintain reader trust.</p><h4>Build specifications</h4><ol><li><strong>Deploy a 3 node Docker Swarm cluster.</strong></li><li><strong>Create 2 networks. One for frontend and another for backend.</strong></li><li><strong>Create MySQL service</strong></li></ol><p>— associated with the backend network</p><p>— Only 1 replica</p><p>— Make the database service resilient and its data persistent across container restarts, use Docker Volumes.</p><p>4.<strong> Create the Wordpress service</strong></p><p>— Associated with the frontend network</p><p>— Should use port 80</p><p>— Accessible from the browser</p><p>— 3 replicas</p><p>— Associated with the MySQL service</p><h4>Pre-reqs</h4><ul><li><strong>Docker and Docker Swarm Knowledge</strong></li><li><strong>Access to EC2 Instances or VMs</strong></li><li><strong>Docker Compose or CLI Familiarity</strong></li><li><strong>Security Groups and Network Configuration on AWS</strong></li><li><strong>Persistent Storage basics (Volumes)</strong></li><li><strong>3 Nodes</strong> (1 manager, 2 workers)</li></ul><h3>Step 1: Set Up Docker Swarm Cluster</h3><ol><li><strong>Initialize the Docker Swarm on EC2 Manager Node (Node 1)</strong>: On your <strong>manager node</strong> (EC2 instance 1), run:</li></ol><pre>docker swarm init --advertise-addr &lt;manager-node-ip&gt;</pre><ul><li>Replace &lt;manager-node-ip&gt; with the private IP address of the EC2 manager node. This will initialize the Swarm and output a join token.</li><li>Run the following command in node1 to make it the manager node:</li></ul><pre>docker swarm init --advertise-addr &lt;master node IP adress&gt;</pre><p>From here you should see a join token for worker nodes.</p><p>Example output:</p><pre>Swarm initialized: current node is now a manager.<br>To add a worker to this swarm, run the following command:</pre><pre>    docker swarm join --token &lt;SWARM-TOKEN&gt; 192.168.1.10:2377</pre><pre>To add a manager to this swarm, run &#39;docker swarm join-token manager&#39; and follow the instructions.</pre><ul><li>Open 2 more terminal windows and Copy paste the token <strong>docker swarm join — token &lt;SWARM-TOKEN&gt; 192.168.1.10:2377</strong> in both <strong>node2</strong> and <strong>node3 </strong>respectively then run it. Your own IP will be listed on the end. This is just an example of what it looks like <strong>do not </strong>copy the IP address.</li><li>Both <strong>node2</strong> &amp; <strong>node3</strong> should now be a part of the swarm as worker nodes.</li></ul><p>3.<strong> Verify the Swarm Cluster</strong>: On the <strong>manager node</strong>, check the nodes in the swarm with:</p><pre>docker node ls</pre><ul><li>This should list your manager node and worker nodes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8-igVkBadVYH5jE4DaDZw.png" /><figcaption>Nodes are active and ready within the swarm</figcaption></figure><h3>Step 2: Create a docker-compose.yml file</h3><ol><li>Either create a new directory or use the one you’re currently in and run the following command to create a docker-compose.yml file:</li></ol><pre>touch docker-compose.yml </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oXy6ixiQhWfVgegs5RykqQ.png" /><figcaption>I ended up moving this file to a directory called “wordpress_project” right after.</figcaption></figure><p>— You can either use <strong>vim</strong> or <strong>nano</strong> to get into the text editor of the docker-compose file directly from the terminal or you can use VSCode project management folder to open up the docker-compose editor. I find this is a little easier since you have to be conscious of the indentations and VSCode does a great job of helping you keep track with the visuals of the indentations (you will see me point this out very shortly).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DqRkb3sbdJQXcnMcWSmyg.png" /><figcaption>You will see a button that says “Open files” or “folders”</figcaption></figure><ul><li>From here a drop-down list will appear and you just have to click on your directory that your docker-compose.yml file is in.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hnpm8RN7Z4k4gSoqnnhw4w.png" /><figcaption>My docker-compose.yml file in the wordpress_project directory.</figcaption></figure><p>— From here I began to build my compose file with all of the necessary components per the business specifications.</p><h3>Step 3: Creating Docker Secrets:</h3><p>You need to create the Docker Secrets (db_root_pass and db_user_pass) before deploying the stack:</p><pre>echo &quot;supersecretrootpassword&quot; | docker secret create db_root_pass -<br>echo &quot;supersecretpassword&quot; | docker secret create db_user_pass -</pre><ul><li>Now that we have our secrets setup and stored in docker secrets lets build out the compose file now:</li></ul><pre>version: &#39;3.7&#39; # Optional to specify the version<br><br>services:<br>  mysql:<br>    image: mysql:lts<br>    secrets:<br>      - db_root_pass      # Reference to the root password secret for MySQL<br>      - db_user_pass      # Reference to the user password secret for MySQL<br>    environment:<br>      - MYSQL_ROOT_PASSWORD_FILE=/run/secrets/db_root_pass  # Set root password from secret<br>      - MYSQL_PASSWORD_FILE=/run/secrets/db_user_pass        # Set user password from secret<br>      - MYSQL_DATABASE=mysql_db                               # Database to create on MySQL startup<br>      - MYSQL_USER=admin                                      # MySQL user for accessing the database<br>    volumes:<br>      - mysql-data:/var/lib/mysql  # Persistent storage for MySQL data<br>    networks:<br>      - backend-network           # Connect MySQL to the backend network for communication with other services<br><br>  wordpress:<br>    image: wordpress:lts<br>    deploy:<br>      replicas: 3                # Scale WordPress to 3 replicas for high availability<br>    environment:<br>      - WORDPRESS_DB_HOST=mysql:3306  # MySQL host and port, where &#39;mysql&#39; is the service name and &#39;3306&#39; is the default MySQL port<br>      - WORDPRESS_DB_NAME=${MYSQL_DATABASE}  # The MySQL database name to connect to, passed as an environment variable<br>      - WORDPRESS_DB_USER=${MYSQL_USER}      # The MySQL user for WordPress to use for connecting to the database<br>      - WORDPRESS_DB_PASSWORD_FILE=/run/secrets/mysql_user_password  # The MySQL user password, securely passed via secret<br>    ports:<br>      - &quot;80:80&quot;  # Map port 80 on the host to port 80 on the WordPress container (makes it accessible via the web)<br>    depends_on:<br>      - mysql  # Ensure WordPress waits for MySQL to be ready before starting<br>    networks:<br>      - frontend-network  # Connect WordPress to the frontend network for web access and communication with other services<br><br>secrets:<br>  db_root_pass:<br>    external: true  # Use the external Docker secret for MySQL root password (pre-created outside of Compose file)<br>  db_user_pass:<br>    external: true  # Use the external Docker secret for MySQL user password (pre-created outside of Compose file)<br><br>volumes:<br>  mysql-data:  # Create a persistent volume to store MySQL data, ensuring it&#39;s not lost when containers are stopped or restarted<br><br>networks:<br>  backend-network:  # Custom network for backend services (like MySQL) to communicate securely<br>  frontend-network:  # Custom network for frontend services (like WordPress) that need to be exposed to the internet</pre><ul><li>I added inline comments for clarification on each spec.</li><li><strong><em>NOTE:</em></strong> Be very attentive to the indentations when you’re building your compose file. If even one indention is off your deployment could blow up your computer and bottom out. Jk, but definitely pat attention or the stack deployment could fail.</li><li>Use the following command to deploy the stack:</li></ul><pre>docker stack deploy -c docker-compose.yml my_stack</pre><h4><strong>Docker-compose file breakdown:</strong></h4><p><strong><em>Services = containers</em></strong></p><ol><li><strong>MySQL Service</strong>:</li></ol><ul><li>The <strong>secrets</strong> section is used to securely store MySQL passwords. These are <strong>external secrets</strong> that need to be created manually with docker secret create.</li><li><strong>MYSQL_ROOT_PASSWORD_FILE=/run/secrets/db_root_pass</strong> tells the MySQL container where to get the root password securely.</li><li><strong>MYSQL_USER</strong> and <strong>MYSQL_PASSWORD_FILE</strong> are used to define the user and its password for MySQL, pulling the password from the secret.</li><li>The <strong>volumes</strong> section ensures that the MySQL data persists across container restarts by storing it in a named volume (mysql-data).</li><li>The <strong>networks</strong> section connects MySQL to the backend-network, making it available for backend services (e.g., WordPress).</li></ul><p>2.<strong> WordPress Service</strong>:</p><ul><li><strong>deploy.replicas: 3</strong> scales WordPress to 3 replicas for higher availability and load balancing.</li><li><strong>environment</strong> contains all the necessary configurations to link WordPress with MySQL:</li><li><strong>WORDPRESS_DB_HOST=mysql:3306</strong>: Points WordPress to the MySQL service, specifying the MySQL host (mysql) and port (3306).</li><li><strong>WORDPRESS_DB_NAME, </strong><strong>WORDPRESS_DB_USER, and </strong><strong>WORDPRESS_DB_PASSWORD_FILE</strong> use environment variables and secrets to configure WordPress’s connection to MySQL securely.</li><li><strong>ports</strong> exposes port 80 on the host and container, making the WordPress site accessible through the web browser.</li><li><strong>depends_on</strong> ensures that WordPress waits for MySQL to be fully ready before starting, helping to avoid connection errors.</li><li><strong>networks</strong> connects WordPress to the frontend-network, allowing it to be accessed publicly via port 80.</li></ul><p>3.<strong> Secrets Section</strong>:</p><ul><li><strong>db_root_pass</strong> and <strong>db_user_pass</strong> are marked as <strong>external</strong> because they are created manually outside of the docker-compose.yml file, ensuring the secrets are securely stored and not hardcoded.</li></ul><p>4.<strong> Volumes Section</strong>:</p><ul><li>The <strong>mysql-data</strong> volume ensures that the MySQL data is persistent across container restarts, so you won’t lose the database when the container is stopped or removed.</li></ul><p>5.<strong> Networks Section</strong>:</p><ul><li><strong>backend-network</strong> and <strong>frontend-network</strong> are custom networks to ensure proper isolation between the different services (e.g., WordPress needs to be on the frontend network for internet access, and MySQL on the backend network for internal communication).</li><li><strong>Backend Network</strong> is used for services that should not be exposed directly to the outside world (like MySQL).</li><li><strong>Frontend Network</strong> is used for services that should be exposed to the internet (like WordPress).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsB3Hj9GVrjIWLz6f30uzg.png" /><figcaption>Stack deploying</figcaption></figure><p>— You can use the following command respectively to list out and verify the networks/services/volumes etc. that you have created:</p><pre>docker network ls<br>docker service ls<br>docker container ps<br>docker service ps my_stack</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vllwHhoFurV3L0hiX_rPJA.png" /><figcaption>The backend and frontend networks were successfully created.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*-Tb-UCGnxjJrmKO2EW59EQ.png" /><figcaption>We see the 2 services deployed (MySQL, WordPress)</figcaption></figure><ul><li>You can curl localhost:80 to access your WordPress through the browser or by entering in your browser url <strong>http://&lt;your-server-ip-address&gt;:80</strong>.</li></ul><p>To access MySQL running in your Docker stack, follow these steps:</p><h3>Step 4: Check the MySQL Service</h3><ol><li>Ensure that your MySQL service is running correctly in your Docker stack. Run the following command to verify the status:</li></ol><pre>docker service ls</pre><ul><li>You should see an entry for my_stack_mysql with a replica running (1/1).</li></ul><p><strong>2. Find the MySQL Container</strong></p><p>You need to find the container ID or name of the MySQL container to interact with it.</p><ul><li>Run the following command to list all the containers in your stack:</li></ul><pre>docker ps</pre><ul><li>Look for the container running the mysql:lts image. You&#39;ll see the container ID and the names of the containers in the stack. For example:</li></ul><pre>CONTAINER ID   IMAGE           COMMAND                  CREATED          STATUS          PORTS     NAMES<br>abc123xyz456   mysql:lts       &quot;docker-entrypoint.s…&quot;   3 minutes ago    Up 2 minutes    3306/tcp  my_stack_mysql.1.abcd1234</pre><p><strong>3. Access MySQL Directly Inside the Container</strong></p><p>Once you have the container ID (e.g., abc123xyz456), you can access MySQL directly from inside the container using docker exec. For example:</p><pre>docker exec -it my_stack_mysql.1.abcd1234 mysql -u root -p</pre><p>— This command runs the mysql client inside the MySQL container and logs you in as the root user. You will be prompted to enter the MySQL root password. If you&#39;ve set the password using the secrets, it will be available inside the container as /run/secrets/db_root_pass.</p><p>You should be in the database now!</p><h3><strong>Conclusion</strong></h3><p>In this project, I deployed a <strong>3-node Docker Swarm</strong> on <strong>EC2</strong>, with separate <strong>frontend</strong> and <strong>backend</strong> networks. The <strong>MySQL service</strong> used Docker volumes for persistence and <strong>Docker secrets</strong> for secure password storage. The <strong>WordPress service</strong> ran with <strong>3 replicas</strong> for high availability, connected to MySQL.</p><p>This setup demonstrated how Docker Swarm and Docker Compose provide a secure, scalable, and resilient environment for containerized applications.</p><h4><strong>Docker documentation</strong></h4><ul><li><a href="https://docs.docker.com/reference/compose-file/build/">Compose Build Specification</a></li><li><a href="https://docs.docker.com/compose/how-tos/use-secrets/">Secrets in Compose</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*qBRuWVJ4U0X_1hAtCgZQXA.png" /></figure><p>Let’s connect! <a href="https://www.linkedin.com/in/jeremy-smith-o3/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df26374554cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Docker Containers with cAdvisor]]></title>
            <link>https://medium.com/@jsantoine24/monitoring-docker-containers-with-cadvisor-ed21a9cfae95?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed21a9cfae95</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cadvisor]]></category>
            <category><![CDATA[docker-monitoring]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[docker-container]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 05:15:20 GMT</pubDate>
            <atom:updated>2024-11-20T05:15:20.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0t2o6Uhu4P6oRQ4D.png" /></figure><p>Testing purposes</p><h3>Using cAdvisor on a Mac to Monitor Docker Container Activity</h3><p>As an engineer working with Docker containers on macOS, I wanted a way to monitor the performance of my containers in real-time. I turned to <strong>cAdvisor</strong>, a tool developed by Google that provides a web UI to display detailed metrics about running containers, including CPU, memory, and network usage. Setting up cAdvisor on a Mac isn’t straightforward due to macOS’s limitations with mounting certain system directories. But here’s a breakdown of how I managed to get <strong>cAdvisor</strong> up and running on my Mac to monitor Docker container activity.</p><h4>Setting Up Docker and cAdvisor</h4><p>The first step was ensuring Docker was running properly on my Mac. I had <strong>Docker Desktop</strong> installed, which makes it easy to run containers on macOS by using a lightweight VM behind the scenes. Once Docker was running, I needed to deploy <strong>cAdvisor</strong> in a container itself, but the challenge was mounting the necessary system directories like /var/lib/docker into the container.</p><p>The Problem with Mounting /var/lib/docker</p><p>When I attempted to run cAdvisor with the following Docker command:</p><pre>sudo docker run -d --name=cadvisor --network test-network -p 8080:8080 -v /:/rootfs:ro -v /var/run:/var/run:rw -v /sys:/sys:ro -v /var/lib/docker/:/var/lib/docker:ro --privileged --device=/dev/kmsg --restart=unless-stopped gcr.io/cadvisor/cadvisor</pre><p>I encountered the error message below:</p><pre>error while creating mount source path &#39;/var/lib/docker&#39;: mkdir /var/lib/docker: read-only file system.</pre><p>This happened because Docker on macOS doesn’t allow write access to certain system directories like /var/lib/docker due to the nature of how Docker runs on macOS, using a virtual machine that doesn’t give full access to the host file system.</p><h4>The Solution: Removing the Mount for /var/lib/docker</h4><p>The fix was simple: I didn’t actually need to mount /var/lib/docker for <strong>cAdvisor</strong> to monitor container activity. So, I removed the /var/lib/docker volume mount and re-ran the command.</p><p>Here’s the modified version of the command:</p><pre>sudo docker run -d \<br>  --name=cadvisor \<br>  --network test-network \<br>  -p 8080:8080 \<br>  -v /:/rootfs:ro \<br>  -v /var/run:/var/run:rw \<br>  -v /sys:/sys:ro \<br>  --privileged \<br>  --device=/dev/kmsg \<br>  --restart=unless-stopped \<br>  gcr.io/cadvisor/cadvisor</pre><p>By removing the /var/lib/docker mount, <strong>cAdvisor</strong> ran smoothly without hitting the <strong>read-only file system</strong> error. The container was now up and running!</p><p>Verify your cAdvisor container is up and running with:</p><pre>docker container ps</pre><h4>Connecting cAdvisor to a Test Network</h4><p>To monitor container activity, I wanted to make sure that my containers could communicate with <strong>cAdvisor</strong>. To do that, I created a custom Docker network called test-network and connected <strong>cAdvisor</strong> to that network.</p><p>Here’s the command I used to create the network:</p><pre>docker network create test-network<br><br>docker network ls #Verify your network</pre><p>When I ran cAdvisor, I made sure to connect it to this network with the --network test-network flag, so that other containers I create could communicate with it.</p><h4>Testing with Containers</h4><p>Now that cAdvisor was up and running, I needed to test it. I created two test containers to communicate with each other — an <strong>busybox container</strong> acting as a server, and a <strong>busybox container</strong> that would ping the cAdvisor server.</p><p>1.<strong> Run a busybox container that pings the cAdvisor container</strong>:</p><pre>docker run -d --name busybox-container --network test-network busybox /bin/sh -c &quot;while true; do ping -c 1 cadvisor; sleep 5; done&quot;</pre><p>This container pings the cAdvisor-container every 5 seconds. It simulates network activity that cAdvisor can monitor.</p><h4>Monitoring Activity in cAdvisor</h4><p>Now that I had containers communicating with each other, I was able to monitor them using cAdvisor. To access the <strong>cAdvisor web UI</strong>, I simply navigated to: <a href="http://localhost:8080/">http://localhost:8080</a> or:</p><pre>curl localhost:8080 #Done in the terminal</pre><p>In the UI, I could see all running containers, including the <strong>busybox</strong> container with detailed statistics about it, such as:</p><ul><li><strong>CPU usage</strong></li><li><strong>Memory consumption</strong></li><li><strong>Network traffic</strong></li><li><strong>Disk I/O</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDww8IvV1RdF4G4yjL0sQg.png" /><figcaption>Click Docker Containers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRPvIn-YeH5_SNHjD7hOww.png" /><figcaption>Click ‘cadvisor’ under Subcontainers to view stats</figcaption></figure><p>If I were running multiple containers then they would all be listed under ‘Subcontainers’ as well<strong>. cAdvisor</strong> also allows me to monitor historical data and get real-time performance metrics, which is incredibly useful for troubleshooting or performance tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykuL9YpGJq1OHeHaJz64Ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfWh7g_KR_he2rN8Out7kQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avYS2ifxEfX2u7QSw8oWXw.png" /><figcaption>Container statistics in real-time</figcaption></figure><h4>Conclusion</h4><p>Using cAdvisor on a Mac to monitor Docker containers is straightforward once you resolve issues with mounting system directories. By removing the /var/lib/docker mount and connecting containers to a shared network, I was able to use cAdvisor to monitor container activity, including real-time performance metrics.</p><p>This setup has been immensely helpful for keeping track of resource usage, especially as I scale my containerized applications. If you’re working on macOS with Docker, I highly recommend trying out cAdvisor to monitor your containers effectively!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*qBRuWVJ4U0X_1hAtCgZQXA.png" /></figure><p>Let’s connect! <a href="https://www.linkedin.com/in/jeremy-smith-o3/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed21a9cfae95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Container Orchestration with Docker Swarm]]></title>
            <link>https://medium.com/@jsantoine24/container-orchestration-with-docker-swarm-64e4bc862c34?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/64e4bc862c34</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker-swarm]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 03:10:07 GMT</pubDate>
            <atom:updated>2024-11-20T03:10:07.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFxirAcxLANsp-S9P_M3TQ.png" /></figure><h4>Use case</h4><p>Your company is new to using containers and has been having issues with containerized workloads failing for their global shipping application. The company is worried about additional potential data loss as they have no way to reschedule containers that are failing. The company has one week to update their infrastructure and leverage the use of Docker Swarm so that data can be restored for the containers that are no longer in a healthy state. Because they are not familiar with Docker Swarm, they will need a step-by-step guide on setting up a Swarm for their containerized workloads to assist with container orchestration.</p><p>The solution should include the use of a global service since the company’s global shipping application is having issues. Your Swarm should be able to launch the containers using a global service. Remember, a service is simply a group of containers of the same image that facilitates the scaling of applications. Your global shipping application will require the use of at least three networked hosts, which should be AWS EC2 Ubuntu 20.04 instances.</p><h4>Objective</h4><p>As the junior engineer, you are responsible for only configuring Docker Swarm and providing your team with a step-by-step guide of setting up the Swarm. You should assume that there are new team members that may not have Docker installed on their devices. Your swarm creation should include the following steps via your remote ssh terminal in VSCode:</p><h4>Pre-reqs</h4><ul><li><strong>Familiarity with Docker Basics</strong></li><li><strong>Networking Knowledge (for Cloud or Local Setup)</strong></li><li><strong>Access to Multiple Machines/VMs</strong></li><li><strong>SSH Access to Remote Nodes</strong></li><li><strong>SSH Host configured in your desired code IDE (ex: VSCode)</strong></li></ul><h3>Setting Up Your 3-Node Docker Swarm on AWS</h3><h4>1. Set Up Node1 (Your Current Environment)</h4><p>Your current EC2 instance will serve as <strong>Node1</strong> in your swarm. Nodes 2 &amp; 3 must also be using the same <strong>OS</strong>, <strong>keypair</strong>, and <strong>Security Group</strong> as <strong>Node1</strong>. (this was done in the AWS console during the creation of the EC2&#39;s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*MRvlH1As8IiN4dDV6lJKkQ.png" /><figcaption>My 3 EC2 instances renamed</figcaption></figure><ul><li>In the VSCode terminal change the hostname of the instance for easy identification. Run the following command as <strong>root</strong>:</li></ul><pre>hostnamectl set-hostname node1<br>reboot</pre><ul><li>Close the terminal and open a new one and <strong>ssh</strong> back into the nodes and<br>you should see the update.</li></ul><h4>2. Modify the Security Group for Node1</h4><ul><li>Modify the <strong>Security Group</strong> associated with your EC2 instance (Node1) to allow all traffic from the <strong>VPC CIDR</strong>. This ensures you can use <strong>private IPs</strong> to reference other nodes within the swarm, avoiding the need to rely on public IPs for every restart.</li><li>— This change applies <strong>only</strong> to the swarm. You will still need the <strong>public IP</strong> of Node1 each time you connect from VSCode initially.</li><li>Optionally, you can also update the <strong>Name Tag</strong> in AWS for this instance to <strong>“node1”</strong> to make it easy to reference.</li></ul><h4>3. Launch 2 More EC2 Instances (Node2 and Node3)</h4><ul><li><strong>Name Tags</strong>: After launching the EC2 instances, update their <strong>Name Tags</strong> to <strong>node2</strong> and <strong>node3</strong>, respectively. Alternatively, you can assign the appropriate name tags during the launch process.</li></ul><p><strong>Instance Configuration</strong>:</p><ul><li><strong>Ubuntu Server 22.04 LTS</strong> (or your preferred version).</li><li><strong>t2.micro</strong> instance type.</li><li>Use the <strong>same SSH key pair</strong> as Node1 to allow SSH access.</li><li><strong>Security Group</strong>: Use the same security group as Node1 to ensure proper network communication between the nodes.</li></ul><p><strong>Add another rule to the Security Group for your nodes (inbound &amp; outbound):</strong></p><ul><li><strong>Type: All TCP.</strong></li><li>Copy the the <strong>IvP4 CIDR</strong> from the <strong>VPC</strong> that the <strong>SG</strong> is attached to.</li><li>Paste it in the <strong>‘Source’</strong> and save it.</li></ul><p><strong>User Data Script</strong>: To install Docker automatically on your instances, add the following <strong>User Data</strong> during instance launch:</p><pre>curl -fsSL https://get.docker.com -o get-docker.sh<br>sh get-docker.sh</pre><h4><strong>4. Add SSH Key to Node 1</strong></h4><ul><li>In the node1 terminal run <strong>cd /root/.ssh</strong></li><li>Use a text editor to <strong>copy and paste</strong> your <strong>Node1 .pem file</strong> into this directory. Ensure the file name matches the name of the key you’re using for SSH access.</li></ul><h4><strong>5. Create SSH Config File on Node1</strong></h4><ul><li>In the node1 terminal run cd /root (If not already in the .ssh<br>directory).</li></ul><pre>cd /root/.ssh</pre><ul><li>Create a new SSH <strong>config file</strong> with the following details using a text editor (use vim):</li></ul><pre>Host node2<br>HostName PrivateIP<br>User ubuntu<br>IdentityFile /root/.ssh/yourkey.pem<br><br>Host node3<br>HostName PrivateIP<br>User ubuntu<br>IdentityFile /root/.ssh/yourkey.pem</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnrbUyDziBUk-l9gUYmvMA.png" /><figcaption>Replace &lt;PrivateIP of Node2&gt; and &lt;PrivateIP of Node3&gt; with the <strong>private IP addresses</strong> of <strong>Node2</strong> and <strong>Node3</strong>, respectively.</figcaption></figure><p>You should now be able to run <strong>ssh</strong> <strong>node2</strong> or <strong>ssh node3</strong> and connect<br>to either. SSH into both and verify docker is installed by running<br>Docker version. They haven’t been named at this point so you will see the IP address for the host names of node2 &amp; node3.</p><h4>6. Change Hostnames on Node2 and Node3</h4><ul><li>Open 2 new terminal windows and change the hostnames of <strong>Node2</strong> and <strong>Node3</strong> to ‘<strong>node2’</strong> and ‘<strong>node3’</strong>, one at a time, using the hostnamectl command as root:</li></ul><pre>hostnamectl set-hostname node2<br>hostnamectl set-hostname node3<br>reboot</pre><ul><li>Again, you may not see the change immediately and still see the IP of the nodes. If not, close the terminal and open a new one and <strong>ssh</strong> back into the nodes and you should see the update.</li></ul><h4><strong>7. Verify SSH Connectivity</strong></h4><ul><li>You should now be able to connect to <strong>Node2</strong> and <strong>Node3</strong> via SSH by running in each terminal window (your terminal should be split 3 ways):</li></ul><pre>ssh node2<br>ssh node3</pre><ul><li>SSH into each node and check if Docker is installed by running:</li></ul><pre>docker --version</pre><ul><li>At this point, you should have <strong>3 terminals</strong> opened in <strong>VSCode</strong> to manage your nodes:</li><li>One for <strong>Node1</strong>.</li><li>One for <strong>Node2</strong>.</li><li>One for <strong>Node3</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWts9bSZdvXBa-zkIzZn-Q.png" /><figcaption>Should look like this</figcaption></figure><h4><strong>8. Initiating Docker Swarm (Manager and worker nodes)</strong></h4><p>Run the following command in node1 to make it the manager node:</p><pre>docker swarm init --advertise-addr &lt;master node IP adress&gt;</pre><p>From here you should see a join token for worker nodes.</p><p>Example output:</p><pre>Swarm initialized: current node is now a manager.<br><br>To add a worker to this swarm, run the following command:<br><br>    docker swarm join --token &lt;SWARM-TOKEN&gt; 192.168.1.10:2377<br><br>To add a manager to this swarm, run &#39;docker swarm join-token manager&#39; and follow the instructions.</pre><ul><li>Copy and paste the token <strong>docker swarm join — token &lt;SWARM-TOKEN&gt; 192.168.1.10:2377</strong> in both <strong>node2</strong> and <strong>node3 </strong>and run it. Your own IP will be listed on the end. This is just an example of what it looks like <strong>do not </strong>copy the IP address.</li><li>Both <strong>node2</strong> &amp; <strong>node3</strong> should now be a part of the swarm as worker nodes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0DaLtGaMHXMPGjWIaWFuw.png" /><figcaption>Nodes 2 &amp; 3 are now worker nodes in the swarm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*ct7bWbZAe7yndx0jkBHF3A.png" /><figcaption>All nodes are ready and active in the swarm</figcaption></figure><p><strong><em>Note:</em></strong> <em>The token is </em><strong><em>unique</em></strong><em> to your swarm and must be kept secure. You can </em><strong><em>regenerate</em></strong><em> the join token at any time on the manager node if needed by running:</em></p><pre>docker swarm join-token --rotate worker</pre><h3>Conclusion</h3><p>In this project, I successfully set up a <strong>3-node Docker Swarm</strong> on AWS EC2 instances, creating a scalable and distributed containerized environment. By configuring hostnames, security groups, and SSH access, I ensured seamless communication between the nodes. I installed and verified Docker on each node, establishing a highly available swarm. This project gave me valuable hands-on experience in deploying and managing a Docker Swarm cluster, and I now have a solid foundation for scaling and optimizing containerized applications in the cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*qBRuWVJ4U0X_1hAtCgZQXA.png" /></figure><p>Let’s connect! <a href="https://www.linkedin.com/in/jeremy-smith-o3/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e4bc862c34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Swarm vs. Kubernetes]]></title>
            <link>https://medium.com/@jsantoine24/docker-swarm-vs-kubernetes-0fb7ae23d2d1?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fb7ae23d2d1</guid>
            <category><![CDATA[docker-swarm]]></category>
            <category><![CDATA[cloud-engineering]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 04:29:07 GMT</pubDate>
            <atom:updated>2024-12-30T22:56:51.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M2h7lZOo8LFOrP7L" /></figure><p>Educational purposes</p><p><strong>Docker Swarm</strong> and <strong>Kubernetes (K8s)</strong> are both <strong>container orchestration</strong> platforms, but they differ in their features, complexity, scalability, and use cases. Both allow you to manage and scale containerized applications, but they are designed with different goals and trade-offs in mind. Let’s dive into it!</p><h3>1. Overview:</h3><p><strong>Docker Swarm</strong>:</p><ul><li><strong>Docker Swarm</strong> is a native clustering and orchestration tool for Docker containers. It’s simpler and more integrated with Docker, making it easier to set up and use for smaller environments.</li><li>It’s ideal for small to medium-sized environments that need basic orchestration without the steep learning curve of Kubernetes.</li></ul><p><strong>Kubernetes (K8s)</strong>:</p><ul><li><strong>Kubernetes</strong> is a more complex and feature-rich container orchestration platform. It has a broader set of features and is designed for managing large-scale, distributed containerized applications across clusters of machines.</li><li>Kubernetes is more flexible and extensible, but it also has a steeper learning curve and more operational complexity.</li></ul><h3>2. Key Differences:</h3><h4>Ease of Setup and Use:</h4><p><strong>Docker Swarm</strong>:</p><ul><li><strong>Easier to Set Up</strong>: Docker Swarm is built into Docker, so setting it up is as simple as running a few commands to initialize a swarm and add worker nodes. It’s integrated with Docker’s CLI, making it easy for users who are familiar with Docker to get started with Swarm.</li><li><strong>Simpler Configuration</strong>: It uses the same Docker commands for managing clusters, and it requires fewer configuration steps.</li><li><strong>Less Overhead</strong>: Since Swarm is tightly coupled with Docker, it doesn’t require managing complex networking and configuration like Kubernetes.</li></ul><p><strong>Kubernetes</strong>:</p><ul><li><strong>More Complex</strong>: Kubernetes is more feature-rich, and setting it up can be complex. It involves configuring a control plane (master node), worker nodes, etc. You also have to manage networking, storage, and security separately.</li><li><strong>Steeper Learning Curve</strong>: Kubernetes introduces concepts like pods, deployments, services, and ingress controllers that can take time to learn.</li></ul><h4>Scalability:</h4><p><strong>Docker Swarm</strong>:</p><ul><li><strong>Moderate Scalability</strong>: Swarm is designed for relatively small to medium-sized environments. It works well for simple scaling, but it can become cumbersome when dealing with very large clusters or complex architectures.</li><li>It can manage a few hundred nodes effectively but may struggle with scaling beyond that in very large environments.</li></ul><p><strong>Kubernetes</strong>:</p><ul><li><strong>High Scalability</strong>: Kubernetes is designed for high scalability, managing large-scale applications with thousands of containers and nodes. It’s widely used in enterprise environments and can handle thousands of nodes, making it suitable for large, complex applications.</li></ul><h4>Features:</h4><p><strong>Docker Swarm</strong>:</p><ul><li><strong>Service Discovery and Load Balancing</strong>: Docker Swarm has built-in service discovery and load balancing. You can define services, and Swarm will automatically handle routing traffic to the right container.</li><li><strong>Rolling Updates</strong>: Swarm supports rolling updates for updating your services without downtime.</li><li><strong>Simple Networking</strong>: Docker Swarm simplifies networking between containers by using Docker’s built-in networking features.</li></ul><p><strong>Kubernetes</strong>:</p><ul><li><strong>Rich Feature Set</strong>: Kubernetes has a rich set of features beyond just container orchestration, including:</li><li><strong>Self-Healing</strong>: Kubernetes can automatically replace failed containers, reschedule them, and even manage high availability of services.</li><li><strong>Pod and Container Management</strong>: Kubernetes groups containers into “pods” for better management.</li><li><strong>Complex Networking</strong>: Kubernetes allows advanced networking configurations, including service discovery, ingress controllers, and network policies.</li><li><strong>Persistent Storage</strong>: Kubernetes supports persistent storage and volume management, which makes it great for stateful applications.</li><li><strong>Resource Management</strong>: Kubernetes offers better resource management, allowing you to define resource limits for CPU, memory, and storage.</li></ul><h4>Networking:</h4><p><strong>Docker Swarm</strong>:</p><ul><li><strong>Simpler Networking</strong>: Docker Swarm uses Docker’s networking features, which are simpler to configure and manage but may not be as feature-rich as Kubernetes’ networking.</li></ul><p><strong>Kubernetes</strong>:</p><ul><li><strong>Advanced Networking</strong>: Kubernetes has a powerful networking model, which can be complex but provides extensive flexibility, including the ability to define services, load balancers, ingress controllers, and network policies.</li></ul><h4>Ecosystem and Extensibility:</h4><p><strong>Docker Swarm</strong>:</p><ul><li><strong>Smaller Ecosystem</strong>: Docker Swarm has a smaller ecosystem compared to Kubernetes. It doesn’t have as many third-party tools, plugins, or integrations.</li><li><strong>Limited Extensibility</strong>: While Docker Swarm integrates with Docker Compose, it has fewer built-in features for extensibility.</li></ul><p><strong>Kubernetes</strong>:</p><ul><li><strong>Large Ecosystem</strong>: Kubernetes has a huge ecosystem with a wide range of integrations, tools, and services. It’s supported by major cloud providers, including Google Cloud, AWS, and Azure.</li><li><strong>Highly Extensible</strong>: Kubernetes has a flexible architecture that supports custom controllers, CRDs (Custom Resource Definitions), and operators for managing complex applications.</li></ul><h4>Community and Support:</h4><p><strong>Docker Swarm</strong>:</p><ul><li><strong>Smaller Community</strong>: While Docker Swarm has a dedicated community, it’s smaller compared to Kubernetes.</li><li><strong>Less Enterprise Adoption</strong>: Docker Swarm is not as widely adopted in large enterprise environments as Kubernetes.</li></ul><p><strong>Kubernetes</strong>:</p><ul><li><strong>Larger Community</strong>: Kubernetes has a massive and active community, and it’s backed by major tech companies (including Google, Microsoft, and Red Hat).</li><li><strong>Widespread Adoption</strong>: Kubernetes is the most widely adopted container orchestration tool in the enterprise space.</li></ul><h3>3. When to Use Docker Swarm:</h3><ul><li><strong>Smaller Environments</strong>: If you’re running a relatively simple application or need a small to medium-sized container orchestration solution, Docker Swarm might be sufficient.</li><li><strong>Simplicity</strong>: If you’re looking for an easy-to-set-up, integrated solution that works well with Docker, Swarm is a good option.</li><li><strong>Docker-native workflows</strong>: If you already use Docker and want a simpler orchestration tool that’s tightly integrated with Docker CLI and Docker Compose.</li></ul><h3>4. When to Use Kubernetes:</h3><ul><li><strong>Large-Scale Environments</strong>: Kubernetes is ideal for large, complex applications and distributed systems, where you need advanced orchestration, scaling, and resource management.</li><li><strong>Microservices</strong>: If you’re building microservices or multi-container applications that require complex networking, persistent storage, and scaling, Kubernetes is the better choice.</li><li><strong>Enterprise Environments</strong>: If you’re working in an enterprise environment with high demands on high availability, security, and scalability, Kubernetes is the industry standard.</li></ul><h3>Conclusion:</h3><ul><li><strong>Docker Swarm</strong> is a simpler, easier-to-use solution for smaller applications or teams looking for basic container orchestration with Docker.</li><li><strong>Kubernetes</strong> is a more powerful, flexible, and scalable solution, widely used in larger, more complex environments with many nodes and advanced features.</li></ul><p>If you’re just starting with container orchestration and want something simpler, <strong>Docker Swarm</strong> might be the way to go. If you’re working on a large-scale, production-level environment or microservices architecture, <strong>Kubernetes</strong> is the more suitable choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fb7ae23d2d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Development and Deployment]]></title>
            <link>https://medium.com/@jsantoine24/continuous-development-and-deployment-d08a3eda6f5c?source=rss-4b472d64fc0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d08a3eda6f5c</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[cloud-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[persistent-volume]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[Jeremy Smith]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 01:32:27 GMT</pubDate>
            <atom:updated>2024-11-11T01:32:27.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sPS5nuUjsYfjI9Zm.png" /></figure><p>with Docker &amp; Jenkins</p><p><strong>What is Jenkins?</strong></p><p>Jenkins is an open-source automation server used primarily for continuous integration (CI) and continuous delivery (CD) in software development. It helps developers automate the process of building, testing, and deploying applications, making it easier to integrate changes to projects and ensuring that the new code integrates smoothly with existing code-bases.</p><h4>Objective</h4><p>The main objective of this project is to use Docker for creating and managing Jenkins containers, emphasizing the implementation of persistent volumes. This strategy aims to build a robust, scalable Continuous Integration and Continuous Deployment (CI/CD) pipeline, facilitating frequent and reliable deployment of software updates.</p><h4>Pre-reqs</h4><ul><li><strong>Docker Installed and Running</strong></li><li><strong>EC2 Instance</strong> (OS of your choice eg. Ubuntu)</li><li><strong>Basic Docker and Jenkins Knowledge</strong></li><li><strong>SSH Host Configured in VS Code</strong></li></ul><h4>Step 1: Pull the Jenkins LTS Image from Docker Hub</h4><p>First things first, I opened my <strong>VS Code</strong> and connected to my <strong>SSH Host</strong>. Once connected and in a new terminal window, I ran the following command to pull the Jenkins LTS image:</p><pre>docker pull jenkins/jenkins:lts-jdk17<br><br>docker image ls #verify the image has been pulled</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHYl6IzOK08cZqUi3bfhbA.png" /><figcaption>Jenkins LTS Image successfully pulled.</figcaption></figure><p><strong><em>Next…</em></strong></p><h4>Step 2: Create a Docker Volume for Jenkins</h4><p>Next I created the <strong>volume</strong> for Jenkins that I want the data to be stored. Volumes are crucial in a containerized CI/CD setup because they <strong>persist</strong> important data like configurations, logs, and job history across container restarts. This ensures your CI/CD environment remains stable, recoverable, and consistent, making your pipeline reliable and efficient by maintaining data outside the container’s lifecycle. See the commands below:</p><pre>docker volume create jenkins_data<br><br>docker volume ls #verify the volume is created</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*7vjgnzczW_7miyS2cIJATg.png" /><figcaption>Volume for Jenkins.</figcaption></figure><p><strong><em>Next…</em></strong></p><h4>Step 3: Run the Jenkins Container with the Volume and Port Mapping</h4><p>Next up was to run a Jenkins container with the volume and necessary ports mapped out. See the commands below:</p><pre>docker run -d -p 8080:8080 -p 50000:50000 --name jenkins \<br>-v jenkins_data:/var/jenkins_home \<br>jenkins/jenkins:lts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_Z05IeHbc59W-vhHurIdQ.png" /><figcaption>Jenkins container created.</figcaption></figure><p>I also wanted to inspect the container’s configuration to verify it was mounted to the volume properly using:</p><pre>docker container inspect jenkins</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRXUMEjC2a7_KVNSwEX13A.png" /><figcaption>The container was mounted properly.</figcaption></figure><h4>Breakdown for the container creation command:</h4><p>This command runs a Jenkins container in the background, mapping necessary ports for web access and agent communication, using a named volume to persist data, and naming the container jenkins.</p><p>1.<strong>docker run</strong>:</p><ul><li>Runs a new container.</li></ul><p>2.<strong>-d</strong>:</p><ul><li>Runs the container in detached mode (in the background).</li></ul><p>3.<strong>-p 8080:8080</strong>:</p><ul><li>Maps port 8080 on the host machine to port 8080 on the container. This is used for accessing the Jenkins web interface.</li></ul><p>4.<strong>-p 50000:50000</strong>:</p><ul><li>Maps port 50000 on the host machine to port 50000 on the container. This port is used for Jenkins agent communication.</li></ul><p>5.<strong>--name jenkins</strong>:</p><ul><li>Names the container jenkins for easier reference.</li></ul><p>6.<strong>-v jenkins_data:/var/jenkins_home</strong>:</p><ul><li>Mounts the Docker volume jenkins_data to the /var/jenkins_home directory inside the container. This ensures that Jenkins data, such as job configurations and plugins, is persisted outside the container&#39;s lifecycle.</li></ul><p>7.<strong>jenkins/jenkins:lts</strong>:</p><ul><li>Specifies the image to use, in this case, the Jenkins LTS (Long-Term Support) version from Docker Hub.</li></ul><p><strong><em>Next…</em></strong></p><h4>Step 4: Retrieve the Admin Password</h4><p>To access Jenkins for the first time, you need the initial admin password. We first need to get into the terminal of the container in order to retrieve it. Run the following command to view it:</p><pre>docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXRrUqOsA23-wqVUITJVUQ.png" /><figcaption>Here is the admin passwd (ex. 46fga6f32tbr546231a879a61)</figcaption></figure><p>Copy the password from the output.</p><p><strong><em>Next…</em></strong></p><h4>Step 5: Login and Create a New User in Jenkins</h4><p>Once I copied the admin password I then went to my browser and entered into the url → <strong>localhost:8080</strong> to see the Jenkins login page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLtp0DOxRksR413oKYTkhQ.png" /><figcaption>Paste the admin password and click continue.</figcaption></figure><p>Next I selected “<strong>install suggested plugins</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYUsMltRykllGzhjaBLceA.png" /><figcaption>All of the plugins needed for Jenkins generic uses downloading.</figcaption></figure><p>Once that finished up…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VmKflEwAOZCbj5QVLhRkyw.png" /><figcaption>Jenkins dashboard</figcaption></figure><p>My account is setup and ready to be used for my CI/CD projects!</p><h4>Step 6: Verifying the volume data persists</h4><p>The last thing I did was created a <strong>new</strong> Jenkins container that will use the same volume and the previous container to verify that the data persisted even with a new container. See the following commands:</p><pre>docker run -d -p 8081:8080 -p 50001:50000 --name jenkins2 \<br>-v jenkins_data:/var/jenkins_home \<br>jenkins/jenkins:lts</pre><p>I used the same command from before but with some slight changes. I named the new container “jenkins2” and I had to tweak the ports a little bit as well to avoid an error. I used <strong>8081:8080 </strong>for my local host and <strong>50001:50000 </strong>for the Jenkins master and slave nodes. This was done to differentiate the containers so Docker would know this was a different container using the same volume. Because in Docker or rather <strong>networking</strong> you cannot use the same ports that an <strong>already existing container</strong> is currently using in that same network (<strong>bridge network</strong> = default network).</p><p>I then verified that both containers were mounted to the same volume with the following command:</p><pre>docker ps --filter volume=jenkins_data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sf_mnqUrx1xlzoijMyaKHw.png" /><figcaption>success</figcaption></figure><p>This command will list out ALL containers that are using a specified volume. You could even inspect the jenkins2 container and check the mounts as well. But this way is more efficient especially when dealing with a plethora of containers.</p><p>And lastly, you could even delete both containers to verify if the volume persists (which it should) and be able to create a brand new container using the same volume and the results should be the same. See you next time!</p><p>Documentation → <a href="https://www.jenkins.io/doc/">https://www.jenkins.io/doc/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*qBRuWVJ4U0X_1hAtCgZQXA.png" /></figure><p>Let’s connect! <a href="https://www.linkedin.com/in/jeremy-smith-o3/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d08a3eda6f5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>