<?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 Kyle Headley on Medium]]></title>
        <description><![CDATA[Stories by Kyle Headley on Medium]]></description>
        <link>https://medium.com/@kyleantonioheadley?source=rss-8e1b55171a79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*onu2w4F4FPOB-XuThuH98w.jpeg</url>
            <title>Stories by Kyle Headley on Medium</title>
            <link>https://medium.com/@kyleantonioheadley?source=rss-8e1b55171a79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:37:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kyleantonioheadley/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[Consolidating Data with DynamoDB]]></title>
            <link>https://kyleantonioheadley.medium.com/consolidating-data-with-dynamodb-6e1d725b2680?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e1d725b2680</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Mon, 08 May 2023 07:24:38 GMT</pubDate>
            <atom:updated>2023-05-08T07:24:38.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*nw-exEgRfz0G2tpn" /></figure><p><strong>DynamoDB</strong> is<em> “a fast and flexible NoSQL database service for all applications that need consistent, single-digit millisecond latency at any scale. It is a fully managed cloud database and supports both document and key-value store models. DynamoDB automatically spreads the data and traffic for your tables over a sufficient number of servers to handle your throughput and storage requirements, while maintaining consistent and fast performance.</em></p><p>For this project, the goal is to utilize the capabilities of DynamoDB to create a table to store information in the form of key-value pairs. This time the task is to create a list of movies in a table that can be accessed and read by an EC2 instance but not written to (edited).</p><p><strong>Creating the Table</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*SVBBFKHrz_g4Iuwc.png" /></figure><p><strong>Granting EC2 permissions</strong></p><p>In the IAM service in the console select roles and create a role. If you type “DynamoDB” you will see a list of associated permission. We will follow the best practice which is to assign the least privilege necessary for this task. In this case it&#39;s “AmazonDynamoDbReadAccess”. Next, just create the policy and and name it.</p><p>After the policy is created we can create a generic t2.micro(free tier) instance and assign the policy read access policy we created to it.</p><p>We can then use the EC2 instance connect to run the AWS CLI within the instance. This allows us to check whether we can read and write to the DynamoDB table. Scan the table with this code:</p><pre>aws dynamodb scan -table-name Movies -region us-east-1.</pre><p>The CLI should list all of the table contents as scanning just requires read access. However, if you try to edit the info you should receive an error. Using this code to enter one more “key:value” pair:</p><pre>aws dynamodb put-item -table-name Movies -region us-east-1 -item ‘{“Title”: {“S”: “Batman”}}</pre><p>This returns an “AccessDeniedException” error indicating the lack of permission to write to the table. Mission accomplished.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e1d725b2680" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Lambda and Python to Shut Down all EC2 instances]]></title>
            <link>https://kyleantonioheadley.medium.com/using-lambda-and-python-to-shut-down-all-ec2-instances-971f6d448521?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/971f6d448521</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Mon, 08 May 2023 05:30:24 GMT</pubDate>
            <atom:updated>2023-05-08T05:30:24.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*DLveCZtaCEV6h1cF0zSvwQ.jpeg" /></figure><p>Let’s say we needed to automate the shutdown of all EC2 instances with code instead of through the console. One way you could do this is with an AWS Lambda function.</p><p>Scenario: Our DevOps engineering team often uses a development lab to test releases of our application. The Managers are complaining about the rising cost of our development lab and need to save money by stopping all of our ec2 instances after all engineers are clocked out.</p><p><strong>Creating a role and assigning permissions:</strong></p><p>The first step to making that happen would be to permit Lambda to interact with your EC2 instance. It’s important to use the principle of least privilege to protect your account from being compromised. All this means is to give the least possible privileges to accomplish the task. In this case, if lambda was comprised its effects would be isolated to whatever specific task it is assigned.</p><p>Now we go to create the role, we can use AWS Service for Entity Type and ‘Lambda’ for Use Case. On the dropdown labeled ‘Use Cases for other AWS Services’ and select ‘Lambda.’ Next for permission select “start/stop EC2” and create the role and name it.</p><p><strong>Create Lambda function:</strong></p><p>Now we go to the Lamda service to create the function, using the authored from scratch setting to have more personalized options. Under permissions use an existing role, which will be the one just created, and then create a function with this code to stop a single instance.</p><pre>import boto3<br><br>region = ‘us-east-1’<br><br>instances = [‘YOUR INSTANCE ID’]<br><br>ec2 = boto3.client(‘ec2’, region_name=region)<br><br>def lambda_handler(event, context):<br><br>ec2.stop_instances(InstanceIds=instances) print(‘stopped your instances: ‘ + str(instances))</pre><p>And this one to stop every instance:</p><pre>import boto3 <br>ec2_client = boto3.client(&#39;ec2&#39;)<br>regions = [region[&#39;RegionName&#39;] for region in ec2_client.describe_regions()[&#39;Regions&#39;]]<br><br>def lambda_handler(event, context):<br>    for region in regions:<br>        ec2_client = boto3.client(&#39;ec2&#39;, region)<br>        all_instances = ec2_client.describe_instances()<br>        if all_instances:<br>            print(&quot;List all instances:&quot;)<br>            for reservation in all_instances[&#39;Reservations&#39;]:<br>                for instance in reservation[&#39;Instances&#39;]:<br>                    print(instance[&#39;InstanceId&#39;] + &quot;-&quot; + instance[&#39;State&#39;][&#39;Name&#39;])<br>                    <br>                    if instance[&#39;State&#39;][&#39;Name&#39;] == &#39;running&#39;:<br>                        print(&quot;Stopping ec2: &quot; + instance[&#39;InstanceId&#39;])<br>                        ec2_client.stop_instances(InstanceIds=[instance[&#39;InstanceId&#39;]])</pre><p>This code imports boto3 so that Lambda can interact with ec2 through boto3. It uses a for loop for the initial region setting to say that this applies to every region in this account.</p><p>The “def lambda_handler(event, context)” is giving the actual task to the lambda function. For all regions, describe or list the status. The function will also print “list all instances” along with the instance ID, name, and state (running/stopped/terminated). For each instance that is listed as running it will print “Stopping ec2: InstanceId” and then stop it.</p><p>After running the code you can see for yourself by looking to see if all the instances are stopped in the EC2 service.</p><p>Just like that, every single instance running is stopped, conserving costs until you need them again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=971f6d448521" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an SQS Queue using Python and Lambda]]></title>
            <link>https://kyleantonioheadley.medium.com/creating-an-sqs-queue-using-python-and-lambda-810aa7642ea8?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/810aa7642ea8</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Mon, 08 May 2023 04:08:43 GMT</pubDate>
            <atom:updated>2023-05-08T04:08:43.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*k6jOhwwVu3Kb9W-BZ7obPg.png" /></figure><p><strong>Goals for this project:</strong></p><ol><li>Create a Standard SQS Queue using Python.</li><li>Create a Lambda function in the console with a Python 3.7 or higher runtime.</li><li>Modify the Lambda to send a message to the SQS queue. The message should contain either the current time or a random number.</li><li>Create an API gateway HTTP API type trigger.</li><li>Test the trigger to verify the message was sent.</li></ol><p><strong>Create SQS queue</strong></p><p>The first step is booting up AWS Cloud9 to use the console for the Python code.</p><pre>import boto3<br>sqs = boto3.resource(&#39;sqs&#39;)<br>queue = sqs.create_queue(QueueName=&#39;Week15pro&#39;)<br>print(queue.url)</pre><p>This code imports the boto3 SDK which allows us to interface with AWS resources using our Python code. The code also allows for the use of the sqs resource and creates an SQS queue named “Week15pro”. It then will print the URL for the queue to the console.</p><p><strong>Create Lambda function</strong></p><p>Now we’ll create a lambda function that sends a message to the queue. We first need to create permissions. Best practice says we use the principle of least privilege which is exactly how it sounds. We choose to give the minimum privileges necessary to accomplish the desired task. This is to prevent damage or security issues if one resource like Lambda was compromised. Our lambda will use the AmazonSQSFullAccess policy.</p><p>To do this you have to go to IAM in the AWS console click on roles and create a role, then lambda select “AmazonSQSFullAccess” , create a role, and name it.</p><p>Now we need to go into the Lambda service to create the function using a runtime version of at least 3.7 and the role created. Note that the destination setting should be Asynchronous. What this means is that lambda can send a message to the queue and just have it sit there rather than needing to return a value. The condition should be set to success.</p><p>This is the code that we need to use for the Lambda function:</p><pre>import json<br>import boto3<br>from datetime import datetime<br><br>current_date_time = datetime.now()<br>sqs = boto3.resource(&#39;sqs&#39;, region_name=&#39;us-east-1&#39;)<br><br>def lambda_handler(event, content):<br>    <br>    queue = sqs.get_queue_by_name(QueueName=&#39;Week15pro&#39;) <br><br>    date_time = current_date_time.strftime(&quot;%d/%m/%Y %H:%M:%S&quot;) <br>    message = (&quot;The current date and time at point of trigger was &quot; + str(date_time) + &quot;.&quot;) <br>    <br>    <br>    response = queue.send_message(MessageBody = message) <br><br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &#39;body&#39;: json.dumps(message)<br>    }</pre><p>This code imports json which is the format Lambda uses to encode, as well as boto3 so the function can interact with the SQS. The datetime package is necessary to import so that the Lambda function can fetch the date and time to send to the queue.</p><p>Lambda then retrieves the queue name for the destination and creates the message written + date and time.</p><p>This will return a status code of “200” and the body of the message when it executes successfully.</p><p><strong>API Trigger:</strong></p><p>Click the “Add trigger” button in your “Function overview” within the Lambda options</p><p>Select “API Gateway” then “<strong>Create a new API”</strong>, then select “HTTP API” for API type. Once a name is created we can add the trigger.</p><p>Now we add permissions just like we did before instead of lambda and create permission “<strong>AmazonAPIGatewayAdministrator</strong>”.</p><p>In the configuration tab if you select triggers and go to the API endpoint link of the new API trigger you should be able to see the message generated from your lambda function. In the actual SQS service screen, you can poll for messages to confirm that it was received from the Lambda function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=810aa7642ea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Python to Automate the Shutdown of Specific Instances]]></title>
            <link>https://kyleantonioheadley.medium.com/using-python-to-automate-a-server-shutdown-d656f28e5ca3?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/d656f28e5ca3</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Mon, 08 May 2023 02:16:44 GMT</pubDate>
            <atom:updated>2023-05-08T04:38:02.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*ZQHHpi_ZzcOFKrbcVU2RxA@2x.png" /></figure><p>Scenario: Our DevOps engineering team often uses a development lab to test releases of our application. However, the managers are complaining about the rising cost of our development lab and need to save money by stopping our (for this example) 3 EC2 instances after all engineers are clocked out.</p><p>First I’ll create the instances to stop them. In a real-world scenario, we would likely need to create also and this allows me to simplify things by using relatable and partially re-usable code.</p><p><strong>Creating:</strong></p><pre>import boto3<br><br>ec2 = boto3.resource(&#39;ec2&#39;)<br><br>instance = ec2.create_instances(<br>    ImageId=&#39;ami-06e46074ae430fba6&#39;,<br>    InstanceType=&#39;t2.micro&#39;,<br>    MinCount=3,<br>    MaxCount=3,<br>    TagSpecifications=[{&#39;ResourceType&#39;:&#39;instance&#39;,&#39;Tags&#39;:[{&#39;Key&#39;:&#39;Name&#39;,&#39;Value&#39;:&#39;Environment: Dev&#39;}]}]<br>)<br><br>print(instance)</pre><p>This code creates ec2 instances using Boto3 and Python. The import boto3 allows us to use the boto3 which is a software development kit that allows interfacing with AWS resources.</p><p>The second line allows the use of the ec2 instance resource. The rest are the details of the instance or instances you want to create.</p><p><strong>Image ID</strong> is ami-06e46074ae430fba6 which is an Amazon machine image. This is a free tier instance for this project.</p><p>The i<strong>nstance type</strong> is “t2.micro”, this is the size, small and free, nothing bigger is needed.</p><p><strong>Min count and Max count</strong> are the minimum and maximum number of instances created.</p><pre>TagSpecifications=[{&#39;ResourceType&#39;:&#39;instance&#39;,&#39;Tags&#39;:[{&#39;Key&#39;:&#39;Name&#39;,&#39;Value&#39;:&#39;Environment: Dev&#39;}]}]<br>)</pre><p>This line allows me to create tags or names for my instances so, in this case, it would give a tag to my instances with the name “<strong>Environment: Dev</strong>”. This will create 3 instances named “<strong>Environment: Dev</strong>”</p><p>We can then use the code:</p><pre>print (instance)</pre><p>This allows us to see the instances created printed to the console.</p><p>Now how do destroy with similar Python code?</p><pre>import boto3<br><br>ec2 = boto3.resource(&#39;ec2&#39;)<br>tag = {&#39;Name&#39;:&#39;tag:Name&#39;,&#39;Values&#39;:[&#39;Environment: Dev&#39;]}<br><br>instances = ec2.instances.filter(Filters=[tag])<br><br>for instance in instances:<br>    instance.stop()<br>    print(&quot;DONE&quot;)</pre><p>This also imports boto3 which we said is required to interact with the resource (EC2). In this case, we create a dictionary of the tags that we can iterate through with specific instructions (filtering by tag). This will search for tags named “<strong>Environment: Dev</strong>”, the same tags created earlier. Then the for loop will stop all of the tags that fit the criteria.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d656f28e5ca3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerization Using Docker + Boto3/Python]]></title>
            <link>https://kyleantonioheadley.medium.com/containerization-using-docker-boto3-python-2b6d75d5edfc?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b6d75d5edfc</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Mon, 08 May 2023 01:10:44 GMT</pubDate>
            <atom:updated>2023-05-08T01:10:44.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FQLUnZPv1qn3otx8.png" /></figure><p><strong>Docker</strong> <em>is</em> <em>a platform that allows developers to create, deploy, and run applications in a containerized environment. Containers are lightweight, portable, and self-contained software packages that include everything an application needs to run, such as code, libraries, and dependencies. Docker provides a standardized way to package and distribute applications, making it easier for developers to build, ship, and run their applications across different environments.</em></p><p>For this project, the goal was to emulate a scenario where members of a software development team are working on a Python-based application. The team needs to simplify its development environment setup and ensure consistent execution of its code across different machines. By utilizing Docker, the team can also ensure that their development environment is portable and can be easily replicated on different machines, streamlining their workflow and enabling efficient collaboration.</p><p>Goals:</p><ul><li>Build a docker file for Boto3 / Python</li><li>Use an official Ubuntu image on Dockerhub</li><li>Download any three repos to the local host</li><li>Create three Ubuntu containers</li><li>Each container should have a bind mount to one of the repo directories</li><li>Log into each container and verify access to each repo directory</li></ul><h4>Start Docker</h4><p>The first step is to boot up AWS Cloud 9, which is an IDE or integrated development environment, this allows you to run docker. Cloud9 gives the user access to a console with some additional built-in functionality. For example, if you run the following command:</p><pre>docker version</pre><p>This lists the info for the currently installed Docker version which is an example of the built-in additions I was referring to as Docker should be preloaded in Cloud 9. If for some reason it isn’t or you need to run Docker in a different Linux console outside of Cloud9 then you would run:</p><pre>sudo yum install -y docker<br>sudo service docker start<br>sudo docker info</pre><p>These lines install, start and verify the current status of Docker (whether it’s running). In my case, I only needed the last two.</p><h4>Get Docker Image</h4><p>Docker images are hosted on <a href="http://dockerhub.com/">dockerhub.com</a>. To get the Ubuntu container image needed you can search Ubuntu and select one of the official images such as the 23.04 version:</p><p>To organize my docker-related project files I created a directory and then moved into that directory using the “mkdir Dockerpro” and “cd Dockerpro” commands.</p><p>Within my new “Dockerpro” directory I created my dockerfile, which is the file docker uses for image instructions. This file is created using the “nano Dockerfile” command. This command opens a text file where you can insert the code the container itself runs. In this case, it’s:</p><pre>FROM ubuntu:23.04<br><br>RUN apt-get update<br><br>RUN apt-get -y install python3-pip \<br>    &amp;&amp; pip install boto3</pre><p>The first line is the Ubuntu image version taken from dockerhub.com. Line two updates all packages and the last line installs both Python and Boto3. It’s important to note that the use of “apt” here is used because the container is using an Ubuntu image that uses the apt package manager. Earlier we used yum to do the same thing in the Cloud9 command line using the yum package manager. Ctrl + o saves the file and Ctrl +x closes the editor.</p><p>Next, the command to build the image using the file is :</p><pre>docker image build -t &lt;insert_custom_name&gt; .</pre><p>The image will have whatever name you include after the “-t”, the “.” at the end signifies that this is taking place in your current working directory, using the dockerfile it will find there.</p><h4>Retreiving the repos:</h4><p>This is very straightforward, clone any three repos to have access to them for your docker containers. The command is “git clone” followed by whatever random repo you choose and repeat two more times. An example is cloning my repo:</p><pre>git clone https://github.com/kyleheadley1/ChevyWoodsPython.git</pre><p>After cloning all three you should be able to see them in the current directory with the “ls” command.</p><h4>Creating the containers and binding the repos:</h4><pre>docker run -d -t --name container_one -v /home/ec2-user/environment/boto3_dev/ChevyWoodsPython:/ChevyWoodsPython python_boto3</pre><p>This code creates a container with the name “container one”. It then uses the “-v” flag to bind the ChevyWoodsPython repo that was cloned to the container. The -d flag allows the container to run the container in the background or “detached”. The -t flag creates a session inside the container which helps it stay running, which was an issue I had. Repeat this replacing “container_one” with a new name and ChevyWoodsPython with another repo. The command “docker ps” will list the names of all containers running and their status.</p><h4>Verify the containers are running:</h4><p>I used the command:</p><pre>docker exec -it container_one bash</pre><p>This allows access into the container where you can verify that all of the files in the repo are there with the cd and ls commands, moving between files and listing contents, respectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b6d75d5edfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Jenkins Server Using Terraform/AWS]]></title>
            <link>https://kyleantonioheadley.medium.com/creating-a-jenkins-server-using-terraform-aws-48e8fbdbae92?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/48e8fbdbae92</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Mon, 08 May 2023 01:09:00 GMT</pubDate>
            <atom:updated>2023-05-08T01:09:00.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i8aDRQqtxLkmZDtF.png" /></figure><p>The goal for this project was to use Terraform to run a Jenkins server housed within AWS services. This demonstrates a realistic example of combining several tools to create a pipeline for DevOps projects. With these concepts a team could use Jenkins for CI/CD and with Terraform the setup could be saved, utilized in various environments, and worked on collaboratively and tracked.</p><p><strong>Terraform</strong> is<em> “an open-source infrastructure as code (IaC) tool developed by HashiCorp that enables users to define and manage infrastructure in a declarative way. It allows users to describe their infrastructure requirements using a high-level configuration language, and then automatically creates and manages the underlying infrastructure resources required to support those requirements.”</em></p><p><strong>Jenkins</strong> is<em> “a popular open-source automation server that is used for continuous integration and continuous delivery (CI/CD) of software applications. It is a Java-based tool that is designed to automate various parts of the software development process, including building, testing, and deploying applications.”</em></p><p>Things I wanted to accomplish:</p><ul><li>Run Terraform on AWS Cloud 9</li><li>Create EC2 instance using Terraform and bootstrap Jenkins Installation</li><li>Create a security group allowing traffic on port 22 from my IP and allowing traffic on port 8080</li><li>Create an S3 bucket for my Jenkins Artifacts, that is not open to the public</li><li>Access Jenkins through the browser to ensure it’s working.</li></ul><p>I chose to run Terraform through AWS because I’m not only very familiar with it at this point, but through the CLI in Cloud9, it has many tools already integrated (like Terraform). Terraform could be run from any console and would then access AWS through SSH. Additionally, if you access Terraform while already within AWS you avoid having to authenticate in whichever other Command Line Interface you use as you would be already logged in. The setup ends up being AWS(Cloud 9) running Terraform running AWS (EC2 instance) running Jenkins which sounds more confusing than it is but still important to note.</p><p>The only requirement here is that you have an AWS account.</p><h3><strong>First Step: Running Terraform in AWS Cloud 9</strong></h3><p>This part was the easiest as the AWS management console is fairly easy to navigate. I just accessed the Cloud9 service and used an environment I created. Then once inside I created the main.tf and variables.tf files that Terraform needs to run. These two files are what give Terraform the plan it needs to run.</p><p><strong>Main.tf file</strong>:</p><pre>resource &quot;aws_security_group&quot; &quot;JenkinsSG&quot; {<br>  name        = &quot;JenkinsSG&quot;<br>  description = &quot;Allow HTTPS/ssh and Jenkins&quot;<br>  vpc_id      = var.vpc_id<br><br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = var.cidr<br>  }<br><br>  ingress {<br>    from_port   = 8080<br>    to_port     = 8080<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = var.cidr<br>  }<br>  <br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = var.cidr<br>  }<br><br>  ingress {<br>    from_port   = 443<br>    to_port     = 443<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = var.cidr<br>  }<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = var.cidr<br>  }<br>}</pre><p>This creates a security group that functions as a firewall limiting access to the ports you choose. 22 is SSH, 80 is HTTP 443 is HTTPS and 8080 is the port that Jenkins uses.</p><p>After that, there needs to be the EC2 created which will be running Jenkins so another resource needed to be added to the main.tf code:</p><pre>resource &quot;aws_instance&quot; &quot;terrajenkinsec2&quot; {<br>  ami           = var.ami<br>  instance_type = var.instance_type<br>  user_data     = file(&quot;jenkins.sh&quot;)<br><br>  vpc_security_group_ids = [aws_security_group.JenkinsSG.id]<br><br>  tags = {<br>    Name = &quot;Jenkinspro&quot;<br>  }<br>}</pre><p>This creates a terraform resource named “terrajenkinsec2”, using the ami and instance type provided in my variables.tf file and user_data provided by the “jenkins.sh” file. This user data provides the code that tells the instance to install and run Jenkins. It also makes sure this instance uses the security group I created in the earlier code allowing it the access necessary for this task.</p><p><strong>Jenkins.sh file:</strong></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<br>sudo amazon-linux-extras install java-openjdk11 -y <br>sudo yum install jenkins -y<br>#sudo systemctl enable jenkins<br>sudo systemctl start jenkins</pre><p>This code updates the package manager and downloads Jenkins from the provided source along with the required key. It then upgrades (replaces the old with the new) and installs Java along with Jenkins and then runs Jenkins. I commented out the “enable” line because it makes Jenkins start automatically on startup. This is a great feature but it becomes a hassle if you need to troubleshoot what part of the code causes problems because Jenkins will show as running still from an earlier successful run.</p><p><strong>Create the s3 bucket</strong></p><pre>resource &quot;aws_s3_bucket&quot; &quot;jenkinsArtifactBucket&quot; {<br>  bucket = var.s3bucketname<br>}</pre><p>The s3 bucket is private and not open to the public by default so no additional code is required.</p><p><strong>Variables.tf file</strong></p><p>This houses the information that corresponds with each “var.x” reference in the main.tf file. While technically everything can be hard-coded or explicitly written out in the main.tf file it’s not considered best practice. This is because one of the main reasons for using Terraform and Infrastructure as code is to have consistent repeatable code. The main.tf can be consistent and allow the variables.tf to be swappable for alternate use cases.</p><pre>variable &quot;ami&quot; {<br>  type    = string<br>  default = &quot;ami-069aabeee6f53e7bf&quot;<br>}<br><br>variable &quot;instance_type&quot; {<br>  type    = string<br>  default = &quot;t2.micro&quot;<br>}<br><br><br>variable &quot;vpc_id&quot; {<br>  type    = string<br>  default = &quot;vpc-026f49c079f59f5df&quot;<br>}<br><br><br><br>variable &quot;security_group&quot; {<br>  type    = string<br>  default = &quot;t2.micro&quot;<br>}<br><br>variable &quot;cidr&quot; {<br>  description = &quot;CIDR&quot;<br>  type        = string<br>  default     = &quot;0.0.0.0/0&quot;<br>}</pre><p>After having both of these files correctly coded, you can run the “terraform init” command, to initialize the directory and create the terraform state. This is necessary to make sure terraform is ready to run. Next, you run “terraform validate” to make sure the syntax of everything is correct for Terraform and then “terraform apply” to apply changes. After waiting for the changes to occur you should then be able to see the Jenkins server page by putting the public IP of your instance in your browser with “:8080/” at the end. The following code will print the full link required, just use the instance name you chose rather than my “terrajenkinsec2”</p><pre>output &quot;jenkins_url&quot; {      #Prints instance public ip to console with :8080<br>  value = &quot;http://${aws_instance.terrajenkinsec2.public_ip}:8080/&quot;<br>}</pre><p>With that link displaying the Jenkins homepage and confirming the s3 bucket and resources were created, I achieved my goal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48e8fbdbae92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using a Python Script to Create, Populate and Scan an AWS DynamoDB Table]]></title>
            <link>https://kyleantonioheadley.medium.com/using-a-python-script-to-create-populate-and-scan-an-aws-dynamodb-table-10835012c68a?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/10835012c68a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Mon, 08 May 2023 00:43:30 GMT</pubDate>
            <atom:updated>2023-05-08T00:43:30.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fs1NhmR7MpGnosEA.png" /></figure><p>For this project, I wanted to be able to automate a few of the more basic tasks of a DynamoDB table using a Python script. The tasks are the creation of the table, adding items to the table, and scanning for said items.</p><p>I used AWS Cloud9 as my IDE, or Integrated Development Environment, allowing me to write my code and push it to GitHub.</p><p><strong>Integrated Development Environment/IDE</strong>: “<em>software for building applications that combines common developer tools into a single graphical user interface (GUI).”</em></p><h3>Creating the table</h3><p>The first step in creating the table was to install and import boto3. Boto3 is an AWS Software Development Kit for Python. This kit allows the user to manage AWS services with their code.</p><p>Install boto3 with this command in the Cloud9 command line:</p><pre>$ pip install boto3</pre><p>I then created a new Python file in Cloud9 to write my script using the touch command ie “touch pythonscript.py”. Within that file, I used the following code broken down by step:</p><pre>import boto3<br><br># replace the keys below<br><br>dynamodb = boto3.resource(<br>    &#39;dynamodb&#39;,<br>    aws_access_key_id=&#39;*****&#39;,<br>    aws_secret_access_key=&#39;*****&#39;,<br>    )</pre><p>This imports boto3 and uses the dynamodb boto3 resource to establish a connection using your AWS access and secret keys. This grants authorization for the later code to make changes within DynamoDB on your account.</p><pre>table = dynamodb.create_table ( # Create the DynamoDB table.<br>    TableName = &#39;DrinkChoice&#39;,<br>       KeySchema = [<br>        {<br>            &#39;AttributeName&#39;: &#39;Name&#39;,<br>            &#39;KeyType&#39;: &#39;HASH&#39;<br>        },<br>        {<br>            &#39;AttributeName&#39;: &#39;Drink&#39;,<br>            &#39;KeyType&#39;: &#39;RANGE&#39;<br>        }<br>    ],<br>    AttributeDefinitions=[<br>        {<br>            &#39;AttributeName&#39;: &#39;Name&#39;,<br>            &#39;AttributeType&#39;: &#39;S&#39;<br>        },<br>        {<br>            &#39;AttributeName&#39;: &#39;Drink&#39;,<br>            &#39;AttributeType&#39;: &#39;S&#39;<br>        },<br>    ],<br>    ProvisionedThroughput={<br>        &#39;ReadCapacityUnits&#39;: 5,<br>        &#39;WriteCapacityUnits&#39;: 5<br>    }<br>)</pre><p>This creates a DynamoTable named “DrinkChoice” as a way for me to categorize my friends’ favorite beverages.</p><p><strong>Keyschema</strong> determines the key value pairing stored in the table. The first attribute is “Name” for the person’s name and Drink for their drink. Hash and range are the default names for the two associated attributes.</p><p><strong>Attribute definitions</strong> define the two attributes as strings or words with an “s”.</p><p><strong>ProvisionedThoroughput </strong>is the table&#39;s ability to read and write, the higher the number the more processing can be done. This table is going to be small so 5 RCUs and 5 wcus’s are sufficient.</p><pre>table.wait_until_exists() # Waits until the table exists before finishing<br><br>print(table) #returns confirmation of table creation<br><br>with table.batch_writer() as batch:<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Alex&quot;, &quot;Drink&quot;: &quot;TequilaSeltzer&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Zozo&quot;, &quot;Drink&quot;: &quot;Margarita&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Melanie&quot;, &quot;Drink&quot;: &quot;Jameson&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Franklin&quot;, &quot;Drink&quot;: &quot;MoscowMule&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Kyle&quot;, &quot;Drink&quot;: &quot;KentuckyMule&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Sarah&quot;, &quot;Drink&quot;: &quot;RumAndRedbull&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Lucy&quot;, &quot;Drink&quot;: &quot;HennyCoolada&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Roberly&quot;, &quot;Drink&quot;: &quot;D&#39;usse&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Jose&quot;, &quot;Drink&quot;: &quot;Casamigos&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Aleane&quot;, &quot;Drink&quot;: &quot;RumAndCoke&quot;})<br>    batch.put_item(Item={&quot;Name&quot;: &quot;Angie&quot;, &quot;Drink&quot;: &quot;ExpressoMartini&quot;})<br><br>print(batch) #returns confirmation of batch write<br><br>response = table.scan() #scans table and returns all items<br>print(&quot;The query returned the following items:&quot;)<br>for item in response[&#39;Items&#39;]:<br>    print(item)</pre><p>The <strong>wait until exists</strong> command isn’t necessary but it waits until the table exists before finishing. This is just a quality-of-life thing, it lets you know the table is fully finished before giving a response in the console. Otherwise, it’ll show as finished and you will have to wait a little longer to see the table in your AWS account. I got a little tired of it saying done and nothing appearing making me think there was an error</p><p><strong>Print table</strong> prints the confirmation of the table creation</p><p><strong>The batch writer command</strong> is important because it populates the full table immediately as opposed to pushing each item one by one. The larger the list the more important that is. “Print batch” then confirms the items are inserted.</p><p>The last bit of code scans the whole table and uses a for loop to then print each item it finds to the console. This allows me to see exactly what the current table reads.</p><p>Additionally, you can use the following code to remove an item from the table:</p><pre>response = table.delete_item(<br>        Key={<br>            &#39;Kyle&#39;: &#39;KentuckyMule&#39;<br>        }<br>    )</pre><p>This wraps up this project, using python code in Cloud9 we successfully created, populated, and scanned an AWS DynamoDB table.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10835012c68a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Two Tier AWS Architecture using Terraform (Web + Database)]]></title>
            <link>https://kyleantonioheadley.medium.com/building-a-two-tier-aws-architecture-using-terraform-web-database-47e04d71e2eb?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/47e04d71e2eb</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 04:33:39 GMT</pubDate>
            <atom:updated>2023-04-17T04:35:15.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g7KUShfLGFAjvFk8.jpg" /></figure><p>For this project the task was to create a VPC with 2 public subnets, and 2 private subnets. Within the public subnets there should be two EC2 instances each with its own webserver. Within the private subnets a RDS database.</p><p><strong>Requirements</strong>: AWS account/ AWS Cloud 9</p><p>I used Cloud 9 for this project because it’s an AWS service so building AWS resources and architecture with it has less obstacles. Cloud 9 also has terraform already included.</p><p><strong>Terraform</strong> is<em> “an open-source infrastructure as code (IaC) tool developed by HashiCorp that enables users to define and manage infrastructure in a declarative way. It allows users to describe their infrastructure requirements using a high-level configuration language, and then automatically creates and manages the underlying infrastructure resources required to support those requirements.”</em></p><p>Github link: <a href="https://github.com/kyleheadley1/ChevyWoodsPython/tree/main/Pro22">https://github.com/kyleheadley1/ChevyWoodsPython/tree/main/Pro22</a></p><p>*All of the below was done within the console in an AWS Cloud9 environment*</p><h3>Creating the Blueprint</h3><p>Terraform needs a Main.tf file in order to execute. This file provides the framework. The contents of this file is what Terraform runs/builds. With this in mind it’s tempting to layout the entire plan within this Main.tf file. Although that would still accomplish the goals here, it’s not best practice. Instead of “hardcoding” or typing in the specific values in the main.tf file, it should be set up with general values that point to the specific values in the variables.tf file. Here’s an example:</p><ol><li>Code in Main.tf file with hardcoded values:</li></ol><pre>resource &quot;aws_vpc&quot; &quot;Main&quot; {          # Creates VPC<br>  cidr_block       = &quot;10.0.0.0/24&quot;   #CIDR block 10.0.0.0/24<br> }</pre><p>2) : Code in Main.tf file referencing values found in variables.tf file below it</p><pre>resource &quot;aws_vpc&quot; &quot;Main&quot; {            # Creates VPC<br>  cidr_block       = var.main_vpc_cidr # CIDR block 10.0.0.0/24<br> }</pre><pre>variable &quot;main_vpc_cidr&quot; {<br>    type    = string<br>    default = &quot;10.0.0.0/24&quot;<br>}</pre><p>In both examples the same thing happens, Terraform creates a VPC with a CIDR block of 10.0.0.0/24. The second allows you to customize and swap variables without editing the main.tf file. This is important because terraform allows you to build a complex framework that someone else can use (Main.tf), while swapping in their own situational variables (variables.tf).</p><p>In the Cloud9 console, I used the Linux touch command to create the main.tf and variables.tf files</p><pre>touch main.tf<br>touch variables.tf</pre><p>In Terraform each of the things you need to build are resources. In order to create a resource in Terraform you have to use a resource block which is displayed below. You can find the appropriate resource blocks and arguments in the Terraform documentation. This is the a link to the documentation on VPC’s (<a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/vpc">https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/vpc</a>).</p><p>The first step is <strong>building the VPC resource</strong> using the code I displayed earlier:</p><pre>resource &quot;aws_vpc&quot; &quot;Main&quot; {            # Creates VPC<br>  cidr_block       = var.main_vpc_cidr # CIDR block 10.0.0.0/24<br>  instance_tenancy = &quot;default&quot;<br> }</pre><p>(I’m going to include my variables.tf file after to avoid going back and forth during this documentation)</p><p>Next step create an Internet Gateway and attach it to the VPC. This is necessary because I wanted to have two webservers which require internet access:</p><pre>#Create Internet Gateway and attach it to VPC<br>resource &quot;aws_internet_gateway&quot; &quot;IGW&quot; { <br>  vpc_id = aws_vpc.Main.id              # uses ID of the VPC created<br>  <br>    tags = {                            #creates name in AWS<br>    Name = &quot;Pro22IGW&quot;<br>  }<br>}</pre><p>The “tags” line creates a name for the resource so that when it is built by Terraform in AWS, you can readily identify the resource in question.</p><p>After this it’s time for the subnets which exist inside of the VPC. First I created the two <strong>public subnets</strong>:</p><pre>resource &quot;aws_subnet&quot; &quot;publicsubnet1&quot; { <br>  vpc_id     = aws_vpc.Main.id<br>  cidr_block = var.public_subnets # CIDR block of public subnets<br>  <br>    tags = {                     # Name of Subnet in AWS<br>    Name = &quot;Pro22PublicSub1&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;publicsubnet2&quot; { <br>  vpc_id     = aws_vpc.Main.id<br>  cidr_block = var.public_subnets # CIDR block of public subnets<br>  <br>    tags = {<br>    Name = &quot;Pro22PublicSub2&quot; # Name of Subnet in AWS<br>  }<br>}</pre><p><strong>Private Subnets</strong>:</p><pre>resource &quot;aws_subnet&quot; &quot;privatesubnet1&quot; {<br>  vpc_id     = aws_vpc.Main.id<br>  cidr_block = var.private_subnets # CIDR block of private subnets<br>  <br>    tags = {<br>    Name = &quot;Pro22PrivateSub1&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;privatesubnet2&quot; {<br>  vpc_id     = aws_vpc.Main.id<br>  cidr_block = var.private_subnets # CIDR block of private subnets<br>  <br>    tags = {<br>    Name = &quot;Pro22PrivateSub2&quot;<br>  }<br>}</pre><p>Similar to attaching an internet gateway to the VPC, you would attach a NAT gateway to the private subnets in order to allow them access to the internet. Public Subnets don’t need this and have access as long as the VPC does and the security group attached allows traffic and everything is routed properly. In this case though one isn’t needed because the RDS database does not require internet access. I still set this up as if it did in order to display how.</p><p>NAT Gateway:</p><pre>resource &quot;aws_eip&quot; &quot;nateIP&quot; {<br>  vpc = true<br>}<br>Creating the NAT Gateway using subnet_id and allocation_id<br>resource &quot;aws_nat_gateway&quot; &quot;NATgw&quot; {<br>  allocation_id = aws_eip.nateIP.id<br>  subnet_id     = aws_subnet.publicsubnet1.id<br>  <br>  tags = {<br>    Name = &quot;Pro22NatGW&quot;<br>  }<br>}</pre><p>*Note the NAT Gateway requires an EIP or Elastic IP to work, this is created first and then the id is used in the creation of the NAT Gatweay*</p><p>Next I needed route tables to make sure the public subnets and private have their traffic organized.</p><pre>resource &quot;aws_route_table&quot; &quot;PublicRT&quot; { # Creating RT for Public Subnet<br>  vpc_id = aws_vpc.Main.id<br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot; # Internet access via Internet Gateway<br>    gateway_id = aws_internet_gateway.IGW.id<br>  }<br>    tags = {<br>    Name = &quot;PublicRT&quot;<br>  }<br>}<br>#Route table for Private Subnets<br>resource &quot;aws_route_table&quot; &quot;PrivateRT&quot; { # Creating RT for Private Subnet<br>  vpc_id = aws_vpc.Main.id<br>  route {<br>    cidr_block     = var.all_access_cidr # Internet access via NAT Gateway<br>    nat_gateway_id = aws_nat_gateway.NATgw.id<br>  }<br>    tags = {<br>    Name = &quot;PrivateRT&quot;<br>  }<br>}</pre><p>These two route tables make sure traffic is routed appropriately. In the case of the public subnet through the VPC’s Internet Gateway, and for the private through the NAT Gateway.</p><p>I then had to associate each of the four subnets with the route tables I created:</p><pre><br>#Public Subnet Route Table Association<br>resource &quot;aws_route_table_association&quot; &quot;PublicRTassociation1&quot; {<br>  subnet_id      = aws_subnet.publicsubnet1.id<br>  route_table_id = aws_route_table.PublicRT.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;PublicRTassociation2&quot; {<br>  subnet_id      = aws_subnet.publicsubnet2.id<br>  route_table_id = aws_route_table.PublicRT.id<br>}<br>#Private Subnet Route Table Association<br>resource &quot;aws_route_table_association&quot; &quot;PrivateRTassociation1&quot; {<br>  subnet_id      = aws_subnet.privatesubnet1.id<br>  route_table_id = aws_route_table.PrivateRT.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;PrivateRTassociation2&quot; {<br>  subnet_id      = aws_subnet.privatesubnet2.id<br>  route_table_id = aws_route_table.PrivateRT.id</pre><p>For reference, any time you see “resource” directly following it in quotation marks is what resource is being created and in the second second set of quotation marks is it’s name in terraform. The ID used as an argument is the (resource).(resource name).id. This allows Terraform to pass a value that is created in the very same code.</p><p>Even though we’ve created the pathway for traffic, we need to create customized security groups for both the Webservers (Public Subnet) and Database (Private Subnet). These function as firewalls and provide more specific restrictions on traffic. With Security groups you can select which ports you want to allow traffic through.</p><p><strong>Webserver Security Group:</strong></p><pre>#Create a security group for WebTier/Webservers<br>resource &quot;aws_security_group&quot; &quot;WebTierSG&quot; {<br>  vpc_id      = aws_vpc.Main.id<br><br>  ingress { #SSH traffic<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = var.all_access_cidr<br>  }<br>  <br>  ingress { #HTTP traffic<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = var.all_access_cidr<br>  }<br><br>  ingress { #HTTPS traffic<br>    from_port   = 443<br>    to_port     = 443<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = var.all_access_cidr<br>  }<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = var.all_access_cidr<br>  }<br>}</pre><p>The ingress rule is allowing traffic in from the ports specified. Port 22 is for SSH which allows me to access whatever’s behind this security group through Secure Shell. This is not strictly needed but it allows anyone with key pair for the instance to connect via terminal. This allows for some troubeshooting in case something goes wrong. *The CIDR block for the SSH ingress rule should be my IP, allowing only access from my IP*. As written it would allow anyone with the key pair to access. My IP was changing while doing this project so I cleared all traffic. Port 80 and 443 are for HTTP and HTTPS respectively, and I allowed all traffic of those types through. This allows access to the webserver through the browser as long as you have the public IP of the instance. The Egress rule allows all outbound traffic from the instance.</p><p>Database Security Group:</p><pre>#Create Databse Security group<br>resource &quot;aws_security_group&quot; &quot;DatabaseSG&quot; {<br>  vpc_id = aws_vpc.Main.id<br><br>ingress { <br>    from_port   = 3306           # Port for MYSQL Traffic<br>    to_port     = 3306<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = var.all_access_cidr<br>  }<br>}</pre><p>The database security group has a lot less steps and only needs port 3306 access which is for MYSQL protocol traffic. MYSQL is a database management system and the one I chose for my relational database. No egress is required from this private database.</p><p><strong>Creating the Webservers:</strong></p><pre>#Create Instance for Apache Webserver<br>resource &quot;aws_instance&quot; &quot;Pro22Webtier1&quot; {<br>  ami           = var.ami<br>  instance_type = var.instance_type<br>  user_data     = file(&quot;apache.sh&quot;)<br><br>  vpc_security_group_ids = [aws_security_group.WebTierSG.id]<br><br>  tags = {<br>    Name = &quot;Pro22Webtier1&quot;<br>  }<br>}<br>#Create second Instance for Apache Webserver<br>resource &quot;aws_instance&quot; &quot;Pro22Webtier2&quot; {<br>  ami           = var.ami<br>  instance_type = var.instance_type<br>  user_data     = file(&quot;apache.sh&quot;)<br><br>  vpc_security_group_ids = [aws_security_group.WebTierSG.id]<br><br>  tags = {<br>    Name = &quot;Pro22Webtier2&quot;<br>  }<br>}</pre><p>*Note that security group line which associates the security groups already made with the webserver instances*</p><p>Any value that has “var.x” is pointing to a value in the variables.tf with “x” name. This code creates two instances using AMI’s or Amazon Machine Images. These images signify the operating system of the instance, in this case it’s Amazon Linux 2. The instance type indicates the size. The user_data field is where the magic happens, this tells the instance to run the file that I isin quotes as soon as the instance starts. This file contains the code to start an Apache Webserver. *Note apache.sh is a separate file you create (touch apache.sh), that is referenced in Main.tf. This file must be there with your main.tf and variables.tf files.</p><p><strong>Apache.sh:</strong></p><pre>#!/bin/bash<br>sudo yum update -y<br>sudo yum install -y httpd.x86_64<br>sudo systemctl start httpd.service<br>#sudo systemctl enable httpd.service</pre><p>I commented out the “enable” line because that makes sure the webserver automatically starts with each subsequent instance start (unless explicitly stopped). This can be a great thing but if you, like me, delete your code to something that doesn’t actually work to test other servers; you may waste hours trying to figure out why the server still appears despite all your changes.</p><p><strong>Database Creation</strong></p><pre>#Create RDS MYSQL database<br>resource &quot;aws_db_instance&quot; &quot;Pro22RdsDB&quot; {<br>  allocated_storage    = 10<br>  #db_name              = &quot;mydb&quot;<br>  engine               = &quot;mysql&quot;<br>  engine_version       = &quot;5.7&quot;<br>  instance_class       = &quot;db.t2.micro&quot;<br>  username             = &quot;22DB&quot;<br>  password             = &quot;22DBpass&quot;<br>  parameter_group_name = &quot;default.mysql5.7&quot;<br>  skip_final_snapshot  = true<br>  db_subnet_group_name    = &quot;${aws_subnet.privatesubnet1.id}&quot;<br>  vpc_security_group_ids  = [aws_security_group.DatabaseSG.id]<br>  <br>  tags = {<br>    Name = &quot;Pro22RdsDB&quot;<br>  }<br>}</pre><p>Ok I’ll admit most of this is hardcoded and I know what I said but this is just for the database and this is long. Here I created the RDS(Relational database service) MYSQL databse. The arguments are the paramters of the databse, such as storage size, engine(type), instance_class(size) and username and password which is mandatory. This then had to be associated with the Database security group I created earlier.</p><p>As promised<strong> Variables.tf:</strong></p><pre>variable &quot;main_vpc_cidr&quot; {<br>    type    = string<br>    default = &quot;10.0.0.0/24&quot;<br>}<br>variable &quot;public_subnets&quot; {<br>    type    = string<br>    default = &quot;10.0.0.128/26&quot;<br>}<br>variable &quot;private_subnets&quot; {<br>    type    = string<br>    default = &quot;10.0.0.192/26&quot;<br>}<br>variable &quot;all_access_cidr&quot; {<br>    type    = string<br>    default = &quot;0.0.0.0/0&quot;<br>variable &quot;instance_type&quot; {<br>  type    = string<br>  default = &quot;t2.micro&quot;<br>}<br>variable &quot;ami&quot; {<br>  type    = string<br>  default = &quot;ami-069aabeee6f53e7bf&quot;<br>}<br></pre><p>There is one more file needed a providers.tf file, which provides the following information:</p><pre>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><p>This specifies the region everything is built in and that it’s using AWS. You can include this information in the main.tf file also but its more prudent to have it in it’s own location. In my case I built this AWS architecture in Terraform inside of AWS Cloud9. I did not need to provide access and secret keys as I was already within my AWS account. If I was not I would need a file with AWS account info in order for me to be able to build this and the file would look more like:</p><pre>terraform {<br>      required_providers {<br>         aws = {<br>         source = &quot;hashicorp/aws&quot;<br>         version = &quot;= 3.74.2&quot;<br>        }<br>     }<br>  }<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>  access_key = &quot;*&quot;<br>  secret_key = &quot;*&quot;<br>}</pre><p>This top you can find in Terraform provider documentation and the bottom is your personal AWS information.</p><p>Now that all the code is written all that is left is to run the following Terraform commands to build this.</p><ol><li><strong>terraform init</strong>: intializes terraform and requires a main.tf file, this must be run in the same directory as main.tf/ variables.tf etc.</li><li><strong>terraform validate: </strong>checks to see that the configuration is valid. This will find any errors in the code or formatting issues that create a terraform error</li><li><strong>terraform plan</strong>: “creates an execution plan, which lets you preview the changes that <strong>Terraform plans</strong> to make to your infrastructure”. Terraform will detail what will be created or taken away depending on what updates you’ve made</li><li><strong>terraform apply</strong>: runs the code applies all the commands, this is the “pressing the button”.</li></ol><p>After entering terraform apply in the Cloud 9 console I had to wait about three minutes for all of the resources to be created. The result was all of my resources existing on AWS and public access through the browser to my websevers, good to go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47e04d71e2eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using a Python Script to Store File Data in a Dictionary]]></title>
            <link>https://kyleantonioheadley.medium.com/using-a-python-script-to-store-file-data-in-a-dictionary-5304584935e6?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/5304584935e6</guid>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[dictionary]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 03:27:37 GMT</pubDate>
            <atom:updated>2023-02-15T03:27:37.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kC26ZOEQtiEizBsJX3PGBg.jpeg" /></figure><p>The goal was to create a Python script that can list the files and file sizes in the working directory. The script must then also be able to store this information in a dictionary and print this dictionary. This dictionary would need to have several key/value pairs to display the name, size, and file path for each file found.<br>In Python, lists and dictionaries have very specific meanings:</p><p><strong>Lists</strong>:<em> used to store multiple items in a single variable. Lists are created using square brackets</em></p><pre>listofitems = [&#39;Name&#39;, &#39;Size&#39;, &#39;Path&#39;]<br>print(listofitems)</pre><p>In the above example, if you were to run that code, the list would be printed or returned as [‘Name’, ‘Size’, ‘Path’]. A list named ‘listofitems’ was created with those three items as its contents.</p><p><strong>Dictionaries</strong>: <em>used to store data values in key: value pairs. Dictionaries are written with curly brackets and have keys and values</em></p><pre>dictionaryofitems = {<br>          &#39;name&#39;:Python,<br>          &#39;size&#39;:50,<br>          &#39;path&#39;:home/<br>}</pre><p>In this above example, ‘name’ would be the key and Python would be the value. The code would not actually work because the variables aren’t defined but this is what the dictionary itself would look like.</p><h3>My solution:</h3><p>The first step was for me to find a way for Python to record the files in the current working directory. For this, I used the method <strong>os.listdir()</strong>, which lists all the files and directories located in the path used as the parameter (in between the parentheses). If there is no argument it uses the current working directory, which I needed. In order for any os module methods to work we have to import os, allowing access to os methods.</p><pre>import os<br>print(os.listdir())</pre><p>This code imports the os and prints the files in the current working directory to the terminal. This is what I used to make sure the method worked.</p><h3>For Loop with variables</h3><p>The next step was to define variables for the ‘for’ loop. I was able to tell a ‘for’ loop was needed because I wanted data listed that depended on other data. This dictionary I needed to create has static key/value pairs like {‘name’ : xxx, ‘size’ : xxx, “path” : xxx}. The actual data will change depending on which file is being looked at. “For each file, create this key/value pair”. The variables I defined were <strong>wd</strong> , <strong>wdfiles</strong>, and <strong>path</strong>. These represent the working directory, files in the working directory, and path (full file location) respectively.</p><pre>wd = os.getcwd()<br>wdfiles = os.listdir()<br>path = os.path.join(wd, file)</pre><p>By defining these variables, whenever the wd, wdfiles, or path variables are used in the ‘for’ loop, the script will use the associated method in its place, including parameters.</p><pre>for file in wdfiles:<br>    path = os.path.join(wd, file)<br>    mydict = { <br>        &#39;name&#39; : file, <br>        &#39;size&#39; : os.path.getsize(file),<br>        &#39;path&#39; : path<br>    }<br>    print(mydict)</pre><p>This For loop’s function is relatively straightforward,</p><p>For each file in wdfiles(<em>defined with a method that calls a list of working directory files</em>):</p><ul><li>path is defined as a method that joins the name of the working directory and file name (creating an absolute path)</li><li>create a dictionary named mydict, with a key of ‘name’ paired with the value file (listing the name). A key of ‘size’ paired with a value of a method that gets the size of the file. A key of ‘path’ paired with the value path which is defined earlier. The quotes around the keys indicate that the literal word should be used and it isn’t a variable.</li><li>Print this new dictionary to the terminal.</li></ul><p>Full code:</p><pre>#Access os module, define variables for Working directory and files in directory<br>import os<br>wd = os.getcwd()<br>wdfiles = os.listdir()<br>#for loop with path defined and dictionary created<br>for file in wdfiles:<br>    path = os.path.join(wd, file)<br>    mydict = { <br>        &#39;name&#39; : file, <br>        &#39;size&#39; : os.path.getsize(file),<br>        &#39;path&#39; : path<br>    }<br>    print(mydict)</pre><p>Note that the path variable has to be defined within the loop as opposed to the other variables. This is because the file variable is created in the first line of the loop and used for the path variable.</p><p>In my working directory where these four files exist:</p><p>[‘README.md’, ‘.c9’, ‘ChevyWoodsPython’, ‘test.py’]</p><p>the script returns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*f5J6XfrXoVIGptDs1ea6pw.png" /></figure><p>Mission accomplished</p><p>*This code does work to get the name, size, and path of the files in my working directory and list them in a dictionary. The method I used to pull the files, pulls both files and directories. My working directory contained only files so it made no difference. If someone were to use this code in a working directory that had directories, it would list those in the dictionary as well with name, size, and path.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5304584935e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Snapchat Uses AWS to Improve Business]]></title>
            <link>https://kyleantonioheadley.medium.com/how-snapchat-uses-aws-to-improve-business-cd88fd6870bf?source=rss-8e1b55171a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd88fd6870bf</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[snapchat]]></category>
            <dc:creator><![CDATA[Kyle Headley]]></dc:creator>
            <pubDate>Fri, 13 Jan 2023 07:45:01 GMT</pubDate>
            <atom:updated>2023-01-13T07:45:01.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjjgy7Teq13G7goAnrVO1w.jpeg" /></figure><p>As I delve further into the AWS(Amazon Web Services) world with <a href="https://www.linkedin.com/company/68995539">Level Up In Tech</a>, understanding its real-world applications becomes increasingly important. Most of us are probably familiar with Snapchat. In case you aren’t, it has been one of the most popular apps for sending visual media and text messages and an app I’ve used extensively over the years.</p><p>Although the app’s main feature from inception has been content disappearing after it’s viewed, the model has since transitioned to embrace users storing media with things like Snapchat memories. In 2016 dealing with increased demand, Snapchat adopted AWS for its storage. AWS was the perfect solution to increase storage without having to sacrifice performance. Snap first used Amazon S3 Standard-IA or Infrequent Access. This storage service is designed for data not often accessed (every 1–2 months) but with fast access when needed.</p><p>In 2021 Amazon launched its S3 Glacial Instant retrieval service, designed to be accessed even less frequently (quarterly) but available immediately when needed. Snapchat was able to save on costs by switching to this AWS service as it fits their needs more closely. Snapchat even contributed to developing this service by providing input while it was being designed. A perfect example of AWS and its services meeting a company’s exact needs to reduce costs and improve or maintain performance.</p><p>Summer 2022 marked the complete transfer of all data to the S3 Glacial Instant retrieval service, more than 2 exabytes or 1.5 trillion files. This switch has saved them tens of millions of dollars in storage costs and improved file access speed (latency) in some regions by 20–30 percent. With the users not negatively impacted in any way by the migration, the AWS switch was a complete success. AWS continues to be an optimal solution for many businesses, with the flexibility to handle various demands. Seeing how such a widely used app utilizes AWS is a reminder of just how valuable it is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd88fd6870bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>