<?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 K Slaughter on Medium]]></title>
        <description><![CDATA[Stories by K Slaughter on Medium]]></description>
        <link>https://medium.com/@slaughterkn?source=rss-4359486445b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VdJscxXrOCyxm2SWMQ4cQg.jpeg</url>
            <title>Stories by K Slaughter on Medium</title>
            <link>https://medium.com/@slaughterkn?source=rss-4359486445b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:29:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@slaughterkn/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[Code, Tweet, and Repeat: Using Python and GPT to Automate Tweets]]></title>
            <link>https://blog.stackademic.com/code-tweet-and-repeat-using-python-and-gpt-to-automate-tweets-4a3373232b1c?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a3373232b1c</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[twitter]]></category>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 22:15:13 GMT</pubDate>
            <atom:updated>2024-04-29T00:36:17.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*VVy4FEtElnBgFP2aiyu03g.png" /><figcaption>Don’t feel like reading? <a href="https://github.com/andotis0105/TweetCraft">Go straight to the TweetCraft Github repository</a>!</figcaption></figure><h3>Learning is Fun</h3><p>Lately, I’ve been diving into <strong>LinkedIn Learning</strong>’s vast resource library. Despite having some prior experience with <strong>OpenAI’s APIs</strong>, I decided to further my skills by taking <strong>Kesha Williams</strong>’ course, “<a href="https://www.linkedin.com/learning/openai-api-code-interpreter-and-advanced-data-analysis">OpenAI API: Code Interpreter and Advanced Data Analysis</a>.” Kesha is <strong><em>fantastic</em></strong> at simplifying complex concepts in an approachable manner, which, along with her enthusiasm, really impressed me.</p><p>Ready to explore more, I promptly moved along to her “<a href="https://www.linkedin.com/learning/building-a-project-with-the-chatgpt-api/">Building a Project with the ChatGPT API</a>” course. It was engaging and informative, and I had a lot of fun experimenting with the code provided in the course files.</p><p>However, after completing the course and looking over my completed project, I felt like something was missing. The dialogue-based interaction didn’t <em>quite</em> suit my taste, and I also wanted to add functionality to include a link to the original URL in my tweets. Inspired to tweak the project further, I revisited the code. While my modifications are heavily inspired by Kesha’s teachings, I customised the script to better fit my vision, enhancing its functionality and simplifying user interaction.</p><p>You can check it out over at the <a href="https://github.com/andotis0105/TweetCraft">TweetCraft Github repository</a>, or keep reading for a step-by-step breakdown of the python script and to see two examples of in-use screenshots and the resulting tweets!</p><h3>Breakdown of the Python Script</h3><ol><li><strong>Imports Libraries:</strong> Starts by importing necessary Python libraries for working with OpenAI, handling files, making web requests, and interacting with Twitter.</li><li><strong>Loads Environment Variables:</strong> Reads an .env file to securely get the OpenAI API key for authentication.</li><li><strong>Initializes the OpenAI Client:</strong> Sets up a connection to OpenAI using the retrieved API key.</li><li><strong>Collects User Input:</strong> Prompts the user to input a URL for processing.</li><li><strong>Generates Text Summary:</strong> Uses GPT to create a short, tweet-friendly summary of the content at the provided URL.</li><li><strong>Creates Image Prompt: </strong>Based on the text summary, GPT crafts a prompt to generate an image that complements the tweet.</li><li><strong>Generates and Downloads Image:</strong> Uses DALL-E to create an image from the prompt and saves the generated image to the local system.</li><li><strong>Authenticates with Twitter:</strong> Logs into Twitter using provided credentials.</li><li><strong>Uploads Image to Twitter: </strong>Sends the image to twitter for inclusion in a tweet.</li><li><strong>Posts Tweet: </strong>Sends out a tweet with the <strong>text summary</strong>, the <strong>URL</strong>, and the <strong>image</strong>.</li></ol><h3>Two Examples (Using the Same URL)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhsEGB_ioVRgRl6IVy_60A.png" /><figcaption>I need to work on the prompt for the image-prompt-writing GPT call, because I will occasionally get weird ones like this that aren’t quite an actual image description.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*_j0Y5PTMq-nzI6azC4CxXQ.png" /><figcaption>Doesn’t really make any sense, but looks cool as hell.</figcaption></figure><h4>and</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDekChPkSjKa7GjhGxvg9g.png" /><figcaption>I changed up the prompt within the code a little bit — this result is a better visual description than before.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*qeULod3SEEkPij4z577-_w.png" /><figcaption>NICE GOING, DALL-E!</figcaption></figure><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a3373232b1c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/code-tweet-and-repeat-using-python-and-gpt-to-automate-tweets-4a3373232b1c">Code, Tweet, and Repeat: Using Python and GPT to Automate Tweets</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting into Orbit: Launching Jupyter Notebook On an AWS EC2 Instance]]></title>
            <link>https://aws.plainenglish.io/getting-into-orbit-launching-jupyter-notebook-on-an-aws-ec2-instance-53ca3c68cf52?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ca3c68cf52</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 22:04:12 GMT</pubDate>
            <atom:updated>2024-04-26T04:20:55.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*2EscUHv82w02cW9i9J2Cxw.png" /></figure><h3>Let me cut right to it:</h3><p>Recently, I’ve been using Jupyter Lab on my PC, but also wanted a solution I could easily access from my Chromebook.</p><p>So today, we’re here to explore how to set up Jupyter Notebook on an AWS EC2 instance. This guide walks through each step from launching your instance, configuring your security group, to accessing Jupiter Lab via your browser.</p><h4>Launch Your Instance</h4><p>For this demo, I’m staying simple with a t2.micro instance type using the Amazon Linux 2023 AMI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*EBhHQsHWBLiuDn5TMGJ-GQ.png" /><figcaption>Depending on how much you plan to actually use Jupyter, you may want to choose a larger instance type. For example, I’ve found that the t2.medium is the best size for my own personal Jupyter Lab usage.</figcaption></figure><h4>Configure the Security Group</h4><p>There’s several different ways you can configure your settings here, depending on your own security preferences.</p><p>Whether you’re connecting through your own SSH client or straight from Instance Connect, you need port 22 open for SSH traffic, and by default, Jupyter uses port 8888 (or choose another).</p><p>Since I’m using Instance Connect for this demo, I have two options. I can allow all traffic (0.0.0.0/0) on port 22, but that’s not secure. The other option is to specify the CIDR range AWS uses for Instance Connect in your region — in my case, us-east-1’s range 18.206.107.24/29.</p><p>For more information, check out the <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-prerequisites.html#ec2-instance-connect-setup-security-group">Security Group section of the Instance Connect Prerequisites</a>, and <a href="https://github.com/joetek/aws-ip-ranges-json/blob/master/ip-ranges-ec2-instance-connect.json">this is a stripped-down list of Instance Connect IP ranges by region</a>*.</p><p>For accessing Jupyter on port 8888, I am using my own IP address. You <em>could</em> set this as 0.0.0.0/0, too, but then quite literally anyone could access your running Jupyter server.</p><p><em>* This information can also be found in the full </em><a href="https://ip-ranges.amazonaws.com/ip-ranges.json"><em>AWS IP Ranges JSON file</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CMgO8EaUkvvDx3otOTm0w.jpeg" /><figcaption><strong>A small note here about portability and access:</strong> If I want to connect to Jupyter from another computer’s browser, I just need to go into the security group rules and change My IP address to the computer I’m currently using, or use the much less secure 0.0.0.0/0 option.</figcaption></figure><h4>Connect Through EC2 Instance Connect</h4><p>Once you’re all set with your security group rules and have your instance up and running, click Connect from the Instance summary screen, and make sure you choose EC2 Instance Connect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*Y08U_j__vXhUNWgzntRHSw.png" /></figure><p>After clicking Connect here, a new browser tab is launched, and after a few seconds, you should be connected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*I9cGhgIlIvGXMegjtXUIoA.png" /></figure><h3>It’s Notebook Time!</h3><p>Once you’re in, it’s good to check whether python and pip are already installed, and if so, what versions you’ve got. Running python --version or python3 --version, and pip --version or pip3 --version will show that information. (If you’re like me and hate having to remember to use the “3” in python/pip, just alias the commands — alias pip3=pip and alias python3=python.)</p><p>If you’re missing something, sudo yum install python3 and sudo yum install python3-pip will get it done for you (This is if you’re using the Amazon Linux distro. For Ubuntu, use apt install instead.)</p><p>Before moving on, run pip install notebook to first install the classic Jupyter Notebooks.</p><h4>Set Up Your Environment</h4><p>You’re going to be running your Jupyter server in a Python virtual environment — python3 -m venv your_notebook_name sets it up, and source your_notebook_name/bin/activate gets it going.</p><p>Next, run pip install jupyter lab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*P46dVvWwMiu9Gmc3p1RW9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UK1RcQLg7TE7ZWt5o02Vg.png" /><figcaption>If you get the pip version warning in this screenshot, you don’t necessarily <em>HAVE TO </em>run the upgrade command, but I just go ahead and do it anyway, because why not?</figcaption></figure><h4>Last Step — LET’S GOOOOO JUPYTER!</h4><p>Are you ready? Because you’re almost there.</p><p>Simply run jupyter lab --ip 0.0.0.0 to start up your Jupyter Server!</p><p>You should see something close to what’s shown in the screenshot below. There’s a couple spots to see it, but that long string of letters and numbers after token= is going to be your access token:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kM0bIpF3TnyberBwaIvo-w.png" /></figure><p>If you haven’t already grabbed the public IP address of your instance, do that now, either from the bottom of the EC2 Connect window, or from the Instance summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*wTrO_LQGn8d6_cpNG8bN1Q.png" /><figcaption>I don’t like clicking the “open address” link because it automatically will try to use HTTPS, which doesn’t work (use HTTP instead), and that’s one of those little things in life that I find wildly annoying.</figcaption></figure><p>Take that public IP address (in my example, 3.95.205.249), open up a new browser window, and put in http://your.public.ip.address:8888/lab to get to the Jupyter Server’s login screen. Where it says “Password or token”, paste in that long string of letters and numbers from the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-LpNU4PNbbKmfAmZOaxbg.png" /></figure><p>Upon clicking “Log in”, you will be taken to your Jupyter Lab server and can open a new Notebook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nblM3k_HJVTlElwIfdjNg.png" /></figure><p>And there you have it — relatively easy and painless.</p><h3>A Couple Final Notes:</h3><ul><li>DON’T CLOSE YOUR INSTANCE CONNECT BROWSER WINDOW! <br>This will shut your Jupyter server down.</li><li>Although Jupyter Notebook DOES have an autosave feature that saves every 120 seconds by default, don’t put your blind trust in that. Make sure you’re manually saving your work.</li><li>You can shut the server down from the File menu in Jupyter Lab itself, as well as from your EC2 Instance Connect Console. Or just close those browser windows and shut down your EC2 Instance — you do you.</li><li>When you want to restart the server, get back into the EC2 Instance Connect and run jupyter lab --ip 0.0.0.0 again. You’ll once again need your EC2 Instance’s public IP address (which will have changed if you have shut down and restarted the instance, unless you spring for an Elastic/static IP), go to http://your.public.ip.address:8888/lab, and copy/paste in your new access token.</li></ul><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ca3c68cf52" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/getting-into-orbit-launching-jupyter-notebook-on-an-aws-ec2-instance-53ca3c68cf52">Getting into Orbit: Launching Jupyter Notebook On an AWS EC2 Instance</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In AWS, Infrastructure is Born: Talking of Terraform]]></title>
            <link>https://medium.com/@slaughterkn/in-aws-infrastructure-is-born-talking-of-terraform-109c8e701dc9?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/109c8e701dc9</guid>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 21:37:03 GMT</pubDate>
            <atom:updated>2023-12-30T21:45:10.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yU0Ti-_jhTYUBUpFtFHZ4Q.png" /></figure><h3>I’ll be honest here —</h3><p>I haven’t been working with <strong>Terraform</strong> long. At this point, it’s probably been a month at most. But OH MY GOD…<strong>Terraform is freakin’ TERRIFIC</strong>. I love the <strong>organisation </strong>and <strong>versatility </strong>that Terraform brings to the table. I feel like I’ve discovered alchemy or something.</p><p>But okay. Real talk now. There are quite a few very beneficial things about using Terraform. First off, we’re talking <strong>IaC </strong>(Infrastructure as Code) — provisioning and managing infrastructure resources through definition files (rather than through the AWS console, for example). This allows for greater consistency, reproducibility, collaboration, and faster development.</p><p>What stands out the most to me, though, is the absolute wealth of documentation and resources HashiCorp has for writing Terraform configurations. Check out some of the <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">AWS documentation here on the Terraform Registry</a>.</p><p>Look, I could write about how cool Terraform is all night, but no one wants to read that. Time to get to work.</p><p>This article is a simple run-through of using<strong> Terraform to deploy some infrastructure in AWS</strong>: an <strong>EC2 instance</strong> bootstrapped with <strong>Jenkins</strong>, a <strong>security group</strong>, and an <strong>S3 bucket</strong>!</p><h3>Let’s Look at the Configuration</h3><p>The first thing I want to do is to quickly delve into my configuration file itself — it can be found within the repo <a href="https://github.com/andotis0105/terraform_jenkins_aws"><strong>here on GitHub</strong></a>.</p><p>Because I’m writing this as a purely beginner exercise, my whole <strong>configuration</strong> is within a single <strong>main.tf</strong>, not separated out into self-contained <strong>modules</strong>, and all information is hard-coded into the configuration itself. Please note that <strong>doing this in any kind of real-world development or production environment is an absolutely terrible idea</strong>, but I’m doing it for the sake of simplicity and clarity here.</p><h4>The Required Providers Block</h4><p>Every Terraform module needs to declare which providers it requires so that Terraform will know what plugins need to be installed. For this project, I’m just using AWS, and I’ve specified anything version 5.0 and up. (At the time of writing this, the current latest version is 5.31.0)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*FBmveIiapdFkrH1RPdG7Ew.png" /></figure><h4>Configuring AWS</h4><p>Next, within a <strong>provider block</strong>, I set up some information for AWS — setting my region as us-east-1, and also providing some credentials via an access key and secret access key*.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*9MCXg3GIr20Y69F_40tn3g.png" /><figcaption>*Don’t freak out — those credentials are fake.</figcaption></figure><p>I mentioned this above, but I’ll mention it again because it’s <strong>really important</strong>. Don’t actually hard-code credentials like these into a configuration file in any real-world scenario. I do this simply for demonstration purposes.</p><h4>Resource #1 — Security Group</h4><p>My first <strong>resource block </strong>is for a new <strong>security group</strong>. I have specified my desired VPC, as well as two custom ingress rules: SSH (tcp 22) from my IP address (blocked out), and the default Jenkins port (tcp 8080) from anywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*kCtzEPQxABkEiTpDzLWs2w.png" /></figure><h4>Data Block — User Data for The EC2 Instance</h4><p>Next up is a <strong>data block </strong>that points to the separate bash script file that will bootstrap install and start Jenkins when the EC2 instance is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*UPNvueJewma0enKwSQbEzw.png" /></figure><p>This is what the bash script actually looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*ANrLqiW0eR6igDZZrTByww.png" /></figure><h4>Resource #2 — EC2 Instance</h4><p>My second resource block is an <strong>EC2 instance</strong>. I feel like most of the details here are self-explanatory (AMI, instance type, keypair, etc), but I do want to point out that the vpc_security_group_ids will get the ID of my newly created security group from above, and user_data references back to the data block and bash script template file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*i1HFfAn6Rt62pSv0bMBEdA.png" /></figure><h4>Resource #3, #4, #5 — S3 Bucket / Ownership Controls / Private ACL</h4><p>I’m covering the last three resource blocks together, since they all deal with the <strong>S3 bucket</strong>. The first block is the bucket itself. That’s super straight-forward, as the only required parameter is the actual name of the bucket.</p><p>The next is the <strong>ownership controls</strong> — here, I have a “depends_on” parameter that refers to the bucket I’m creating.</p><p>Lastly, I have the bucket’s <strong>ACL</strong>. I have another “depends_on” parameter here that references the bucket’s ownership controls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*zumflm8Ik6GH9ljJHeqiyA.png" /></figure><h4>Output Block — EC2 Instance’s Public IP Address</h4><p>To wrap up my configuration file, I have a handy <strong>output block</strong>. Upon applying / deploying the configuration, Terraform will tell me the public IP address that was assigned to the EC2 instance I created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*onTC8e39iKV9QizHHohQUw.png" /></figure><h3>Alright! Deploy the Configuration!</h3><p>Enough of just looking at this configuration file — time to make it a reality! (It’s still real if it’s in the cloud, right?)</p><p>First, just showing that I’m inside the directory with both my <strong>main.tf</strong> and <strong>user_data.sh</strong> files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*GtdOLkWDsOMJV1kRvBa9EA.png" /></figure><p>To initialise the directory, I run a simple terraform init. This starts Terraform’s process of setting up the backend, installing provider plugins, etc:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*v3rXShqKkgKXSMOqEyERFg.png" /></figure><p>Next, I run a quick terraform validate to make sure my configuration syntax is good:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*3wpFpCJbdDKO59ZPG4qtrQ.png" /></figure><p>To check out what Terraform will do when I apply my configuration, I decided to do a terraform plan first. This produces a whole crap-ton of information about the intricacies of my configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TlY5SKUDGjL5EopB02tQ_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*Ow_tApJc9hYV2-uOC5XVpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHSsWAJfSEVmiXyTrO36LA.png" /></figure><p>Because those screenshots above are just brutal to look at, here’s a much closer look at the final snippet there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*HUQsTXmZhMlyWJd35jZdSw.png" /><figcaption>I had 5 resource blocks, Terraform will add 5 things.</figcaption></figure><p>All that’s left to do now is deploy my configuration using terraform apply. I didn’t include the initial screenshots, because they basically look just like the “plan” phase above — the difference comes here when I’m asked whether I want to perform the actions of the plan, to which I type “yes”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9Rs4cBTDoj4MLvuzqswvw.png" /></figure><p>So I can watch as Terraform goes through and creates my resources.</p><p>And at the very end, under “Outputs”, it gives me the public IP address of the instance it just created!</p><p>Honestly, is this not kind of amazing? Less than 45 seconds and <em>*poof!* </em>it’s all there?? It’s alchemy, I tell you.</p><p>Now that it’s up and running, let’s talk <strong>Jenkins</strong>.</p><h3>Setting Up Jenkins</h3><p>I’ve actually already covered the initial Jenkins installation and setup before in my <a href="https://medium.com/@slaughterkn/stand-by-me-persistent-data-with-docker-volumes-61e7b08d28da">previous article about persistent volumes in Docker</a>, but I figured I’d go through it again here as well.</p><h4>Get the Jenkins Admin Password</h4><p>When first installed and started, Jenkins does a handy little thing where it creates an admin password.</p><p>I simply used VS Code to SSH into my new instance and retrieve the password. (See this <a href="https://code.visualstudio.com/blogs/2019/07/25/remote-ssh#_connect-using-remote-ssh">Visual Studio Code blog page for instructions on setting up a remote connection via SSH</a>)</p><p>In the screenshot below, I show the process of moving to the Jenkins directory, making sure everything is there, and then retrieving the password. However, if you’d like to save yourself about 10–15 seconds, simply running cat /var/lib/jenkins/secrets/initialAdminPassword would work as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGuG_dl5tQSmaECac9acvw.png" /></figure><p>I can copy that password, paste it into the little box, and click “continue”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*la12uFhBXSB7-K-SJs6Okg.png" /></figure><p>From there I’m taken to the plugin installation page(s):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*rD4JfseG3rMK__nv0eNUvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEQ9aCP8r3vFzRtEoYjdWQ.png" /></figure><p>Once that’s finished, I can either create a first Amin User, or skip through and continue (which is what I did), and the next page is to specify the URL configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwpgFQGsw89dYbvIJcK2nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xP1W3Ue8_GKYssKtut8tUQ.png" /></figure><p>Once I click “Save and Finish”, my Jenkins setup is complete! All I have left to do is click “Start using Jenkins”, and I’m taken to the Jenkins dashboard page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6YopYYmBV88JuMnCZiXqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEq8j1XSnEY1q4nJGb7dUQ.png" /></figure><p>And my initial setup is complete!</p><p>If you’ve read this far, I feel compelled to tell you that this article’s title is a play off of the lines in <a href="https://www.poetryfoundation.org/poetrymagazine/poems/44212/the-love-song-of-j-alfred-prufrock">T.S. Eliot’s <em>The Love Song of J. Alfred Prufrock</em></a><em> — </em>“In the room the women come and go / Talking of Michelangelo.”</p><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=109c8e701dc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Delicious Duo Deployed in Docker: MySQL and WordPress with Docker Swarm]]></title>
            <link>https://medium.com/@slaughterkn/a-delicious-duo-deployed-in-docker-mysql-and-wordpress-with-docker-swarm-83c8c63a98ab?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/83c8c63a98ab</guid>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 20:57:14 GMT</pubDate>
            <atom:updated>2023-12-27T20:57:14.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*pkOUrYjfISeydUTQW8IPIA.png" /></figure><p>I often eat while in the process of working on these projects or writing about them, and today, I’m on my second <a href="https://www.smuckersuncrustables.com/">Uncrustables </a>peanut butter and (grape) jelly sandwich.</p><p>In the wide, wide world of web development, <strong>WordPress</strong> and <strong>MySQL</strong> are like a digital peanut butter and jelly sandwich. I like to think of WordPress as the metaphorical peanut butter in this equation: smoooooth, reliable, and incredibly versatile — it’s a simple foundation to add up layers of content, fancy things up with themes, and maybe even include some plugins for extra flair (this would be the equivalent of cutting the crust off <em>and </em>cutting the sandwich diagonally).</p><p>Then there’s MySQL, the jelly component to the WordPress peanut butter — an essential counterpart that keeps all of the data neatly sandwiched together.</p><p>Working together, WordPress and MySQL are a delicious digital duo akin to the classic PB&amp;J sandwich (or Uncrustable) that’s perfect for almost any occasion. And today, this article is all about deploying them through Docker.</p><p>I’ll be demonstrating two ways to accomplish this — first in Docker Swarm, by using the CLI, and then by deploying a Docker stack file.</p><h3>Initial 3-Node Swarm Setup</h3><p>For an in-depth tutorial on creating a Docker Swarm environment, check out my previous article<a href="https://medium.com/@slaughterkn/setting-up-a-3-node-docker-swarm-7dacd6a64847"> Setting Up a 3-Node Docker Swarm</a>.</p><p>For this article, I am simply starting by connecting my three already-running instances using docker swarm init in my manager node, and running docker swarm join --token commands in the two desired worker nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAs8QM-N_aCywex4z62Rtg.png" /></figure><h3>Method I: From the CLI</h3><h4>Networks</h4><p>Once I have my swarm up and running, my first step here is to create my two networks with docker network create --driver overlay, along with the desired network names (<em>frontend </em>and <em>backend</em>).</p><p>I’m using the --driver overlay option, which is a distributed network, meaning it can communicate across multiple Docker hosts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*RnyV99TmfdmfV2DZ7_XXAQ.png" /></figure><h4>MySQL Database Backend</h4><p>Next, I need to create my MySQL database, as this needs to already exist <em>before</em> the WordPress frontend. The full command is:</p><p>sudo docker service create --name mysql --network backend --mount type=volume,sourcce=mysql_data,destination=var/lib/mysql -e MYSQL_ROOT_PASSWORD=&lt;password&gt; -e MYSQL_DATABASE=wordpress mysql</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*wJinzw0XkcRSGxrsvOBhJw.png" /></figure><h4>WordPress Frontend</h4><p>Now, when creating the WordPress frontend, I need to also pass in those same MySQL credentials:</p><p>sudo docker service create --name wordpress --network frontend -p 80:80 --replicas 3 -e WORDPRESS_DB_HOST=mysql WORDPRESS_DB_USER=root -e WORDPRESS_DB_PASSWORD=&lt;password&gt; -e WORDPRESS_DB_NAME=name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*uK5-YLVKlE1O19pebMZnBQ.png" /></figure><p>And when I run a docker service ls , my single MySQL and three WordPress replicas are shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*GmK_mr0cPK1wap2nlK3t-g.png" /></figure><h3>Setting Up WordPress</h3><p>Now that I’ve got my services’ containers running, all that’s left is to finish up the WordPress setup and installation. I pop in the IP address in an incognito window and get to work choosing my language preference and filling in the information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*T01Sa5Lq0Xf__5QlbDWPOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*LrbmdbyzX1Tiq39ZbpWAzw.png" /></figure><p>After clicking “Install WordPress”, it does its magic and brings me to the installation confirmation page, where I can log in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*zmwnsPTga23RJbR9TrVzhg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*WzIwGl0tdvXFJVxv9TJPUA.png" /><figcaption>WordPress’s installation success screen (left) and login screen (right).</figcaption></figure><p>And with that, I’m taken to the WordPress dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gWrA9XJqWt5Jhvuf_02UjA.png" /></figure><p>Awesome! Method I down, Method II coming up next!</p><h3>Method II: Docker Stacks</h3><p>(TL;DR <a href="https://github.com/andotis0105/docker-swarm-wordpress-stack/blob/main/wordpress.yml">here’s a link to the stack file</a>)</p><p>So, first, let me start this section out by saying that I <em>really</em> enjoy working with Docker Compose and Docker Stack files. It’s not that I mind working with the Docker CLI, but I feel like commands sometimes just feel clunky or too long-winded.</p><p>Compose or Stack files, on the other hand, fill my need for organisation and structure.</p><p>This time, I wanted to make things a bit more secure, so I am employing Docker Secrets here. These are actually pretty easy to create and use by running echo &quot;yoursecret&quot; | docker secret create your_secret_name -, like I did for my two password secrets below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umzjOiu5yqK-dEOBTaIbNA.png" /><figcaption>Docker stores my secrets someplace secret.</figcaption></figure><p>Now, for the stack configuration, I have included all of those same components from the CLI, just in a much neater, organised package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sE0xE8GS1hJRduOm4ddBTA.png" /><figcaption>Both services (MySQL and WordPress) defined along with their respective options and variables.</figcaption></figure><p>Note here that instead of hardcoding those passwords in, I’m using Docker Secrets, so I need to instead indicate the file containing that secret. (ie — MYSQL_ROOT_PASSWORD_FILE /run/secrets/mysql_root_password instead)</p><p>You can check out the full stack file <a href="https://github.com/andotis0105/docker-swarm-wordpress-stack/blob/main/wordpress.yml">here on Github</a>.</p><p>To deploy this stack, all I have to do is run sudo docker stack deploy --compose-file yourfilename.yml your_stack_name, like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWfsX3FwjsmLxhUvwi0LEg.png" /><figcaption>Docker deploys the stack and shows all of my components being created.</figcaption></figure><p>Once that’s finished up, I can open the IP address, and I’m at the same WordPress setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*KM1RMhvWiWFPzRcIOoToQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*KTWU7RegQcKOavUC3_GvFA.png" /><figcaption>Initial setup for installation.</figcaption></figure><p>This is the same process as before, but I just wanted to show that it worked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*pGeSTAMoVo4zlxrAPrmTMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*v_6WYbQE06stjB-jIM9p8w.png" /><figcaption>Successful installation and login.</figcaption></figure><p>And, once again, the WordPress landing dashboard!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*-EhBdnOljnNMHBf0PuWrvw.png" /></figure><p>So that’s the deal.</p><p>That’s my peanut butter and jelly sandwich.</p><p>And it was <strong>absolutely delicious</strong>.</p><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83c8c63a98ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Three-Tier Architecture Model in AWS!]]></title>
            <link>https://medium.com/@slaughterkn/building-a-three-tier-architecture-model-in-aws-d874895b20fc?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d874895b20fc</guid>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 21:37:18 GMT</pubDate>
            <atom:updated>2023-12-21T21:37:18.245Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I’m implementing a <strong>Three-Tier Architecture model </strong>using AWS’s <strong>VPC</strong> and <strong>EC2</strong> services.</p><p>The goal of this article’s journey* is creating a secure, scalable environment in AWS: working through setting up a new <strong>Virtual Private Cloud </strong>(VPC), as well as a front-facing web tier (with an <strong>autoscaling group</strong>), an application tier (in a <strong>private subnet</strong>), and finally, a <strong>database tier </strong>to tie the infrastructure together.</p><p>* <em>Yes, it’s a journey. Why? Because I said so.</em></p><h3>Services and Programs Used</h3><ul><li>AWS VPC</li><li>EC2</li></ul><h3>The VPC</h3><p>I have a VPC located in the US-East-1 region with:</p><ul><li>Two <strong>public subnets</strong> (one in us-east-1a AZ, the other in us-east-1f AZ), associated with a <strong>route table</strong> and<strong> internet gateway</strong>.</li><li>Four <strong>private subnets </strong>(one in us-east-a/b/e/f AZs), associated with two <strong>private route tables. </strong>One table (us-east-a/f AZs) routes to a<strong> NAT Gateway </strong>(located in my public subnet in us-east-1a) with an <strong>elastic IP address</strong>. The other is a mysql-3-tier</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRfeiIgodIMbLIqMmAZcIg.png" /></figure><h3>The Web Tier</h3><p>I’m going to be breaking this down tier-by-tier, starting with the web tier (hypothetical website).</p><p>In EC2, I set up an Autoscaling Group for the front-facing website, using a launch template I made from a custom AMI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXYLgcn6q5WHolEVMDD4lg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCRTCCenUhdB0EiCc5CDBA.png" /></figure><p>And just to test that my site works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*JY1sfubn3I-Q2kpe8rMSbw.png" /></figure><h3>The App Tier</h3><p>Next up is the “app tier” — I set up another ASG (generic Linux 2023 AMI launch template) for my application instances, which will be in two of the private subnets. The security group used in this template only has permissions for traffic from my original web server security group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OGXk5DFLNET2S5ohGTzJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyRh_er4fY3rhgCxAtzd4g.png" /></figure><h4>Testing Them Out</h4><p>Using AWS’s Instance Connect, I can hop into my bastion host instance and see if I can reach an app tier instance over in its secluded private subnet.</p><p>My goal is to SSH into one of these private instances, so I ran nano private-sub-kp.pem and copy/pasted it in. The absolute pinnacle of security, I know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*-o49IQ4AqkpZqbnYR43l5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*1wr93W6rmGsph4YS8HX_SQ.png" /></figure><p>From here, I want to use my bastion host to try to SSH into one of my private app-tier instances:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*E12TYlT3w4OX_yC4p-YUpw.png" /></figure><p>On to the next step!</p><h3>Database Tier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*2QySpC2c9gXOTtniMkD_Xg.png" /></figure><h4>Connecting to the Database</h4><p>Back in my bastion host, I already have the MySQL CLI installed (by running sudo dnf mariadb105 -y), so I just need to take that endpoint from RDS and run mysql -h [RDS endpoint] -P 3306 -u admin -p, and enter my password at the prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*mM4_JQF3nREHYkYqCOLdug.png" /><figcaption>Note: Although identical, this is actually a different instance from the first bastion host I used because I accidentally terminated the original one instead of just stopping it.</figcaption></figure><p>And there we go! Connected to the database!</p><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d874895b20fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up a 3-Node Docker Swarm]]></title>
            <link>https://medium.com/@slaughterkn/setting-up-a-3-node-docker-swarm-7dacd6a64847?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dacd6a64847</guid>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 00:46:13 GMT</pubDate>
            <atom:updated>2023-12-01T00:46:13.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*NOzkFRL0A1gfmpIuiKiL2w.png" /></figure><p>In the world of container orchestration, Docker Swarm is an essential tool when it comes to efficiency, scalability, and reliability in application development.</p><p>Swarm is a clustering tool for Docker containers that makes managing multiple containers across multiple machines a streamlined process, especially for complex applications. This is crucial for applications that demand high availability, and makes handling scaling and failover processes easily manageable.</p><p>This guide illustrates the setup of a simple 3-node Docker Swarm.</p><h3>1. Pre-Setup</h3><h4>On Local Computer: Install Visual Studio Code</h4><p>- <a href="https://code.visualstudio.com/Download">Download and Install Visual Studio Code</a><br>- Install Remote-SSH Extension</p><p>For more information:<br>- <a href="https://code.visualstudio.com/docs/setup/setup-overview">Setting up Visual Studio Code</a><br>- <a href="https://code.visualstudio.com/blogs/2019/07/25/remote-ssh">Remote Development using SSH</a></p><h4>In AWS: Create a New Security Group</h4><p>- Allow all traffic from your IP address.</p><p>- Allow all traffic from the VPC’s CIDR — this can be found in AWS under the information for your desired VPC. Look for “IPv4 CIDR”.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NYVkickduTnazZHGqw4lA.png" /></figure><h4>Recommended (But Not Necessary): Allocate a new elastic IP address.</h4><h3>2. Launch Instances</h3><h4>Instance Configuration Requirements</h4><p>- Ubuntu 22.04 AMI<br>- t2.micro<br>- Assign security group created in step 1. <br>- Create a new (or use existing) keypair.<br>- Copy/paste the <strong>User Data Bash Script</strong> code below into the “user data” under the advanced settings.</p><h4>User Data Bash Script</h4><pre>#!/bin/bash<br><br># Update and Upgrade Ubuntu<br>sudo apt-get update -y<br>sudo apt-get upgrade -y<br><br># Install Docker (from the official Docker convenience script)<br>curl -fsSL https://get.docker.com -o install-docker.sh<br>sh install-docker.sh</pre><p>On the right-side panel, change the number of instances to 3 (as seen in the screenshot below), and launch the instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*uVN2-PJ5YquteHnTZmM4yg.png" /></figure><h4>Recommended: Change Instance Names in the AWS Dashboard</h4><ul><li>One instance labelled as <strong>manager</strong> node, with the other two labelled as <strong>worker</strong> nodes (example screenshot below).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*etJkBBwcQIUBG7sdxlrG-A.png" /></figure><ul><li>If you allocated an elastic IP address, attach it to your manager node now.</li><li>You may want to go ahead and make note of the <strong>PRIVATE </strong>IP addresses of the two worker nodes. You will need these in future steps.</li></ul><h4>Set up SSH and Connect to Manager in VS Code</h4><p>Make sure the Remote-SSH extension has been added, then connect to your manager instance.</p><h3>3. SSHing into the Instances</h3><p>Upon first SSH-ing into the manager instance in VS Code, check to make sure Docker is installed with docker --version.</p><p>Next, runsudo hostnamectl set-hostname manager-node to give it a more easily understood name. Then,reboot for the change to take effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*5Ot5AaIu-9K2OE_cwo4ZOQ.png" /></figure><p>Once the manager node reboots, run cd /root/.ssh (you may need to use sudo privileges). Inside the .ssh directory, use your desired text editor to create your keypair (.pem) and config files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*8kwY5rNzc3qX-NIb_9zHvQ.png" /></figure><p>Copy/paste the key into the .pem file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*OpF3SXZ1be5TtCiQsGYpfA.png" /><figcaption>* Nano is used for this demo, but use whatever you are more comfortable with (Vim, Neovim, GNU Emacs, etc).</figcaption></figure><p>In the config file, fill in the following for both “worker” instances:</p><pre>Host &lt;name&gt;<br>HostName &lt;private ip&gt;<br>User ubuntu<br>IdentityFile /root/.ssh/your-kp-file.pem</pre><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*HTLoa0-YjqZD9Meh8og72Q.png" /></figure><h4>SSH Into Worker Nodes</h4><p>You should now be able to SSH into either of the two worker nodes (ex: ssh worker-node-1). Note that you may need to use sudo privileges here as well.</p><p>If you run into any issues with being denied access based on the keypair file’s visibility or permissions, running chmod 600 your-kp-file.pem should fix it and allow the connection.</p><p>Once SSH-ed into both worker nodes, again check that Docker was successfully installed using docker --version, then use sudo hostname set-hostname and name these two accordingly. In the example below, worker-node-1 and worker-node-2 have been chosen to go along with what was previously written in the config file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gW_TJMUWUaNvoKa-sjvJyA.png" /></figure><p>Again, reboot these two instances for the change to take effect.</p><p>Example upon rebooting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNci0osVd7qeD2UML71mrw.png" /></figure><h3>4. Building the Swarm</h3><p>From the manager instance, run docker swarm init — this will initialise the swarm with this instance as a manager node. In the two worker instances, simply copy/paste the docker swarm join --token ... command that was generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xi1Grntb2uS4aSi7iXc1cg.png" /></figure><p>To see the nodes in a swarm, check their status, etc, simply run docker node ls.</p><p>The example below shows all three nodes in the swarm — one manager, and two workers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KS7CJH-h2YyUL-8N2PSmkg.png" /></figure><p>With your three-node swarm set up, you can now deploy services.</p><h3>5. Test it Out</h3><p>Run a simple test to make sure your preliminary swarm setup behaves properly.</p><p>Use docker service create -d 80:80 --name nginx-web --replicas 1 nginx:alpine to launch the , then docker service ls to see the running service.</p><p>Next, test the service with docker service scale nginx-web=3 to scale to three replicas. You can again use docker service ls to check on the number of replicas as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nelxzqaeiePMYWDsWiowqg.png" /></figure><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dacd6a64847" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stand by Me: Persistent Data with Docker Volumes]]></title>
            <link>https://medium.com/@slaughterkn/stand-by-me-persistent-data-with-docker-volumes-61e7b08d28da?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/61e7b08d28da</guid>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 20:26:00 GMT</pubDate>
            <atom:updated>2023-11-25T20:26:00.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Z6ZLwS_Q8wNx6LRI8CVMdw.png" /></figure><h3>The Situation</h3><p>For businesses, continuous improvement in software development and deployment is crucial. Efficiency is the key to improving productivity, as well as the quality of software applications. Using tools like <strong>Docker</strong> and <strong>Jenkins</strong> provide a good path to this goal.</p><p>Docker simplifies processes by creating consistent, repeatable environments for applications, which ensures that they run smoothly across different system types.</p><p>Jenkins is a fantastic tool that automates parts of development, like building and testing code; in turn, making it faster and more reliable. Combining these two services streamlines the workflow process, reduces errors, and overall, help present better solutions.</p><h4>Why use Docker here?</h4><p>- <strong>Boosted Productivity</strong>: Docker speeds up the Jenkins setup process, reducing environment-related issues.</p><p>- <strong>Reliable Consistenc</strong>y: Docker ensures applications work consistently across different environments, maintaining reliability.</p><p>- <strong>Efficient Scalability</strong>: Docker’s ability to create new Jenkins containers on demand streamlines CI/CD pipelines, increasing efficiency and scalability.</p><p>- <strong>Persistent Data</strong>: Docker volumes are storage spaces that allow data to be shared between containers, which maintains both consistency and reliability.</p><h3>Setting it Up!</h3><h4>Pulling the Jenkins Image</h4><p>My first step is to pull the Jenkins image with a simple docker pull along with the image name. Here, I’ve chosen the specifically tagged jenkins:lts-jdk17 image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eaip3LbzRO9aF5ynblJLGg.png" /></figure><h4>Running the Jenkins Container</h4><p>Next up is to create the first Jenkins container, as well as the persistent volume both of the containers will share. I’m calling this container “jenkins_1” and have ports mapped to 8080:8080.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMu3L_chqdM1-VV3E6hBPQ.png" /></figure><h4>Finding the Jenkins Password</h4><p>Now that the container is up and running, I need to find the Jenkins password that was created at launch in the container’s logs. Below, I ran docker logs using the first three characters of the container ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0hB9zR8WKTxkspjZMP-Vg.png" /></figure><p>A bunch of launch information pops up, but if I scroll down a bit, I find this conveniently formatted section here, containing the generated password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*15kJyjNJj4gJdXkrva31Qw.png" /><figcaption>Note that this password can also be found in var/jenkins_home/secrets/initialAdminPassword</figcaption></figure><p>Now, in my browser, I can input my instance’s public IP address and specified port, and I’m brought to the Jenkins “Getting Started” page. Here’s where I paste in that password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xOaLcfnwngozRbg1T0RSQ.png" /></figure><p>After clicking continue, I can go through the rest of the set-up and installation pages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_faHR6Kjr9UwubzxE-TLtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sM09eY9D8C7kwYXzIn9IFg.png" /><figcaption>For the sake of this demo, I just went with the default options.</figcaption></figure><p>The last step in setting up Jenkins is creating the first administrative user and logging in for the first time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Z-6mOowVZhTUY6mx7nzHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GtAar3uDx9eEuiF2GhgBWA.png" /><figcaption>Creating the first admin user (left) and signing in (right).</figcaption></figure><p>Once I sign in, I’m brought to the Jenkins welcome dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrqhIldKa78rkMkcYzqFRA.png" /></figure><p>Alright! I can stop here and go on to the next big step: the second Jenkins container!</p><h3>The Second Container</h3><p>Now it’s test time. I need to launch another Jenkins container, just like I did before, but with two changes: this time, I’m using -p 8081:808, and --name jenkins_2 as my assigned port and container name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*nS-PTSLYcY9FYF59p8pk0Q.png" /><figcaption>I also need to make sure that the previously-created volume is attached to this container as well.</figcaption></figure><h4>Sign in to Jenkins from the New Container</h4><p>This right here is the moment of truth — is the data from the first container shared with this new one? I open my browser, navigate to my instances IP (port 8081 this time!), and am greeted by this awesome sight:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*RzSMi8JJQ398oXuv8U5zZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*RxVRUNCrE6DzdZ6dzeZ0XQ.png" /></figure><p>I’m taken straight to the sign in page — no need to enter in a generated password or go through setup instructions. All I need to do is enter in the admin username and password I created earlier, and CHECK IT OUT! Back in the Jenkins dashboard! I’d call that a success.</p><h4>One Last Point about the Volume:</h4><p>By running docker container inspect on both Jenkins containers, you can verify that they share that volume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*WuItz1-pA54M8SsG81UTrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*PCBa8gEPXRZbdX1cJ83APw.png" /><figcaption>Volume information for the jenkins_1 (left) and jenkins_2 (right) containers.</figcaption></figure><h3>Shorter Addendum Article Topics I’m Working On:</h3><ul><li>Using Jenkins with Docker Compose</li></ul><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61e7b08d28da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sitting on the Dock of the Bay: Dockerising Ubuntu and Apache]]></title>
            <link>https://medium.com/@slaughterkn/sitting-on-the-dock-of-the-bay-dockerising-ubuntu-and-apache-a91760a89a8c?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a91760a89a8c</guid>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Thu, 09 Nov 2023 23:13:47 GMT</pubDate>
            <atom:updated>2023-11-09T23:13:47.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*W6OCWp3598zajWbdeQ0mmg.png" /></figure><h3><strong>The Situation</strong></h3><p>Today at OtisCorp, we’re diving into the world of Docker! <br>I’ll be doing a couple of different things here:</p><ul><li>running an Ubuntu container</li><li>installing an Apache2 server <em>inside </em>that container</li><li>replacing the default Apache landing page with a ‘custom’ index</li><li>pushing and pulling to and from Docker Hub</li></ul><h4><strong>What’s So Special About Docker?</strong></h4><ul><li><strong>Consistency and Portability:<br></strong>Docker takes the stress out of moving apps from development to production, in consistent environments that work anywhere.</li><li><strong>Separation and Smarter Use of Resources:<br></strong>Docker containers keep web apps separate. This way, they play nice and don’t annoy each other. Allocating resource is also simplified, so each app gets exactly what it needs to perform best.</li><li><strong>Reproducible Outcomes</strong>:<br>A Dockerfile configuration specifies the exact components and settings required to run a web app container. This reproducible environment standardizes deployments across development, QA, staging and production.</li><li><strong>Quicker, Hassle-Free Deployment:<br></strong>Docker packages the complete web app stack into a single, containerised unit, so deployment is quick and easy.</li></ul><h4>Programs / Services Used</h4><ul><li>Visual Studio Code</li><li>Docker</li><li>Docker Hub</li><li>AWS EC2</li></ul><h3>Getting the Container Running</h3><p>I’m connected to an EC2 instance running Ubuntu via VS Code. I already have Docker installed, so I can jump right in. By default, Docker needs sudo privileges, so first I runsudo su to act as the root user.</p><p>Now, I can get to the actual Docker stuff — I’m using docker container run with the -d (detached), -p (port), --name (container name), and -i (interactive) options<strong>*</strong>.</p><p>Using the commanddocker container ps, I can see my ubuntu_web container up and running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhUz70Q9WWKb9hv_cloWMQ.png" /><figcaption><strong>*</strong> For some reason, without using -i, the Ubuntu container would start up, then immediately exit (even though I specified -d). This only happened on Ubuntu containers, despite the image version . Additionally, every other official Linux-distribution-based image I tried (alpine, centos, debian, amazonlinux, archlinux) worked fine, so honestly, I’m still not really sure what was up with that.</figcaption></figure><h3>Getting Inside the Container</h3><p>With my container up and running, my next step is to get inside it, using the command docker exec -it container_name bash. This command opens a BASH shell in my running container, giving me direct access to the Ubuntu environment.</p><h4>Updating the Container</h4><p>Now that I’m inside the container, I need to do a quick update. This works just like updating in a “regular” Ubuntu terminal environment, by running apt-get update -y. This updates all packages and ensures I have the latest security patches and updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSwQMYP2leUuGoPCPJv5Vw.png" /><figcaption>Updated!</figcaption></figure><h4>Installing and Starting the Apache Server</h4><p>After my initial update, I need to run apt install apache2 -y (or apt-get install apache2 -y) to install Apache2 inside the container as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYRycQaToVlAj9oZq2vBhA.png" /></figure><p>Once it’s installed, systemctl start apache2 (or service apache2 start)starts the Apache service. Running systemctl status apache2 (or service apache2 status) lets me check to make sure it’s up and running inside the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8nuxPuTxH_zmuoHkmRNTQ.png" /></figure><h4>Replacing the Default Apache Index</h4><p>This is the part where I get to add my own index page! I want to have an easy way to edit my index.html in the future, so I install nano with apt-get install nano y. Once that’s installed, I can run nano index.html to open the editor, paste in my fancy html, then save and close with ctrl+x, y, and hitting enter.</p><p>My index.html page is still in my current directory, so to replace the default Apache page, I simply need to copy it to the Apache web root directory running!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtBAmIafdeE05yQWENmOUw.png" /></figure><p>If I navigate over to the Apache web root directory (cd /var/www/html) and run cat index.html, I can see the contents of my file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfWFksCgc0YQVvp8g1HESg.png" /><figcaption>Technically I didn’t even need to actually GO to that directory. Silly me.</figcaption></figure><h4>Checking in the Browser</h4><p>Now, I’m all set up, so I need to check to see if I can actually access my page from my browser. I navigate to my EC2 instance’s current IP address, specifying port 80. In this case, it’s 52.200.105.29:80(but if not using an EC2 instance, localhost:80 should do the trick).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*D5pXFyenPf3jKhuvleDG5g.png" /></figure><p>And I’ve got a success!</p><h3>Creating the Image and Pushing to DockerHub</h3><p>I have to start this section off with a disclaimer — I had previously given my “ubuntu” user sudo privileges, meaning I could run Docker commands without using sudo or sudo su. For the sake of writing this article, though, I thought it would be less confusing if I was using regular sudo and sudo su as my commands. At some point, I took a break, came back to finish up this project, and totally forgot about that little detail. So, from here to the end, I’m running the Docker commands straight from my “ubuntu” user. Check out this <a href="https://docs.docker.com/engine/install/linux-postinstall/">Linux Post-Installation Steps Docker Docs page </a>to see that process.</p><p>With that out of the way, let’s continue. To make my changes here persistent, I need to create a new Docker image with docker commit container_name dockerhub_username/image_name:tag. I then push it to Dockerhub with docker push &lt;dockerhub_username/image_name:tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Np4S_IWx8a7JQA2efh4xVA.png" /></figure><p>If I hop over to Docker Hub, my image was successfully pushed to my repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RprZu0oPdbiUqH3z41EhZQ.png" /></figure><h3>Pulling the Image from Dockerhub</h3><p>Now that my custom Docker image is on Docker Hub, let’s see what happens when I pull it, using docker pull dockerhub_username/image_name:tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXBL-xpcSCpgxzOA-jX3zw.png" /></figure><h4>Deploying a New Container</h4><p>I’m deploying a new container from the pulled image, this time mapping port 8080 on the EC2 instance to port 80 in the container by running docker run -d -p 8080:80 --name new_container_name -i dockerhub_username/image_name:tag.*</p><p>* Again, using that -i, because the Ubuntu images are weird for me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_eoY_wbr4w6vtsadXW5eg.png" /></figure><p>I jump inside the new container, start the Apache server, then exit the container. Back in the Ubuntu terminal, If I run curl localhost:8080, I can once again see the contents of my custom index.html that’s now a part of this container’s image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTn6dgbgKZi6lFVrY2m32g.png" /></figure><h3>Checking the Browser Again</h3><p>When I check my browser now, I need to point it to the right port so this time I use my instance’s IP address with port 8080:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*HI70MyRtJtdkX2R0aM7KJg.png" /></figure><p>And this one works too! Yay!</p><h4>Shorter Addendum Article Topics I’m Working On:</h4><ul><li>Creating a new Docker network and attaching a container</li><li>Writing a Dockerfile</li></ul><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a91760a89a8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Functions: Using Lambda to Tuck EC2 Instances in at Night]]></title>
            <link>https://medium.com/@slaughterkn/functional-functions-using-lambda-to-tuck-ec2-instances-in-at-night-4cb67244cf19?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cb67244cf19</guid>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 20:02:05 GMT</pubDate>
            <atom:updated>2023-10-29T20:08:26.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Rs7k1m14vfz6vtUXFAObcw.png" /></figure><h3>The Scenario</h3><p>Here at OtisCorp, the engineering team frequently utilizes a dedicated development environment to assess new application releases. Recently, my managers have expressed their concerns after seeing increasing expenses associated with the development lab.</p><p>To address this issue and reduce costs, they have asked me to come up with a way to halt the usage of our EC2 instances once all engineers have completed their work for the day.</p><h3>The Solution</h3><p>To implement this cost-saving measure, I will be creating a Lambda function that will automatically stop the running EC2 instances every night at 7:00 PM.</p><p>This, in turn, will help us optimize our resource usage and reduce unnecessary expenditures.</p><h3>Programs / Services Used</h3><ul><li>AWS Lambda</li><li>AWS IAM</li><li>AWS CloudWatch EventBridge</li><li>AWS CloudWatch logs</li></ul><h3>The Lambda Function</h3><p>First things first — I head over to <strong>Lambda </strong>to create a new <strong>function </strong>that I’m calling “stop_instances”, using Python 3.11 (the newest Python edition listed at this time).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*dd_HWEA2efoeT0YTUixtow.png" /></figure><p>For the time being, I’m just letting Lambda create its <strong>default execution role</strong>. I’ll need to edit that in a minute, though. I also don’t need to do anything within the advanced settings, so I can go ahead and click through to create my function.</p><h4>The Functionality of the Function</h4><p>Once that’s created, I can go about actually specifying what this function should do within the “<strong>lambda_function.py</strong>” tab under “<strong>Code</strong>”.</p><p>The code here is simple and straightforward:</p><pre>import json<br>import boto3<br><br>def lambda_handler(event, context):<br>    ec2 = boto3.client(&#39;ec2&#39;)<br>    ec2.stop_instances(InstanceIds=[&#39;instance-id&#39;])<br><br></pre><p>In my example, I’m using ids of my three “dev-lab” instances. This is what it looks like in the Lambda console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6Amm1WNZCZqCqgISe4lcw.png" /></figure><p>At this point, if I were to deploy this function and attempt to test it, I’d get hit with an error, because my function’s IAM role doesn’t have the necessary permissions to EC2.</p><p>So let’s fix that!</p><h3>Modify the IAM Role</h3><p>In IAM, my function’s role is conveniently named the same thing as the function itself (with some extra characters added to the end):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BpF9oLZoZm5FiQFE89C15g.png" /></figure><p>There’s a couple different ways to modify the permissions to get my desired outcome. By far the quickest and easiest way is to click “add permissions”, “attach policies”, search for the “AmazonEC2FullAccess” policy, and attach it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18hw8l_uqmYkcyexwtcmfA.png" /></figure><p>But to be honest, that’s not the most secure way to handle things here, especially since my function just needs to perform one task — stopping the running instances.</p><h4>By Principal of Least Privilege</h4><p>Instead of using the full-access policy from AWS, I’m using my own simple inline policy (click “add permissions &gt; “create inline policy”). Now, I can strictly limit what my function can do within EC2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xB14R5knGlWgvPAR94IK-g.png" /></figure><p>I’m giving permissions to do two things — “DescribeInstances” and “StopInstances”.</p><p>I click through to review, name my inline policy, and finally create it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEDK9Uyb89hvhMFquLBBgA.png" /><figcaption>I probably could have given it a better name, but I figured “stop_instances_policy” worked well enough.</figcaption></figure><p>And here’s what that looks like in the IAM role instead of the previous “AmazonEC2FullAccess”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ld7fvIhjwA5cOpj7aGrPA.png" /></figure><p>Now that I have permissions taken care of, I can go back to Lambda and try my function out!</p><h3>Run the Test Event</h3><p>So, let me get a quick look at EC2, with my three “dev-lab” instances, running happily, unaware of what is about to happen to them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5a14diMjg-nozAMyqYv3eg.png" /></figure><p>Back in Lambda, I make sure to deploy the function, then do my first test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFdWaecBRAZ6yVVVeScrfQ.png" /><figcaption>It took a little less than three seconds this time.</figcaption></figure><p>And checking back in EC2, the three instances have been stopped:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IT7bfTehdzESk29PG3HSnQ.png" /></figure><p>Next, I’ll add the event that will automatically shut these down at 7:00pm.</p><h3>Integrate an EventBridge Trigger</h3><p>The trigger event can be created in EventBridge separately, or added right in through the Lambda console itself.</p><p>I’m using the “add trigger” straight from the Lambda console’s function overview section. For this scenario, my source is EventBridge and choose “create a new rule” and fill in the rule’s desired name and description. For rule type, I want “schedule expression”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*VIdbeBV0t2OZvrMuT0Qjeg.png" /></figure><p>I’m using a Cron expression above to specify when my function will be triggered. I want to invoke my function every day at 7:00 pm EST, so my cron expression would be cron(0 23 * * ? *)<strong>*</strong>.</p><p><strong><em>*Note:</em></strong><em> During the time of the year I’m writing this, I have to account for EST’s daylight savings time. When daylight savings time is not in effect, the expression should actually be </em>cron(0 0 * * ? *)<em>, because EST is UTC -5.</em></p><p><em>To see how cron expressions work, check out this AWS EventBridge reference page, and to learn more about UTC time, including time zone conversions and time offsets, </em><a href="https://www.utctime.net/"><em>utctime.net</em></a><em> is the best resource.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKnw35d8u7-VkzDpxiAnpw.png" /><figcaption>What it looks like in the function’s configuration tab.</figcaption></figure><p>Looking at the rule directly in EventBridge, I can see 10 of the upcoming times this rule will invoke my function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*ZErj1MihH9JImIxA0lBbRw.png" /></figure><p>Even though I already know my Lambda function works by directly invoking it, I now need to test this trigger.</p><h4>Testing the Trigger</h4><p>Clearly, I don’t want to wait all the way to 7:00pm to see if this works, so I made a quick modification — I changed the rule’s cron expression time to 1:30 PM, which gave me enough time to spin the three instances back up into a running state, go grab a bottle of water, and give my kid a bag of chips.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*wu4s501MZySAb76Ar0ZyzQ.png" /><figcaption>I probably should have just skipped showing the whole 7:00pm part and just done this, but then it wouldn’t go along with my scenario’s story, so this is just a minor detour for the sake of narrative consistency.</figcaption></figure><p>I come back after 1:30, check the log events, and my function was, indeed, invoked at the specified time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2fx8a4wYk-bBc8EXNFNGA.png" /><figcaption>Also, after checking over in EC2, all three of the dev-lab instances have been stopped.</figcaption></figure><p>And with that, I can implement this cost-saving measure for OtisCorp!</p><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cb67244cf19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python and Spaceships: Building a Dictionary of Files]]></title>
            <link>https://medium.com/@slaughterkn/python-and-spaceships-building-a-dictionary-of-files-a87e01c1a7c4?source=rss-4359486445b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a87e01c1a7c4</guid>
            <dc:creator><![CDATA[K Slaughter]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 20:38:21 GMT</pubDate>
            <atom:updated>2023-10-15T20:38:21.127Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Situation and the Solution</h3><p>A division of OtisCorp manufactures space ship parts*. They currently manufacture parts for four different categories: Engines, Grav Drives, Reactors, and Sensor Jammers.</p><p>I’ve been tasked with creating a Python script that can extract information (name, size, type, etc) about the files in a directory and store that information in a list of dictionaries.</p><p>My solution is to create two scripts — one that simply pulls the file information from the user’s current working director, and another that allows the user to specify a directory or path.</p><p><em>*Look, I’ve been </em><a href="https://bethesda.net/en/game/starfield"><em>playing a little too much Starfield</em></a><em> lately. The ship building in the game is awesome, so I thought I’d have a little fun.</em></p><h3>Programs and Services Used</h3><ul><li>AWS Cloud9 Environment</li><li>Python</li></ul><h3>The Code</h3><p>For this first part, I am creating the script that will get file information from the current working directory. This is what it looks like in the Cloud9 environment (an explanation and code block follow the image):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiq5bsIIFIFZjF3S6BueNA.png" /></figure><h4>How the Script Works:</h4><ol><li>First, it imports the os module, which provides functions for interacting with the operating system, then gets the current working directory with os.getcwd()and stores it in the variable cw_directory. This is the directory the script will be executed from.</li><li>It lists all the files in the current working directory using os.listdir(cw_directory) — these file names are stored in the files variable.</li><li>Creates an empty list called file_info_list that stores information about the files in the directory.</li><li>Iterates through each file in the files list using a forloop.</li><li>For each file in the directory, the full file path is created by joining the current working directory with the file name using os.path.join(cw_directory, each) and stores it in the file_path variable.</li><li>Checks if the file_path corresponds to a file (not a directory) using os.path.isfile(file_path) — if it’s a file, it retrieves the following information about the file and stores it as a dictionary:<br> — — “File Name”: name of the file (each)<br> — — “File Size (bytes)”: file sizewith .path.getsize(file_path)<br> — — “File Type”: by splitting the file name at the dot (.)<br> and using the last part of the split (the file extension)</li><li>The dictionary containing file information is appended to file_info_list.</li><li>Finally, it prints the list of dictionaries along with the information for each file found in the current working directory.</li></ol><p>For copy/paste purposes:</p><pre>import os<br><br># Get current working directory<br>cw_directory = os.getcwd()<br><br># List all the files in directory<br>files = os.listdir(cw_directory)<br><br># Create new empty list for file dictionaries<br>file_info_list = []<br><br># Iterate through each file in the list<br>for each in files:<br>    file_path = os.path.join(cw_directory, each)<br><br>    # Checks if it&#39;s a file  <br>    if os.path.isfile(file_path):<br>        # If file, gets the file information<br>        file_info = {<br>            &quot;File Name&quot;: each,<br>            &quot;File Size (bytes)&quot;: os.path.getsize(file_path),<br>            &quot;File Type&quot;: each.split(&#39;.&#39;)[-1],  # Gets file extension<br>        }<br>        file_info_list.append(file_info)<br><br># Print list of dictionaries<br>for file_info in file_info_list:<br>    print(file_info)</pre><h4>Select the Desired Directory</h4><p>In Cloud9, on the right-hand side of the terminal window there are three options/(buttons?) — “Runner”, “CWD”, and “ENV”. Click the middle “CWD” option and theres a popup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*FSJxkEjHMMm4b9eZL6K2ug.png" /></figure><h4>Run It!</h4><p>Once the current working directory has been set, click “Run” on the left-hand side of the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wVQN2iXngOYFzCkSs-wMg.png" /></figure><h3>Make It Better With User Input</h3><p>Now onto the second part — a script that will allow the user to specify any directory or path. This version will also be recursive — meaning that it will look into any nested directories within the given path.</p><p>Again, here’s what it looks like in Cloud9 (an explanation and code block follow the image):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZSeF0eaNVVT_wJcnQnG3w.png" /></figure><h4>How the Script Works</h4><ol><li>Like the first example, this script first imports the os module.</li><li>Defines the get_file_info(directory)function, which takes a directory path as input. This function retrieves information about all the files in the specified directory and its subdirectories.</li><li>Creates the empty list file_info_list that stores information about the files in the directory and subdirectories.</li><li>Uses the function os.walk(directory) to go through the directory and its subdirectories. For each file found, it extracts the following information:<br> — — “File Name”: name of the file (each).<br> — — “File Size (bytes)”: file size usingos.path.getsize(file_path).<br> — — “File Type”: by splitting the file name at the dot (.) and using the last part of the split (the file extension).</li><li>Appends this information as a dictionary to file_info_list.</li><li>Defines the choose_directory() function, which:<br> — — Prompts the user to input a directory path, OR if the user presses Enter without providing a path, defaults to the current working directory.<br> — — Converts the input path to an absolute path using os.path.abspath() (ensures that it is a valid path).<br> — — Calls the get_file_info function with the chosen directory path and stores the result in the resultvariable.<br> — — Iterates through the list of file information in result and prints to the console.</li></ol><p>For copy/paste purposes:</p><pre>import os<br><br># Instructions because I don&#39;t like text input boxes after a long line of text<br>print(&#39;--Input desired directory below, or hit Enter for the current directory.-- &#39;)<br><br># This function gets the file information<br>def get_file_info(directory):<br>    file_info_list = []<br>    for root, dirs, files in os.walk(directory): # Makes it recursive<br>        for each in files:<br>            file_path = os.path.join(root, each)<br><br>            file_info = {<br>                &quot;File Name&quot;: each,<br>                &quot;File Size (bytes)&quot;: os.path.getsize(file_path),<br>                &quot;File Type&quot;: each.split(&#39;.&#39;)[-1],  # Gets the file extension<br>                &quot;File Path&quot;: file_path, # States full directory path for the file<br>            }<br>            file_info_list.append(file_info) # Puts it all together in a list<br>    return file_info_list<br><br>def choose_directory(): <br>    path = input(&quot;Directory: &quot;) # Allows user input of directory path.<br>    if not path: <br>        path = os.getcwd() # Defaults to current working directory if no path is given<br>    else:<br>        path = os.path.abspath(path)  # Converts the input path to an absolute path (so chosen directory is also recursive)<br><br>    result = get_file_info(path)<br>    for item in result:<br>        print(item)<br><br>if __name__ == &quot;__main__&quot;:<br>    choose_directory()</pre><h4>Now Run This One!</h4><p>When I run this script, I am first greeted by my instructions and option to type in my desired directory. This time, instead of just seeing the Engines directory, I want to see ALL of the equipment OtisCorp offers — so I enter ../OtisCorp_ship_parts (the .. before the directory indicates that the script should look for the OtisCorp_ship_parts directory in the home directory).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Kt5LoJyGwGwLEm3e1PgOw.png" /><figcaption>Note that (as seen in the previous section’s “choose current working directory” screenshot) the directory “OtisCorp_ship_parts” does not contain any files, only other directories.</figcaption></figure><p>I hit Enter, my script executes, and the entirety of all four directories nested inside of OtisCorp_ship_parts is printed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HmKOA_MDoiJQWAafEQHgHA.png" /><figcaption>That’s a lot of files.</figcaption></figure><p>There we go — two ways get file information from directories using dictionaries!</p><h4>Thank you for reading! If you found this article interesting or helpful, feel free to <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=k-slaughter">follow me on LinkedIn</a>!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a87e01c1a7c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>