<?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 Madison Hersom on Medium]]></title>
        <description><![CDATA[Stories by Madison Hersom on Medium]]></description>
        <link>https://medium.com/@madison.hersom?source=rss-148de943bc14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QwkRuXfZiz6qokBP</url>
            <title>Stories by Madison Hersom on Medium</title>
            <link>https://medium.com/@madison.hersom?source=rss-148de943bc14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:59:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madison.hersom/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[Introduction to CI/CD Pipelines]]></title>
            <link>https://medium.com/@madison.hersom/introduction-to-ci-cd-pipelines-20a075e43a10?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/20a075e43a10</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[cicd]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 22:07:09 GMT</pubDate>
            <atom:updated>2024-03-22T17:37:52.726Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27epofCZsY1KsWMoP02vJA.png" /><figcaption><a href="https://solidstudio.io/blog/ci-cd-pipelines">https://solidstudio.io/blog/ci-cd-pipelines</a></figcaption></figure><h3>Definitions</h3><p><strong>What is Continuous Integration/Continuous Delivery</strong> (<strong>CI/CD)? </strong>CI/CD is a tool that helps software teams send out code updates quicker and with fewer problems. It’s made up of rules (ways of doing things) and tools that make sure the changes made to the code actually work and get sent out (deployed) smoothly. CI/CD not only helps automate releases, but also helps with quality tests.</p><p><strong>Why is CI/CD important? </strong>These tools automate the build, test, and deployment processes, which allows development teams to deliver high-quality software quickly and efficiently. Key benefits of CI/CD are listed below:</p><ol><li>Faster Time to Market</li><li>Increased Productivity</li><li>Improved Code Quality</li><li>Reduced Risk</li><li>Consistency and Standardization</li></ol><h3>Use Case</h3><p>Create a CI/CD pipeline utilizing GitHub Actions. This pipeline should build and deploy a Nginx image to Docker Hub. The Docker file should outline creating a custom html webpage.</p><h3>Prerequisites</h3><p>The assumption is being made that you have some sort of means to connect to Docker. I will be using the following services to walk through this use case</p><ol><li>AWS EC2 Instance</li><li>Visual Studio Code (VS Code) with Docker installed and SSH Remote connection</li><li>GitHub account</li><li>Docker Hub Account</li></ol><h3>GitHub Preparation</h3><ol><li>First, we will need to create a new repository in GitHub. You will want to ensure that the repository is private. Later, we will add Docker Hub credentials that should not be publicly viewable.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPIqAPWP5L9HDwLGx296lg.png" /></figure><p>2. Next, navigate to Settings &gt; Secrets and Variables &gt; Actions. Create a repository secret for the Docker Hub account username and another for the password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qaUN8RLXNqS_HDbCuHfdZA.png" /></figure><p>3. Within VS code, you will need to remotely connect via SSH to your EC2 instance. Once connected, you will want to create a directory to house your GitHub Actions pipeline and then create a subdirectory. I created a directory called “gha” for GitHub Actions and a subdirectory named “pipeline”.</p><pre># Create a directory named &#39;gha&#39;<br>mkdir gha<br><br># Change into the &#39;gha&#39; directory<br>cd gha<br><br># Create a subdirectory named &#39;pipeline&#39; inside the &#39;gha&#39; directory<br>mkdir pipeline<br><br># List the contents of the current directory (&#39;gha&#39;) to verify the changes<br>ls</pre><p>Along the lefthand side, VS Code will have the option to clone a repository. Click the button and copy the repository URL into the field. Follow the prompts until you have completed cloning your repository to VS Code. It will prompt you to open a new window like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*qNCsirOddqFgbSNp4YqWow.png" /></figure><h3>Building the Pipeline</h3><ol><li>Within VS Code, create a new folder called “.github/workflows”. Within this folder, create a yaml file. I am going to name my “nginx_pipeline.yaml”. This is the only file that needs to be housed within the workflow folder.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*27g3ZxQuUZJ-LzRISqahcA.png" /></figure><p>2. Next, we will create a Dockerfile and input the below contents</p><pre># Base image that we want to use<br>FROM nginx:latest <br><br># Copy our custom html webpage<br>COPY index.html /usr/share/nginx/html<br><br># Expose our ports<br>EXPOSE 80 </pre><p>3. Next, create an index.html file and input the below contents. Customize how you see fit.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Testing for the Pipeline&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Welcome to my new custom webpage&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>4. Saving the more difficult file for last, let’s navigate back to the nginx_pipeline.yaml file. The formatting is crucial in this file type. Pay close attention to your spacing and indentation.</p><pre>name: Build and Deploy Nginx to Docker Hub<br> <br>on:<br>  push:<br>    branches: [main]<br><br>jobs:<br>  build-and-push:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout Repository<br>        uses: actions/checkout@v4.1.1<br><br>      - name: Log in to Docker Hub<br>        uses: docker/login-action@v3<br>        with:<br>          username: ${{ secrets.DOCKERHUB_USERNAME }}<br>          password: ${{ secrets.DOCKERHUB_PASSWORD }}<br><br>      - name: Build and Push Nginx image<br>        uses: docker/build-push-action@v5.2.0<br>        with:<br>          push: true<br>          tags: ${{ secrets.DOCKERHUB_USERNAME }}/cicd_test:latest<br><br>  test:<br>    needs: build-and-push<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4.1.1<br><br>      - name: Install Dependencies and Verify<br>        run: |<br>          sudo apt-get update<br>          sudo apt-get install -y curl<br>          curl --version<br>          echo &quot;curl -f http://localhost&quot;</pre><h3>Executing the Pipeline</h3><ol><li>Now we have created all of the necessary files, within VS Code, we will want to navigate to the terminal to run the “git add .” command. The period (.) represents the current directory. This will allow you to stage all changes within the current directory for the next commit.</li></ol><p>2. Run the “git commit” command. You can add a message to describe what you’re doing or changing. This would come in handy if you had to make any changes.</p><p>3. Lastly, run the “git push” command.</p><pre># Stage changes for commit<br>git add .<br><br># Commit changes with a descriptive message<br>git commit -m &quot;Your commit message here&quot;<br><br># Push committed changes to the remote repository<br>git push</pre><p>4. Navigate to your GitHub repository. You should see the folder and files we created in VS Code within your GitHub repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*nYDA3GipKiH7nlHecKax0g.png" /></figure><p>5. Navigate to the GitHub Actions tab within your repository. You should see a successful commit.</p><p>I had an issue with tag formatting. I kept receiving an error saying: invalid reference format. First, I checked that I had the proper Docker Hub repository name listed in my .yaml file. Second, I tried just removing the tag line just to see if the remaining content worked. I learned that was required and had to input it back in. I tried a few other adjustement to pinpoint where my error was. I finally realized that I made a silly error with my Docker Hub username secret. Ultimately, all I had to do was update my secret in GitHub to the CORRECT username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*eR3ZxGeyo_5FcCwQhR0Oag.png" /></figure><p>6. Lastly, navigate to your Docker Hub account. You should find the image in your repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgTkBWK6Rnf6raZWiTsNDg.png" /></figure><h3>Cleanup</h3><p>Once you are done working on this use case, ensure you shut down your AWS EC2 instance. This will prevent costs from accruing on your account.</p><h3>Conclusion</h3><p>In this article, we walked through how to set up a CI/CD pipeline utilizing GitHub Actions.</p><h3>Helpful References</h3><ul><li><a href="https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions">Understanding GitHub Actions - GitHub Docs</a></li><li><a href="https://github.com/actions/checkout">GitHub - actions/checkout: Action for checking out a repo</a></li><li><a href="https://github.com/docker/build-push-action">GitHub - docker/build-push-action: GitHub Action to build and push Docker images with Buildx</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20a075e43a10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Two-Tier Network with Terraform]]></title>
            <link>https://medium.com/@madison.hersom/creating-a-two-tier-network-with-terraform-89b955e81578?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/89b955e81578</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 01:30:47 GMT</pubDate>
            <atom:updated>2024-03-05T20:52:03.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OUWO3ZVOxtmForf7" /><figcaption>Photo by <a href="https://unsplash.com/@christinhumephoto?utm_source=medium&amp;utm_medium=referral">Christin Hume</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Use Case</h3><p>In this article, we will create a highly available two-tier AWS architecture containing the following:</p><ol><li>Custom VPC</li><li>Two Public Subnets for the Web Server Tier</li><li>Two Private Subnets for the RDS Tier</li><li>Route Tables</li><li>A Linux EC2 Instance to host an Apache web server in each public web tier subnet</li><li>One RDS MySQL Instance (micro) in the private RDS subnets</li><li>Security Groups properly configured for needed resources ( web servers, RDS)</li></ol><h3>Prerequisites</h3><ol><li>AWS Free Tier Account</li><li>Basic AWS Knowledge (EC2, Auto Scaling Groups, Security Groups, S3 etc.)</li><li>AWS Cloud9 Environment (or another Integrated development environment)</li></ol><h3>Prep Work</h3><p>Navigate to Cloud9 or another IDE. Create a main.tf file and a variable.tf file.</p><p>Ensure your main.tf file has the following provider blocker, or you can create a separate provider.tf file.</p><pre># Configure the AWS Provider<br>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}</pre><h3>Setting up the Two Tier Network</h3><p>In order to create a two tier network, we need to create a configuration to include setting up the VPC, private and public subnets, private and public route tables, internet gateway, NAT gateway, and elastic IP address. Then we also need to ensure these items are all associated together appropriately.</p><p>My main.tf file included the following for the VPC configuration:</p><pre>#Create VPC <br>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block       = var.vpc_cidr<br>  instance_tenancy = &quot;default&quot;<br><br>  tags = {<br>    Name = &quot;main&quot;<br>  }<br>}<br><br>#Create subnets in the VPC for Web Server Tier<br>resource &quot;aws_subnet&quot; &quot;subnet-public-1&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = var.pub_subnet1_cidr<br>  map_public_ip_on_launch = true # it makes this a public subnet<br>  availability_zone       = &quot;us-east-1a&quot;<br>  tags = {<br>    Name = &quot;subnet-public-1&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;subnet-public-2&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = var.pub_subnet2_cidr<br>  map_public_ip_on_launch = true # it makes this a public subnet<br>  availability_zone       = &quot;us-east-1b&quot;<br>  tags = {<br>    Name = &quot;subnet-public-2&quot;<br>  }<br>}<br><br>#Create subnets in the VPC for RDS Tier<br>resource &quot;aws_subnet&quot; &quot;subnet-private-1&quot; {<br>  vpc_id            = aws_vpc.main.id<br>  cidr_block        = var.priv_subnet1_cidr<br>  availability_zone = &quot;us-east-1a&quot;<br>  tags = {<br>    Name = &quot;subnet-private-1&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;subnet-private-2&quot; {<br>  vpc_id            = aws_vpc.main.id<br>  cidr_block        = var.priv_subnet2_cidr<br>  availability_zone = &quot;us-east-1b&quot;<br>  tags = {<br>    Name = &quot;subnet-private-2&quot;<br>  }<br>}<br><br>#Create Internet Gateway<br>resource &quot;aws_internet_gateway&quot; &quot;internet_gw&quot; {<br>  vpc_id = aws_vpc.main.id<br><br>  tags = {<br>    Name = &quot;main_igw&quot;<br>  }<br>}<br><br>#Internet Gateway Attachment <br>resource &quot;aws_internet_gateway_attachment&quot; &quot;internet_gw&quot; {<br>  internet_gateway_id = aws_internet_gateway.internet_gw.id<br>  vpc_id              = aws_vpc.main.id<br>}<br><br># Create Public Route Table<br>resource &quot;aws_route_table&quot; &quot;public_route_table&quot; {<br>  vpc_id = aws_vpc.main.id<br><br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.internet_gw.id<br>  }<br><br>  tags = {<br>    Name = &quot;public-route-table&quot;<br>  }<br>}<br><br>#Route Table Association for Public Subnet 1<br>resource &quot;aws_route_table_association&quot; &quot;public_subnet1_association&quot; {<br>  subnet_id      = aws_subnet.subnet-public-1.id<br>  route_table_id = aws_route_table.public_route_table.id<br>}<br><br>#Route Table Association for Public Subnet 2<br>resource &quot;aws_route_table_association&quot; &quot;public_subnet2_association&quot; {<br>  subnet_id      = aws_subnet.subnet-public-2.id<br>  route_table_id = aws_route_table.public_route_table.id<br>}<br><br>#Create Elastic IP<br>resource &quot;aws_eip&quot; &quot;nat_eip&quot; {<br>  vpc = true<br>  tags = {<br>    Name = &quot;main_eip&quot;<br>  }<br>}<br><br>#Create NAT Gateway<br>resource &quot;aws_nat_gateway&quot; &quot;priv_NAT_gw&quot; {<br>  allocation_id = aws_eip.nat_eip.id<br>  subnet_id     = aws_subnet.subnet-public-1.id<br>  depends_on    = [aws_internet_gateway.internet_gw]<br>}<br><br>#Create Private Route Table<br>resource &quot;aws_route_table&quot; &quot;private_route_table&quot; {<br>  vpc_id = aws_vpc.main.id<br><br>  route {<br>    cidr_block     = &quot;0.0.0.0/0&quot;<br>    nat_gateway_id = aws_nat_gateway.priv_NAT_gw.id<br>  }<br><br>  tags = {<br>    Name = &quot;private-route-table&quot;<br>  }<br>}<br><br>#Route Table Association for Private Route Table Subnet 1<br>resource &quot;aws_route_table_association&quot; &quot;private_subnet1_association&quot; {<br>  subnet_id      = aws_subnet.subnet-private-1.id<br>  route_table_id = aws_route_table.private_route_table.id<br>  depends_on     = [aws_route_table.private_route_table]<br>}<br><br>#Route Table Association for Private Route Table Subnet 2<br>resource &quot;aws_route_table_association&quot; &quot;private_subnet2_association&quot; {<br>  subnet_id      = aws_subnet.subnet-private-2.id<br>  route_table_id = aws_route_table.private_route_table.id<br>  depends_on     = [aws_route_table.private_route_table]<br>}</pre><p>My variable.tf file included the following for the VPC configuration:</p><pre>variable &quot;aws_region&quot; {<br>  description = &quot;AWS region&quot;<br>  type        = string<br>  default     = &quot;us-east-1&quot;<br>}<br><br>variable &quot;vpc_cidr&quot; {<br>  description = &quot;CIDR block for the VPC&quot;<br>  type        = string<br>  default     = &quot;10.0.0.0/16&quot;<br>}<br><br>variable &quot;pub_subnet1_cidr&quot; {<br>  description = &quot;CIDR block for Public Subnet1&quot;<br>  type        = string<br>  default     = &quot;10.0.1.0/24&quot;<br>}<br><br>variable &quot;pub_subnet2_cidr&quot; {<br>  description = &quot;CIDR block for Public Subnet2&quot;<br>  type        = string<br>  default     = &quot;10.0.2.0/24&quot;<br>}<br><br>variable &quot;priv_subnet1_cidr&quot; {<br>  description = &quot;CIDR block for Private Subnet1&quot;<br>  type        = string<br>  default     = &quot;10.0.3.0/24&quot;<br>}<br><br>variable &quot;priv_subnet2_cidr&quot; {<br>  description = &quot;CIDR block for Private Subnet2&quot;<br>  type        = string<br>  default     = &quot;10.0.4.0/24&quot;<br>}</pre><p>After building my configuration files, I wanted to test that this worked appropriately. I ran the below five commands and then navigated to my AWS console to ensure that I created everything successfully.</p><p>You’ll want to keep these five commands handy throughout this article.</p><pre># Initialize Terraform working directory, downloading any necessary plugins<br>terraform init<br><br>#Format your Terraform configuration files<br>terraform fmt<br><br>#Check the syntax and validity of your Terraform configuration<br>terraform validate<br><br># Generate and show an execution plan without making any changes<br>terraform plan<br><br># Apply the changes described in the Terraform execution plan<br>terraform apply</pre><h3>Setting up the Security Group</h3><p>Next, I wanted to create a new security group for my web server and for my database. We will later associate it with the Auto Scaling Group instances and RDS database.</p><p>My main.tf file included the following for the Security Group configuration:</p><pre>#Security Groups properly configured for needed resources ( web servers, RDS)<br><br># Create Web Server Security Group<br>resource &quot;aws_security_group&quot; &quot;web_sg&quot; {<br>  name        = &quot;web_sg&quot;<br>  description = &quot;Security group for web sever instances&quot;<br>  vpc_id      = aws_vpc.main.id<br><br>  # Inbound Http, Https, and SSH<br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  ingress {<br>    from_port   = 443<br>    to_port     = 443<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  # Outbound Internet Access<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br><br># Create Database Security Group<br>resource &quot;aws_security_group&quot; &quot;db_sg&quot; {<br>  name        = &quot;db_sg&quot;<br>  description = &quot;Security group for database instances&quot;<br>  vpc_id      = aws_vpc.main.id<br><br>  # Inbound MySQL and SSH<br>  ingress {<br>    from_port       = 3306 #RDS MySQL port<br>    to_port         = 3306<br>    protocol        = &quot;tcp&quot;<br>    security_groups = [aws_security_group.web_sg.id]<br>  }<br><br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  # Outbound Internet Access<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><p>You will want to test your configuration by running the Terraform commands previously mentioned (init, plan, apply). Validate in your AWS Console that you created a new security group with the desired inbound and outbound rules.</p><h3>Setting up the Web Server</h3><p>Next, we need to create an autoscaling group for the Linux EC2 instances to host an Apache web server in each public web tier subnet.</p><p>My main.tf file included the following for the VPC configuration:</p><pre>#Launch an EC2 Instance with your choice of web server in each public web tier subnet<br><br># Create Launch Template<br>resource &quot;aws_launch_template&quot; &quot;lt-asg&quot; {<br>  name                   = &quot;lt-asg&quot;<br>  image_id               = var.linux_ami<br>  instance_type          = var.instance_type<br>  key_name               = var.key_pair_name<br>  vpc_security_group_ids = [aws_security_group.web_sg.id]<br>  user_data = base64encode(&lt;&lt;EOF<br>    #!/bin/bash<br>    yum update -y<br>    yum install -y httpd<br>    systemctl start httpd<br>    systemctl enable httpd<br>EOF<br>)<br>}<br><br># Create Auto Scaling Group<br>resource &quot;aws_autoscaling_group&quot; &quot;web_asg&quot; {<br>  desired_capacity    = var.min_instances<br>  max_size            = var.max_instances<br>  min_size            = var.min_instances<br>  vpc_zone_identifier = [aws_subnet.subnet-public-1.id, aws_subnet.subnet-public-2.id]<br><br>  # Attach Launch Template to Auto Scaling Group<br>  launch_template {<br>    id      = aws_launch_template.lt-asg.id<br>    version = &quot;$Latest&quot; # or specify the version you want<br>  }<br>}</pre><p>My variable.tf file included the following for the VPC configuration:</p><pre>variable &quot;instance_type&quot; {<br>  description = &quot;EC2 instance type&quot;<br>  default     = &quot;t2.micro&quot;<br>}<br><br>variable &quot;min_instances&quot; {<br>  description = &quot;Minimum number of instances in Auto Scaling Group&quot;<br>  default     = 2<br>}<br><br>variable &quot;max_instances&quot; {<br>  description = &quot;Maximum number of instances in Auto Scaling Group&quot;<br>  default     = 2<br>}<br><br>variable &quot;linux_ami&quot; {<br>  description = &quot;ID of the Linux AMI to use&quot;<br>  default     = &quot;ami-0e731c8a588258d0d&quot;<br>}<br><br>variable &quot;ingress_ports&quot; {<br>  description = &quot;List of ingress ports&quot;<br>  type        = list(number)<br>  default     = [80, 443]<br>}<br><br>variable &quot;key_pair_name&quot; {<br>  description = &quot;Name of the key pair useds&quot;<br>  type        = string<br>  default     = &quot;ABC_KP&quot; # Replace with your default key pair name<br>}</pre><p>You will want to test your configuration by running the Terraform commands previously mentioned (init, plan, apply). Validate in your AWS Console that you created an autoscaling group with instances hosting the Apache web server.</p><h3>Setting up the RDS Database</h3><p>Lastly, we will want to create a RDS MySQL Instance (micro) in the private RDS subnets.</p><p>My main.tf file included the following for the RDS MySQL configuration:</p><pre>#One RDS MySQL Instance (micro) in the private RDS subnets ***NEED to update***<br><br>resource &quot;aws_db_subnet_group&quot; &quot;mysql_subnet_group&quot; {<br>  name       = &quot;my-rds-subnet-group&quot;<br>  subnet_ids = [aws_subnet.subnet-private-1.id, aws_subnet.subnet-private-2.id]<br>}<br><br>resource &quot;aws_db_instance&quot; &quot;mysql_rds_instance&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.t3.micro&quot;<br>  username             = &quot;username&quot;<br>  password             = &quot;password&quot;<br>  parameter_group_name = &quot;default.mysql5.7&quot;<br>  skip_final_snapshot  = true<br>  db_subnet_group_name    = aws_db_subnet_group.mysql_subnet_group.name<br>  depends_on           = [aws_db_subnet_group.mysql_subnet_group]<br>}</pre><p>You will want to test your configuration by running the Terraform commands previously mentioned (init, plan, apply). Validate in your AWS Console that you created a RDS MySQL database.</p><h3>Cleanup</h3><p>You can tear down everything you built with one simple command. This will shut everything down for us that was set up.</p><pre># Destroy the infrastructure defined in the Terraform configuration<br>terraform destroy</pre><h3>Conclusion</h3><p>In this article, we walked through how to:</p><ol><li>Create a custom VPC with two Public Subnets for the Web Server Tier and two Private Subnets for the RDS Tier</li><li>Create route tables and associate appropriately</li><li>Create a Linux EC2 Instance to host an Apache web server in each public web tier subnet</li><li>Create a RDS MySQL Instance (micro) in the private RDS subnets</li><li>Create Security Groups</li></ol><h3>Helpful References</h3><ul><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/vpc">Terraform Registry</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/subnet">Terraform Registry</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route_table">Terraform Registry</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route_table_association">Terraform Registry</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance">Terraform Registry</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/db_instance#example-usage">Terraform Registry</a></li><li><a href="https://github.com/mhersom/terraform-luit/tree/97fff0d3b2c567b6989dc3a0846b4cc8003d0caf/Week%2023%20Project">terraform-luit/Week 23 Project at 97fff0d3b2c567b6989dc3a0846b4cc8003d0caf · mhersom/terraform-luit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89b955e81578" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Terraform to Create a Web Server on AWS]]></title>
            <link>https://medium.com/@madison.hersom/using-terraform-to-create-a-web-server-on-aws-68f8079bf21e?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/68f8079bf21e</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[auto-scaling-groups]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 21:54:48 GMT</pubDate>
            <atom:updated>2024-02-24T14:18:09.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n8bQgZ5sb3H6E7Nu" /><figcaption>Photo by <a href="https://unsplash.com/@cookiethepom?utm_source=medium&amp;utm_medium=referral">Cookie the Pom</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Use Case</h3><p>An e-commerce company needs to handle a surge in traffic during the holiday season. The company wants to ensure that their website remains available and responsive to customers even during high traffic periods.</p><p>The project can be used to launch an Auto Scaling group that spans two subnets in the default VPC, ensuring high availability and fault tolerance. The Auto Scaling group will automatically scale up or down based on traffic, ensuring that the website remains responsive to customers at all times.</p><p>To ensure that the instances in the Auto Scaling group are secure, a security group is created that allows traffic from the internet and associates it with the instances. Additionally, a script is included in the user data to launch an Apache web server, ensuring that the website is available to customers.</p><p>To ensure that the Auto Scaling group has the appropriate capacity, it is set to have a minimum of two instances and a maximum of five. This ensures that the website can handle a surge in traffic during the holiday season, while also minimizing costs during periods of low traffic.</p><p>Finally, to ensure that the infrastructure is reliable and can be easily managed, an S3 bucket is created and set as the remote backend for Terraform. This ensures that the infrastructure is versioned and can be easily rolled back if necessary.</p><p>To complete this, we will need to complete the following tasks:</p><ol><li>Launch an Auto Scaling Group that spans 2 subnets in the default VPC</li><li>Create a security group that allows traffic from the internet and associate it with the Auto Scaling Group instances.</li><li>Include a script in the EC2 instance user data to launch an Apache web server. The Auto Scaling Group should have a minimum of 2 and a maximum of 5.</li><li>To verify everything is working check the public IP addresses of the two instances. Manually terminate one of the instances to verify that another one spins up to meet the minimum requirement of 2 instances.</li><li>Create an S3 bucket and set it as your remote backend.</li></ol><h3>Prerequisites</h3><ol><li>AWS Free Tier Account</li><li>Basic AWS Knowledge (EC2, Auto Scaling Groups, Security Groups, S3 etc.)</li><li>AWS Cloud9 Environment (or another Integrated development environment)</li></ol><h3>Prep Work</h3><p>Navigate to Cloud9 or another IDE. Create a main.tf file and a variable.tf file.</p><p>Ensure your main.tf file has the following provider blocker, or you can create a separate provider.tf file.</p><pre># Configure the AWS Provider<br>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}</pre><h3>Setting up the VPC and Subnets</h3><p>To ensure my existing state aligned with the use case requirements, I needed to make a few adjustments to my network setup. My current setup already had a default VPC already created. My below configurations ensured that I created two new subnets within my existing default VPC. During this process my new subnets were added to the existing route table and internet gateway settings.</p><p>My main.tf file included the following for the VPC configuration:</p><pre># Get information about the default VPC<br>data &quot;aws_vpcs&quot; &quot;default&quot; {<br>  filter {<br>    name   = &quot;isDefault&quot;<br>    values = [&quot;true&quot;]<br>  }<br>}<br><br># Create subnets in the VPC<br>resource &quot;aws_subnet&quot; &quot;subnet-public-1&quot; {<br>  vpc_id                  = data.aws_vpcs.default.ids[0]<br>  cidr_block              = var.subnet1_cidr<br>  map_public_ip_on_launch = true # it makes this a public subnet<br>  availability_zone       = &quot;us-east-1a&quot;<br>  tags = {<br>    Name = &quot;subnet-public-1&quot;<br>  }<br>}<br>resource &quot;aws_subnet&quot; &quot;subnet-public-2&quot; {<br>  vpc_id                  = data.aws_vpcs.default.ids[0]<br>  cidr_block              = var.subnet2_cidr<br>  map_public_ip_on_launch = true # it makes this a public subnet<br>  availability_zone       = &quot;us-east-1b&quot;<br>  tags = {<br>    Name = &quot;subnet-public-2&quot;<br>  }<br>}</pre><p>My variable.tf file included the following for the VPC configuration:</p><pre># CIDR block for Subnet1 variable<br>variable &quot;subnet1_cidr&quot; {<br>  description = &quot;CIDR block for Subnet1&quot;<br>  type        = string<br>  default     = &quot;172.31.1.0/24&quot;<br>}<br><br># CIDR block for Subnet2 variable<br>variable &quot;subnet2_cidr&quot; {<br>  description = &quot;CIDR block for Subnet2&quot;<br>  type        = string<br>  default     = &quot;172.31.2.0/24&quot;<br>}</pre><p>After building my configuration files, I wanted to test that this worked appropriately. I ran the below five commands and then navigated to my AWS console to ensure that I didn’t create another VPC and that I created 2 new subnets associated with my default VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEWWGUEHMaT_PAWtnUeY9Q.png" /><figcaption>This confirms that my Terraform configuration worked and created two new subnets under my default VPC.</figcaption></figure><p>You’ll want to keep these five commands handy throughout this article.</p><pre># Initialize Terraform working directory, downloading any necessary plugins<br>terraform init<br><br>#Format your Terraform configuration files<br>terraform fmt<br><br>#Check the syntax and validity of your Terraform configuration<br>terraform validate<br><br># Generate and show an execution plan without making any changes<br>terraform plan<br><br># Apply the changes described in the Terraform execution plan<br>terraform apply</pre><h3>Setting up the Security Group</h3><p>Next, I wanted to create a new security group for my web server. We need to ensure that the security group allows traffic from the internet (ports 80 and 443). We will later associate it with the Auto Scaling Group instances.</p><p>My main.tf file included the following for the Security Group configuration:</p><pre># Create Security Group<br>resource &quot;aws_security_group&quot; &quot;web_sg&quot; {<br>  name        = &quot;web_sg&quot;<br>  description = &quot;Security group for web instances&quot;<br>  vpc_id      = data.aws_vpcs.default.ids[0]<br><br># Inbound Http, Https, and SSH<br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  ingress {<br>    from_port   = 443<br>    to_port     = 443<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  # Outbound Internet Access<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><p>You will want to test your configuration by running the Terraform commands previously mentioned (init, plan, apply). Validate in your AWS Console that you created a new security group with the desired inbound and outbound rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*TIs3d2aiNptooeNKbhAvxA.png" /><figcaption>This confirms that my Terraform configuration worked and created a new Security Group.</figcaption></figure><h3>Setting up the Auto Scaling Group</h3><p>Now, we need to launch an Auto Scaling Group that spans two subnets in the default VPC.</p><p>Per the case, we also want to set up the Auto Scaling Group to have minimum of 2 and a maximum of 5 instances. This will help adjusting to traffic. We also need to associate it with our new security group.</p><p>You will notice that we need to create a new file for variables.</p><p>My main.tf file included the following for the Auto Scaling Group configuration:</p><pre># Create Launch Template<br>resource &quot;aws_launch_template&quot; &quot;lt-asg&quot; {<br>  name                   = &quot;lt-asg&quot;<br>  image_id               = var.linux_ami<br>  instance_type          = var.instance_type<br>  key_name               = var.key<br>  vpc_security_group_ids = [aws_security_group.web_sg.id]<br><br>  user_data = filebase64(&quot;${path.module}/apache_install.sh&quot;)<br>}<br><br># Create Auto Scaling Group<br>resource &quot;aws_autoscaling_group&quot; &quot;web_asg&quot; {<br>  desired_capacity    = var.min_instances<br>  max_size            = var.max_instances<br>  min_size            = var.min_instances<br>  vpc_zone_identifier = [aws_subnet.subnet-public-1.id, aws_subnet.subnet-public-2.id]<br><br>  # Attach Launch Template to Auto Scaling Group<br>  launch_template {<br>    id      = aws_launch_template.lt-asg.id<br>    version = &quot;$Latest&quot; # or specify the version you want<br>  }<br>}</pre><p>My variable.tf file included the following for the Auto Scaling Group configuration:</p><pre># ID of the Linux AMI to use variable<br>variable &quot;linux_ami&quot; {<br>  description = &quot;ID of the Linux AMI to use&quot;<br>  default     = &quot;ami-0e731c8a588258d0d&quot;<br>}<br><br># EC2 instance type variable<br>variable &quot;instance_type&quot; {<br>  description = &quot;EC2 instance type&quot;<br>  default     = &quot;t2.micro&quot;<br>}<br># Key variable<br>variable &quot;key&quot; {<br>  default = &quot;INPUT YOUR KEY NAME&quot;<br>  type    = string<br>}<br># Minimum number of instances in Auto Scaling Group variable<br>variable &quot;min_instances&quot; {<br>  description = &quot;Minimum number of instances in Auto Scaling Group&quot;<br>  default     = 2<br>}<br># Maximum number of instances in Auto Scaling Group variable<br>variable &quot;max_instances&quot; {<br>  description = &quot;Maximum number of instances in Auto Scaling Group&quot;<br>  default     = 5<br>}</pre><p>My Apache install file contained this scripting:</p><pre>#!/bin/bash<br><br># Update the system packages<br>yum update -y<br><br># Install Apache (httpd) web server<br>yum install -y httpd<br><br># Start the Apache web server<br>systemctl start httpd<br><br># Enable Apache to start on system boot<br>systemctl enable httpd</pre><p>You will want to test your configuration by running the Terraform commands previously mentioned (init, plan, apply). Validate in your AWS Console that you created a new launch template and autoscaling group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*wXMqVVbNoCXqZf5Osz21-w.png" /><figcaption>This confirms that my Terraform configuration worked and created a new Launch Template.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*29r0YZdmgzQWjuJywDApkA.png" /><figcaption>This confirms that my Terraform configuration worked and created a new Auto Scaling Group.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6DZb-e05PMl99UUj5ljzw.png" /><figcaption>This confirms that my Terraform configuration worked and the Auto Scaling Group spun up the two desired instances.</figcaption></figure><h3>Setting up the S3 Bucket</h3><p>We want to create an S3 bucket and set it as the remote backend. To complete this, I input the resource block in the main.tf to create a new bucket.</p><p>My main.tf file included the following for the S3 bucket configuration:</p><pre># Create an S3 bucket for Apache artifacts<br>resource &quot;aws_s3_bucket&quot; &quot;apache_bucket&quot; {<br>  bucket = &quot;apache-bucket-mh-123123123&quot;<br>  acl    = &quot;private&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*PHskRPKT97uQ_pEEqaWo9Q.png" /><figcaption>This confirms that my Terraform configuration worked and created a new bucket.</figcaption></figure><p>I tested that my configuration updates actually created a new bucket, and then I created a new file for the backend setup. Your bucket will need to be created before you can configure the backend setup.</p><p>backend.tf file:</p><pre># Configure the backend for storing Terraform state in the Apache S3 bucket<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket  = &quot;apache-bucket-mh-123123123&quot;<br>    key     = &quot;terraform.tfstate&quot;<br>    region  = &quot;us-east-1&quot;<br>    encrypt = true<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*gEXcW2Po9Je8XqG0p8_EWQ.png" /><figcaption>This confirms that my Terraform configuration worked and my state file is stored in my S3 bucket.</figcaption></figure><h3>Testing</h3><p>To verify that everything is working correctly, the public IP addresses of the two instances are checked. This will ensure our Apache web server installed and started correctly.</p><p>You can also check in the command line:</p><pre># Check the status of the Apache web server using systemd<br>systemctl status httpd</pre><p>To test your Auto Scaling group, terminate one of the instances manually terminated to verify that another instance will spin up to meet the minimum requirement of two instances.</p><h3>Cleanup</h3><p>You can tear down everything you built with one simple command. This will shut everything down for us that was set up.</p><pre># Destroy the infrastructure defined in the Terraform configuration<br>terraform destroy</pre><h3>Conclusion</h3><p>In this article, we walked through how to:</p><ol><li>Launch an Auto Scaling Group that spans 2 subnets in the default VPC</li><li>Create a security group and associate it with the Auto Scaling Group</li><li>Include a script in the EC2 instance user data to launch an Apache web server.</li><li>Create an S3 bucket and set it as the remote backend.</li></ol><h3>Helpful References</h3><ul><li><a href="https://registry.terraform.io/?ajs_aid=c1d5b8a3-9211-4067-9ba3-1df78be0bab4&amp;product_intent=terraform">Terraform Registry</a></li><li><a href="https://github.com/mhersom/terraform-luit/tree/main/Week%2022%20Project_2">terraform-luit/Week 22 Project_2 at main · mhersom/terraform-luit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68f8079bf21e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Terraform]]></title>
            <link>https://medium.com/@madison.hersom/introduction-to-terraform-77e4ee1cf560?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e4ee1cf560</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 16:44:55 GMT</pubDate>
            <atom:updated>2024-02-24T14:07:41.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*qDt5Wl_W1rAj-AOyzN9ejQ.png" /></figure><h3>Use Case</h3><p>Your team would like to start using Jenkins as their CI/CD tool to create pipelines for DevOps projects. They need you to create the Jenkins server using Terraform so that it can be used in other environments and so that changes to the environment are better tracked. In this use case, we will have all our code in a single main.tf file (known as a monolith) with hardcoded data.</p><h3>Definitions</h3><p><strong>What is Terraform?</strong> Terraform is an infrastructure as code tool that lets users define both resources in human-readable configuration files that users can version, reuse, and share. The main benefits of this functionality is: consistency, repeatability, time-savings, and increase efficiency.</p><p><strong>What is Jenkins? “</strong>Jenkins is a self-contained, open source automation server which can be used to automate all sorts of tasks related to building, testing, and delivering or deploying software.”</p><h3>Prerequisites</h3><ol><li>AWS Free Tier Account</li><li>Basic AWS Knowledge (EC2, Security Groups, S3 etc.)</li><li>Basic Terraform knowledge</li><li>AWS Cloud9 Environment (or another Integrated development environment)</li></ol><h3>Prep Work</h3><p>As a beginner to Terraform, I found it easier to figure out what I needed to do by running through the use case in a platform I was already familiar with…AWS Console. By running through this in the AWS Console first, it helped me figure out what I need to build out in the main.tf file for Terraform.</p><ol><li>Deploy 1 EC2 Instance in the Default VPC. Bootstrap the EC2 instance with a script that will install and start Jenkins. Ensure to set up the instance with the following criteria:</li></ol><ul><li>I am using the Ubuntu AMI. If you use Linux, you’ll need to revise the commands indicated below.</li><li>Create a new security group. We will want to revise the inbound rules later.</li><li>Under Advanced Details &gt; User Data, input the below code</li></ul><pre>#!/bin/bash<br><br>#Download Java 8. Jenkins requires Java 8 or later.<br>sudo apt install -y default-jre<br><br>#Download Jenkins GPG key<br>sudo wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -<br><br>#Add Jenkins repository to APT sources list<br>sudo sh -c &#39;echo deb http://pkg.jenkins.io/debian-stable binary/ &gt; /etc/apt/sources.list.d/jenkins.list&#39;<br><br>#Update package list<br>sudo apt update -y<br><br>#Install Jenkins<br>sudo apt install -y jenkins<br><br>#Start Jenkins service<br>sudo systemctl start jenkins<br><br># Enable Jenkins service to start on boot<br>sudo systemctl enable jenkins  </pre><p>2. Update the new Security Group so that it allows traffic on port 22 from “your IP” and allows traffic from port 8080.</p><p>3. Create a S3 bucket for the Jenkins Artifacts that is not open to the public.</p><h3>Building the EC2 Instance</h3><p>After walking through how to do this in the AWS Console, we can better understand what we need to actually input into our resource block. We will need to refer to the Terraform registry to help us determine the coding that we will need to use for creating the desired EC2 instance. The link I referenced is listed below. We will want to navigate to our IDE to begin our configuration build.</p><pre># Create an EC2 instance<br>resource &quot;aws_instance&quot; &quot;jenkins_instance&quot; {<br>  ami           = &quot;ami-0c7217cdde317cfec&quot; # Specify the desired AMI ID<br>  instance_type = &quot;t2.micro&quot;              # Specify the desired instance type<br><br>  key_name = &quot;[INSERT KEY PAIR NAME]&quot; # Specify the key pair name for SSH access<br><br>  vpc_security_group_ids = [aws_security_group.jenkins_sg.id]<br><br>  tags = {<br>    Name = &quot;Jenkins&quot;<br>  }<br><br>  user_data = &lt;&lt;-EOF<br>              #!/bin/bash<br>              sudo apt update -y<br>              sudo apt install -y default-jre<br>              wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -<br>              sudo sh -c &#39;echo deb http://pkg.jenkins.io/debian-stable binary/ &gt; /etc/apt/sources.list.d/jenkins.list&#39;<br>              sudo apt update -y<br>              sudo apt install -y jenkins<br>              sudo systemctl enable jenkins<br>              sudo systemctl start jenkins<br>              EOF<br><br>}</pre><p>You can also create a separate file to house your user data aka script to install Jenkins.</p><h3>Creating and Updating the Security Group</h3><p>We will need to refer to the Terraform registry to help us determine the coding that we will need to use for creating the desired security group. The link I referenced is listed below.</p><pre># Create a security group for Jenkins<br>resource &quot;aws_security_group&quot; &quot;jenkins_sg&quot; {<br>  name        = &quot;jenkins_sg&quot;<br>  description = &quot;Jenkins Security group&quot;<br><br>  # Allow SSH access for administration (replace with your IP address)<br>  ingress {<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;50.4.49.47/32&quot;] # Replace with your IP address<br>  }<br><br>  # Allow HTTP access to Jenkins web interface on port 8080<br>  ingress {<br>    from_port   = 8080<br>    to_port     = 8080<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;] # Allow access from any IP<br>  }<br><br>  # Allow HTTPS access to Jenkins web interface on ports 443 and 433<br>  ingress {<br>    from_port   = 443<br>    to_port     = 443<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;] # Allow access from any IP<br>  }<br><br>  # Allow all outbound traffic from the Jenkins instance<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot; # Allow all protocols<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><h3>Creating the S3 Bucket</h3><p>We will need to refer to the Terraform registry to help us determine the coding that we will need to use for creating the desired S3 bucket. The link I referenced is listed below.</p><pre># Create an S3 bucket for Jenkins artifacts<br>resource &quot;aws_s3_bucket&quot; &quot;jenkins_bucket&quot; {<br>  bucket = &quot;INPUT UNIQUE BUCKET NAME&quot; <br>  acl    = &quot;private&quot;<br>}</pre><p>Note: When I ran the “terraform validate”, the system advised that this block was deprecated, which means outdated. It suggested using “ aws_s3_bucket_acl resource” instead. I had to lean on some Google articles to get me through this roadblock. Eventually, I was able to find what I needed to resolve the errors being presented.</p><p>Another thing to note, ensure your bucket name is very specific, otherwise you’ll run into issues getting it created. It has to be unique.</p><pre># Create an S3 bucket for Jenkins artifacts<br>resource &quot;aws_s3_bucket&quot; &quot;jenkins_bucket&quot; {<br>  bucket = &quot;jenkins-bucket-mh-141414&quot;<br>}<br><br># Add ownership controls for the Jenkins S3 bucket<br>resource &quot;aws_s3_bucket_ownership_controls&quot; &quot;jenkins_ownership_controls&quot; {<br>  bucket = aws_s3_bucket.jenkins_bucket.id<br><br>  rule {<br>    object_ownership = &quot;BucketOwnerPreferred&quot;<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_acl&quot; &quot;jenkins-acl&quot; {<br>  bucket     = aws_s3_bucket.jenkins_bucket.id<br>  acl        = &quot;private&quot; # Set ACL to private to restrict public access<br>  depends_on = [aws_s3_bucket_ownership_controls.jenkins_ownership_controls]<br>}</pre><h3>Building the main.tf file in Cloud9</h3><p>In the Cloud9 environment, we will need to put all of these code blocks together in a main.tf file. Navigate to “File” and select “New File”. We will want to save the file and name it “main.tf”. The .tf indicator will ensure that the system recognizes it as a Terraform file.</p><p>We will need to start the file with the below code block. This block will tell Terraform that we are using AWS and not another cloud platform. It also will tell the system which region to create the resources in.</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}</pre><p>Now copy and paste all of the resource block information for the EC2, security groups, and bucket into the main.tf file.</p><p>Now I want to run a few commands to initialize and “spell check” what I’ve created thus far. These commands will check the syntax and validity of what is built.</p><pre># Initialize Terraform working directory, downloading any necessary plugins<br>terraform init<br><br>#Format your Terraform configuration files<br>terraform fmt<br><br>#Check the syntax and validity of your Terraform configuration<br>terraform validate</pre><p>When you run the “terraform validate” command, ensure you’re reading the output and make any revisions as instructed. Repeat this process until you get a success message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*Ula9Jc26fHJkMxAK8M0ctQ.png" /></figure><h3>Applying the main.tf File</h3><p>Next, we will want to execute commands that will build the resources. When you run “terraform plan”, the output will show you what will be built. This will not actually build out the resources. We need to run the “terraform apply” command to actually build out the resources. If you do not use the “auto-approve” version, you will need to manually input “yes” before the build will complete.</p><pre># Generate and show an execution plan without making any changes<br>terraform plan<br><br># Apply the changes described in the Terraform execution plan<br>terraform apply<br><br># Apply with auto-approval<br>terraform apply --auto-approve</pre><p>It will take a few moments for the resources to be built. As the system is processing, you can navigate to the AWS Console and watch as your resources are getting built out.</p><h3>Testing</h3><p>You can check the service status, by connecting to your instance and running the below command. The output will confirm if Jenkins is active.</p><pre># Check Jenkins service status<br>sudo systemctl status jenkins</pre><p>Verify that you can reach your Jenkins install via port 8080 in your browser. To complete this, copy the Jenkins instance public IP address and paste into the browser. You will want to follow this formatting: “IP_ADDRESS:8080”.</p><p>You should be presented this screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*l2UY95RxzkYTuuS1XS9yBg.png" /></figure><h3>Cleanup</h3><p>You can tear down everything you built in the main.tf file with one simple command. This will shut everything down for us that was set up with the main.tf file.</p><pre># Destroy the infrastructure defined in the Terraform configuration<br>terraform destroy</pre><h3>Conclusion</h3><p>In this article, we walked through how to utilize the Terraform registry to build out a main.tf file to build resources such as: EC2 instance, security group, and S3 buckets.</p><h3>Helpful Resources</h3><ol><li><a href="https://www.jenkins.io/doc/book/installing/linux/">https://www.jenkins.io/doc/book/installing/linux/</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance">https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group">https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket">https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket</a></li><li><a href="https://github.com/mhersom/terraform-luit/blob/main/Week21_main.tf">https://github.com/mhersom/terraform-luit/blob/main/Week21_main.tf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e4ee1cf560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Services in Docker Swarm]]></title>
            <link>https://medium.com/@madison.hersom/how-to-create-services-in-docker-swarm-0a6ca00c485f?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a6ca00c485f</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[swarm]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 00:21:11 GMT</pubDate>
            <atom:updated>2024-02-21T16:05:48.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mTa0FKt94fubB5wK" /><figcaption>Photo by <a href="https://unsplash.com/@justin_morgan?utm_source=medium&amp;utm_medium=referral">Justin Morgan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Definitions</h3><p><strong>What is a frontend network? </strong>Think of the frontend network as the user facing interface. For example, a website.</p><p><strong>What is a backend network? </strong>Think of the backend network as the server that could house the database, or a means to store logic that runs and supports the website.</p><h3>Use Case</h3><p>Level Up Publications is an online publication that posts blogs about the hottest updates and trends in IT. Level Up Publications is in the process of transitioning its web infrastructure to a containerized environment using Docker Swarm due to the rapid growth of its reader base.</p><p>For a company like Level Up Publications, the adoption of Docker Swarm provides the agility to respond to rapidly changing news cycles. It can also efficiently serve a growing readership, ensuring that the publication’s website remains available and responsive, even as traffic fluctuates. Moreover, by improving the security of the system, Docker Swarm helps the publication protect its valuable content and data, as well as maintain the trust of its readership.</p><p>In this article we will walk through how to complete the following:</p><ol><li>Deploy a 3 node Docker Swarm cluster</li><li>Create 2 networks: one for frontend and another for backend</li><li>Create a MySQL service associated with the backend network, with only 1 replica. You will want to make the database service resilient and its data persistent across container restarts by using Docker Volumes.</li><li>Create the WordPress service associated with the frontend network, with 3 replicas. We will want to use port 80. This will need to be accessible from the browser. It will need to be associated with the MySQL service</li></ol><h3>Prerequisites</h3><p>The assumption is being made that you have some sort of means to connect to Docker. I will be using the following services to walk through this use case.</p><ol><li>AWS Free Tier Account</li><li>AWS EC2 Instance for remotely connecting to VS Studio Code</li><li>Visual Studio Code (VS Code) with Docker installed</li><li>SSH Remote connection</li></ol><p>Note: I already set up an environment to connect one EC2 Instance to Visual Studio Code to work with Docker. This article walks through how to set up a Docker Swarm and services.</p><h3>Deploy a 3 node Docker Swarm cluster</h3><p>Walk through the steps outlined in the below article to set up your 3 node Docker Swarm.</p><p><a href="https://medium.com/@madison.hersom/setting-up-docker-swarm-1d2720241776">Setting Up Docker Swarm</a></p><h3>Create Networks</h3><p>Before we are able to create our services, we will want to create the two networks that we will associate with our services. Run the three below commands in VS Code in Node 1, aka the manager node.</p><pre>#create frontend network<br>sudo docker network create --driver overlay frontend-network<br><br>#create backend network<br>sudo docker network create --driver overlay backend-network<br><br>#list networks<br>sudo docker network ls</pre><h3>Create a MySQL Service</h3><p>Per the use case, we need to create a MySQL service associated with the backend network with only 1 replica, and we need to set up a volume to store the data to. We will want to create the volume before creating the service. Be sure to run these commands in Node 1, aka the manager node.</p><pre>#create volume<br>sudo docker volume create mysql-data<br><br>#list volumes<br>sudo docker volume ls<br><br>#create MySQL Service<br>sudo docker service create --name mysql-service --replicas 1 --network backend-network --mount type=volume,source=mysql-data,target=/var/lib/mysql -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=wordpress mysql:latest</pre><p>Breaking down the MySQL command:</p><ul><li>sudo docker service create: This is the base command needed to build the service</li><li>name: This will name the service whatever we tell it to (e.g. mysql-service)</li><li>replicas: This will spin up as many replicas that we indicate (e.g. 1)</li><li>network: This will associate the network we name (e.g. backend-network)</li><li>mount: This will mount the volume to the service/container</li><li>-e MYSQL_ROOT_PASSWORD=password: The “-e” is to set an environment variable. This is part of the MySQL setup. It is advised to input a root password when creating the service.</li><li>-e MYSQL_DATABASE=wordpress: The “-e” is to set an environment variable. This will create a database upon starting the service/container.</li><li>mysql:latest: This is identifying the desired service and version.</li></ul><p>After you run the above commands, it may take a few moments for processing. Once it is complete, the system should output a “Service converged”.</p><h3>Create a WordPress Service</h3><p>Per the use case, we need to create a WordPress service that is associated with the frontend network, has 3 replicas, and uses port 80. This service will need to be accessible from the browser. This service will need to be associated with the MySQL service.</p><pre>#create WordPress service<br>sudo docker service create --name wordpress-service --replicas 3 --network frontend-network -p 80:80 wordpress:latest</pre><p>Breaking down the WordPress command:</p><ul><li>sudo docker service create: This is the base command needed to build the service</li><li>name: This will name the service whatever we tell it to (e.g. wordpresss-service)</li><li>replicas: This will spin up as many replicas that we indicate (e.g. 3)</li><li>network: This will associate the network we name (e.g. frontend-network)</li><li>-p 80:80: This will publish the desired port and map from the host to the service</li><li>wordpress:latest: This is identifying the desired service and version.</li></ul><p>After you run the above commands, it may take a few moments for processing. Once it is complete, the system should output a “Service converged”.</p><h3>Testing</h3><p>Run the below commands to view the services recently created. You will want to see “Desired State” showing running.</p><pre>#list all services<br>sudo docker service ls     <br> <br>#check the WordPress service      <br>sudo docker service ps wordpress-service  <br><br>#check the MySQL service<br>sudo docker service ps mysql-service</pre><p>Next, we will want to test access via the internet browser. To navigate to user page for WordPress, copy the AWS EC2 instance’s public IP address and add “:80” into your internet browser. For example IP.ADDRESS:80. You should be presented with a login screen. You should see a screen similar to below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ofblhTovE4Js6flTTHy4OQ.png" /></figure><p>That’s it! We successfully completed the requirements of the use case.</p><h3>Cleanup</h3><p>It is important to remember to clean up the items you created during this article, leave the swarm, and exit the ssh connection in each node. You will want to leave the manager swarm last.</p><pre>#remove services<br>sudo docker service rm mysql-service<br>sudo docker service rm wordpress-service<br><br>#remove networks<br>sudo docker network rm frontend-network<br>sudo docker network rm backend-network<br><br>#remove volume<br>sudo docker volume rm mysql-data<br><br>#leave the swarm<br>sudo docker swarm leave --force<br><br>#exit the ssh connection<br>exit</pre><p>It is also important to shut down your AWS EC2 instances when they aren’t being used.</p><h3>Conclusion</h3><p>In this article, we walked through how to set up a Swarm cluster, set up networks, and create services.</p><h3>Helpful Resources</h3><ul><li><a href="https://hub.docker.com/_/mysql">mysql - Official Image | Docker Hub</a></li><li><a href="https://hub.docker.com/_/wordpress">wordpress - Official Image | Docker Hub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a6ca00c485f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Docker Swarm]]></title>
            <link>https://medium.com/@madison.hersom/setting-up-docker-swarm-1d2720241776?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d2720241776</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-swarm]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 20:35:20 GMT</pubDate>
            <atom:updated>2024-02-21T15:56:13.144Z</atom:updated>
            <content:encoded><![CDATA[<h3>Setting Up a Docker Swarm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnHjjCFjCsKPy0FVDVoLgw.png" /></figure><h3>Definitions</h3><p><strong>What is Docker Swarm? </strong>Docker Swarm is called an orchestration management tool. This feature allows for management of clusters and scheduling for people who work with Docker. One of the main benefits of Docker Swarm is that it helps ensure high availability. For example, if a service becomes unhealthy, it will automatically bring up a new service to replace it.</p><p><strong>What is a node? </strong>A node is an instance of a Docker engine. There are worker nodes and manager nodes. These different nodes make up a Docker Swarm.</p><h3>Use Case</h3><p>Your company is new to using containers and has been having issues with containerized workloads failing for their global shipping application. The company is worried about additional potential data loss as they have no way to reschedule containers that are failing. The company wants to update their infrastructure and leverage the use of Docker Swarm so that data can be restored for the containers that are no longer in a healthy state. They will need a step-by-step guide on setting up a Swarm for their containerized workloads to assist with container orchestration.</p><p>The solution should include the use of a global service. Your Swarm should be able to launch the containers using a global service. A service is simply a group of containers of the same image that facilitates the scaling of applications. Your global shipping application will require the use of at least three networked hosts, which should be AWS EC2 Ubuntu 20.04 instances.</p><p>As a junior engineer, you are responsible for only configuring Docker Swarm and providing your team with a step-by-step guide of setting up the Swarm. Your swarm creation should include the following steps via your remote SSH terminal in Visual Studio Code:</p><ul><li>Installing Docker on all hosts</li><li>Verifying that Docker is in an active state</li><li>Change the host name on each node to identify the master node and the two worker nodes</li><li>Validating the worker nodes all share the same security group as the master node</li><li>Be sure to add your SSH key to each node</li><li>Running the necessary containers using the CLI</li><li>Creating the Docker Swarm using one master node and two worker nodes</li><li>Show your team members the status of the Docker nodes</li></ul><h3>Prerequisites</h3><p>The assumption is being made that you have some sort of means to connect to Docker. I will be using the following services to walk through this use case.</p><ol><li>AWS Free Tier Account</li><li>AWS EC2 Instance for remotely connecting to VS Studio Code</li><li>Visual Studio Code (VS Code) with Docker installed</li><li>SSH Remote connection</li></ol><p>Note: I already set up an environment to connect one EC2 Instance to Visual Studio Code to work with Docker. This article walks through how to set up a Docker Swarm.</p><h3>Creating the Backend Infrastructure</h3><ol><li>We will start with ensuring that we have three AWS EC2 Ubuntu 20.04 instances. Repeat the below steps to launch the three EC2 instances:</li></ol><ul><li>Name the instances something like Docker_Node1, Docker_Node2, and Docker_Node3</li><li>Select the Ubuntu 20.04 Amazon Machine Image</li><li>Ensure each instance is on the same Virtual Private Cloud (VPC).</li><li>Create a new key pair and name it Docker. Just ensure all instances are using the same key pair. Make sure you know where your key pair file downloaded to locally. We will need this later.</li><li>Create a new security group. The inbound rules should allow HTTP, HTTPS, and SSH from the “My IP” option under Source. We also want to add the VPC by copying the IPv4 CIDR from the VPC tied to the each instances and inputting into the field with the magnifying glass (shown below). Ensure all three instances are using the same security group.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xc9frVxTg5hxotnOd8bFrA.png" /></figure><p>It may take a minute for each instance to get up and running.</p><p>2. While the instances are getting started, we can navigate over to Visual Studio Code (VS Code) to create the configuration file. This configuration file will essentially allow us to connect the AWS EC2 instances to VS Code.</p><p>In VS Code, navigate to the .ssh folder. Depending on your setup, you may need to create a configuration file. The below commands will help accomplish this:</p><pre>#navigate to .ssh folder<br>cd .ssh<br><br>#view what files already exist<br>ls<br><br>#create config file <br>touch config<br><br>#file editor<br>vim config</pre><p>Next, we want to edit the config file. Copy and paste the below information into the config file. Next to HostName, we want to input the private IP address from each node. You can find this information on the AWS EC2 instances.</p><pre>Host node2<br>  HostName [Input PrivateIP]<br>  User ubuntu<br>  IdentityFile [input keypair file path]<br><br>Host node3<br>  HostName [Input PrivateIP]<br>  User ubuntu<br>  IdentityFile [input keypair file path]</pre><p>The IdentityFile is looking for where we have the keys stored. In order to get the locally stored key pair information onto our remote connection, open up the key pair file and copy the data within.</p><p>Run another touch command to create a new key pair file. Ensure the file name matches exactly. After running the vim command, paste the file information, save, and exit. Once the file is created and saved, run the chmod command. If you’re unsure of the file path, run the readlink command. Copy and paste the output next to the IdentityFile line for node 2 and node 3.</p><pre>#create key pair file<br>touch keypairfilename.pem<br><br>#update file<br>vim keypairfilename.pem<br><br>#update permissions<br>chmod 400 keypairfilename.pem<br><br>#find path of keypair<br>readlink -f keypairfilename.pem</pre><p>Note: Whenever you need to exit vim, press “esc”, then “:”, then “wq”.</p><h3>Docker Swarm Prep</h3><p>Next, we need to ensure that Docker is installed and is in an active state. We can do this by running the below “#install Docker” command. Complete this in the terminal on VS Code with the Docker_Node1 instance.</p><p>To make it easier on ourselves, we want to update the host name so that we can ensure we are in the correct node. To update the name, run the commands under “#change hostname”.</p><pre>#install Docker<br>curl -fsSL https://get.docker.com -o get-docker.sh<br>sh get-docker.sh<br><br>#check status of Docker<br>sudo docker info<br><br>#change hostname<br>sudo hostnamectl set-hostname node1<br>sudo reboot</pre><p>We want to connect to the Docker_Node2 EC2 instance in VS Code, install Docker, and update the host name to ensure we are working in the correct node. To complete this, you can run the below commands:</p><pre>#connect to node2<br>ssh node2<br><br>#install Docker<br>curl -fsSL https://get.docker.com -o get-docker.sh<br>sh get-docker.sh<br><br>#check status of Docker<br>sudo docker version<br><br>#change hostname<br>sudo hostnamectl set-hostname node2<br>sudo reboot</pre><p>To set up the third and final node, open another terminal within VS Code. We want to connect to the Docker_Node2 EC3 instance in VS Code. Then we want to install Docker and update the host name to ensure we are working in the correct node. Copy the commands above and replace the “2” with a “3” where appropriate.</p><p>Node 1 will be our master node. Node 2 and 3 will be the worker nodes. You can always use difference names for your host to be “manager” or “worker1”.</p><p>To see the host name updates, you may want to exit and reconnect to the nodes.</p><h3>Setting up the Swarm</h3><p>In Node 1, we want to input the below command. This will initialize, or begin, the swarm.</p><pre>sudo docker swarm init --advertise-addr [Input node1 Private IP]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w626_rGgekRa_1gZc1tWTA.png" /></figure><p>The output above literally gives us the exact command we need to run to get Node 2 and 3 added to the swarm. Note: we will need to add “sudo” to the front of this command. Copy the command into each terminal for Node 2 and 3 (shown below). This will complete the process for each node to join the swarm the manager (Node 1) created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*nHPa3qg6Xz5mxsvRcO1Cag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*RNuFM_BlktsduS22fzUaKQ.png" /></figure><p>Lastly, in the manager node (Node 1) check the status of each node.</p><pre>sudo docker node ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gYBS5NeqpwJR_rn4yOiug.png" /></figure><p>We can see above that each node is active. So, that’s it! We successfully set up a Docker Swarm with one manager node and two worker nodes.</p><h3>Cleanup</h3><p>It is important to remember to leave the swarm and exit the ssh connection in each node. Input the two below commands into each node. You will want to leave the manager swarm last.</p><pre>#leave the swarm<br>sudo docker swarm leave --force<br><br>#exit the ssh connection<br>exit </pre><p>It is also important to shut down your AWS EC2 instances when they aren’t being used to minimize costs.</p><h3>Conclusion</h3><p>In this article, we walked through how to create a globally accessible Docker Swarm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d2720241776" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker, Volumes, and Jenkins]]></title>
            <link>https://medium.com/@madison.hersom/docker-volumes-and-jenkins-29aafd7c6840?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/29aafd7c6840</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-volume]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 00:08:28 GMT</pubDate>
            <atom:updated>2024-02-21T15:13:21.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*D1bfUNt1dXy2_4tZxqQfbQ.png" /></figure><h3>Definitions</h3><p><strong>What is a Docker volume? </strong>A Docker volume is used when you want to persist data. To persist data is a fancy way to say that you can keep the data even after you remove a container.</p><h3>Use Case</h3><p>The main objective of this project at Level Up Solutions is to use Docker for creating and managing Jenkins containers, emphasizing the implementation of persistent volumes. This strategy aims to build a robust, scalable Continuous Integration and Continuous Deployment (CI/CD) pipeline, facilitating frequent and reliable deployment of software updates.</p><p>Using the command line interface (CLI), we will complete the following:</p><ol><li>Pull the Jenkins LTS image from Docker Hub.</li><li>Create a Docker volume for Jenkins to persist its data.</li><li>Run the container with the volume and correct port mapped to the container.</li><li>Retrieve the Admin password.</li><li>Login and create a new user.</li><li>Launch a new Jenkins container using the same volume and verify that the data has persisted by logging in as the newly created user.</li></ol><h3>Prerequisites to follow along:</h3><p>The assumption is being made that you have some sort of means to connect to Docker. I will be using the following services to walk through this use case.</p><ol><li>AWS EC2 Instance</li><li>Visual Studio Code (VS Code) with Docker installed</li><li>SSH Remote connection</li><li>Review the Docker introduction article if you need to cover more of the “basics”:</li></ol><p><a href="https://medium.com/@madison.hersom/introduction-to-docker-ad72bd95f9e4">Introduction to Docker</a></p><h3>Pull the Jenkins LTS image</h3><ol><li>Navigate to <a href="https://hub.docker.com/">https://hub.docker.com/</a> and search for the Jenkins LTS image</li><li>Within your IDE (e.g. VS Code), input the following command:</li></ol><pre>sudo docker pull jenkins/jenkins:lts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*z__nLdE9coxH-jBKXKe_uA.png" /></figure><h3>Create a Docker Volume</h3><p>Next, we will create the Docker volume:</p><pre>sudo docker volume create --name jenkins_data</pre><p>I’m going to pull the list of available volumes to check that I can locate the one that was just created:</p><pre>sudo docker volume ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*d9op0S7a7u5qnDlJK94L-w.png" /></figure><h3>Run the Container</h3><p>Now that we’ve pull the image down and created the desired volume, we can spin up the container. After running the container, I’m going to run another command to make sure I can see the newly created container.</p><pre>#run the container<br>sudo docker run -d -p 8080:8080 -p 50000:50000 -v jenkins_data:/var/jenkins_home --name jenkins_container jenkins/jenkins:lts<br><br>#lists containers<br>sudo docker ps -a</pre><h3>Retrieve the Admin password</h3><p>To retrieve the Admin password, we will need to walk through a few steps.</p><ol><li>We need to access the Bash shell:</li></ol><pre>sudo docker exec -it jenkins_container bash</pre><p>3. We need to locate the admin password that is saved in the secrets file. For the sake of showing each step, review the screenshot below. You can cd and ls as you work through the directories, but the commands immediately below will take you directly to the desired location.</p><pre>#this will take you to the correct file location<br>cd /var/jenkins_home/secrets/<br><br>#this will print the password we are looking for<br>cat initialAdminPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*0EGW0EzzEzdtG2121YszLA.png" /><figcaption>I redacted the actual password output. After running the cat command, copy the password that is output.</figcaption></figure><p>You can also locate the password by running the log command.</p><pre>sudo docker logs jenkins_container</pre><h3>Login and create a new user</h3><p>Before accessing Jenkins, navigate to AWS EC2 and open up your instance’s security group inbound rules. Ensure you have the following inbound rules set with the “MyIP” as the source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*tbWAyK-dZqGffRkA8DnuOA.png" /></figure><p>To navigate to user page for Jenkins, copy the AWS EC2 instance’s public IP address and add “:8080” into your internet browser. For example IP.ADDRESS:8080.</p><p>You should be directed to the login screen. Copy the password that we found previously and paste into the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*l2UY95RxzkYTuuS1XS9yBg.png" /></figure><p>You will be asked to install suggested plug-ins or to select your own. Select whichever option you’d like. For simplicity, I selected the suggested plug-in option. That process will take a minute or two to install.</p><p>Once complete, you will be directed to the below screen to create the first admin user. Ensure you remember the username and password as we will need it later. Input the desired information and click “Save and Continue.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*JTV9hNxCcSN4dGJNkIgv8A.png" /></figure><p>The next screen will display the instance configuration. Copy the Jenkins URL and save it for later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lnCn6lCTMOslmImI5WZJg.png" /><figcaption>My IP address is redacted.</figcaption></figure><p>Follow the prompts and you will then see the below screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*Rbvk_IpOvehftm_SCM2BVQ.png" /></figure><h3>Testing and Validation</h3><p>To test our set up, we need to launch a new Jenkins container using the same volume and verify that the data has persisted by logging in as the newly created user.</p><p>The whole purpose of a volume is to ensure data is available even if the container is no longer running. To fully test this volume works, I’m going to ensure my first container is stopped.</p><pre>#run the new container<br>sudo docker run -d -p 8080:8080 -p 50000:50000 -v jenkins_data:/var/jenkins_home --name jenkins_container2 jenkins/jenkins:lts<br><br>#stop the original container<br>sudo docker container stop [CONTAINER ID]<br><br>#lists containers<br>sudo docker ps -a</pre><p>Next, we need to navigate to the login page for Jenkins by copying the AWS EC2 instance’s public IP address and add “:8080” into the internet browser. For example IP.ADDRESS:8080. Input the admin credentials you created a few moments ago.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*CRJSsjlEE44xbM8Wi25Pwg.png" /></figure><p>If the volume is working as expected, then we should be able to login without any issues .</p><p>If successful, you should be able to login and see the page below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*H86WHZ5IKrY3JHtrxfJQWw.png" /></figure><h3>Cleanup</h3><p>Since this is just a tutorial, I’m going to do some clean up to free up space on my system. These are good commands to know when working with Docker. With the below commands, you only need to enter enough of the ID so that it’s unique.</p><pre>#stop container<br>sudo docker container stop [CONTAINER ID] <br><br>#remove container<br>sudo docker container rm [CONTAINER ID]<br><br>#remove image<br>sudo docker image rm [IMAGE ID]<br><br>#remove volume<br>sudo docker volume rm [VOLUME NAME]</pre><p>You can run “sudo docker ps -a”, “sudo docker image ls”, and “sudo docker volume ls” to ensure there isn’t anything remaining.</p><h3>Conclusion</h3><p>In this article, we completed the following:</p><ul><li>Pulled an image down from Docker Hub</li><li>Created a Docker Volume</li><li>Spun up a container with the volume and created another container to ensure data persisted</li><li>Retrieved credentials and created a new user</li></ul><h3>Helpful References:</h3><p><a href="https://hub.docker.com/_/jenkins">jenkins</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29aafd7c6840" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Docker]]></title>
            <link>https://medium.com/@madison.hersom/introduction-to-docker-ad72bd95f9e4?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad72bd95f9e4</guid>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[ubuntu]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 03:14:17 GMT</pubDate>
            <atom:updated>2024-02-21T15:07:23.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6HYxKGXo-MgUygG_" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Definitions</h3><p><strong>What is Docker? </strong>Docker is defined as an open platform for developing, shipping, and running applications. Docker enables you to separate your applications from your infrastructure so you can deliver software quickly. Docker offers developers a way to easily bundle their application and its essential components into one standardized package, aka containers.</p><p><strong>What is a Dockerfile? </strong>This is a text file that serves as the recipe or the instructions for your container. Within this text file, one would list all of the necessities to build an image with commands. This file is used to create a Docker Image. I imagine the Dockerfile as the recipe to create the cookie dough.</p><p><strong>What is a Docker Image? </strong>An image is a read-only template with instructions for creating a Docker container. This is what will build out the container. A Dockerfile builds an image and then an image is required to build a Docker container. Think of the image as the template. I imagine an image as the cookie cutter for the container. Once you cut the cookie dough with that cookie cutter, you can’t make any changes to the cookie unless you create a new cookie.</p><p><strong>What is a Docker Container? </strong>You can turn a Docker Image into a container by building or running it on the Docker Engine. These containers are standardized, executable components that contain application code. When you build a container, you’re creating a self-contained instance of the software. These are mutable, meaning you can make changes at runtime to better meet your needs. I imagine the container as the cookie with slight variations, such as sprinklers or frosting.</p><p><em>I realize my cookie metaphor might be a stretch, but maybe it’ll help you work out the differences and importance of each component.</em></p><p><strong>Why do we care about Docker and why is it used?</strong></p><ul><li>Consistency</li><li>Portability</li><li>Reproducibility</li><li>Scalability</li><li>Streamlined Deployment</li></ul><h3>Use Case</h3><p>Level Up Solutions is a dynamic technology company that offers innovative web solutions to its clients. As part of their software development process, they have decided to adopt containerization using Docker to streamline their web application deployment. Docker provides Level Up Solutions with a flexible and efficient way to package, distribute, and run their applications in isolated containers, ensuring consistency and portability across different environments.</p><p>Level Up Solutions can harness the benefits of Docker containers, including consistency, portability, isolation, reproducibility, version control, scalability, streamlined deployment, and improved collaboration. These advantages contribute to more efficient and reliable web application deployments, enhancing the overall development and deployment processes for the company.</p><p>We will walk through how to complete the following:</p><ul><li>Create a Docker Ubuntu container running detached and on port 80</li><li>Use BASH shell to update all packages within the container</li><li>Use BASH shell to install Apache2 on the Ubuntu container</li><li>Add a custom webpage</li><li>Verify you can reach the web server from your browser</li></ul><h3>Prerequisites to follow along:</h3><p>The assumption is being made that you have some sort of means to connect to Docker. I will be using the following services to walk through this use case.</p><ol><li>AWS EC2 Instance</li><li>Visual Studio Code (VS Code) with Docker installed</li><li>SSH Remote connection</li></ol><h3>Run a Docker Ubuntu Container</h3><p>In order to pull the Ubuntu image down from DockerHub and into my VS Code, I want to run the following command:</p><pre>sudo docker run -d -p 80:80 --name ubuntu_container ubuntu:latest /bin/bash -c<br> &quot;while true; do sleep 1; done&quot;</pre><p>Let’s breakdown the code. The use case asks us to run a Docker Ubuntu container running detached and on port 80, so we need the “-d” and “-p 80:80” to meet those requirements.</p><ul><li>sudo : This allows me to execute the command as the superuser. This gives me “special” permissions.</li><li>docker run : This will create and run the container based on the image.</li><li>-d : This flag means “detached”. The container will run in the background, which allows us to keep using the terminal after starting the container.</li><li>-p 80:80 : This flag helps map the ports between the host and container.</li><li>— name ubuntu_container : This flag allows me to name the container.</li><li>ubuntu:latest : This is the name of the Docker image. We are requesting to pull the latest version of this image.</li><li>/bin/bash -c “while true; do sleep 1; done” : This will start a Bash shell and execute a loop. This loop will sleep for 1 second indefinitely. This allows the container to run in the background processes thus keeping it “alive”.</li></ul><p><em>I was having issues getting my container to stay running and resorted to ChatGPT to help me discover another command. The “/bin/bash -c “while true; do sleep 1; done” suggestion resolved the error I was encountering.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*PeVmBTaKng2NEzGviinIhA.png" /><figcaption>You can see the container ID (starts with d31) is spit out after the command is executed.</figcaption></figure><h3>Upgrade/update all packages and install Apache2</h3><p>Using Bash shell, we will update all packages within the container and install Apache2 on the Ubuntu container. In order to do this, we will need to run the following command:</p><pre>sudo docker exec -it ubuntu_container bash</pre><p>Let’s breakdown the code:</p><ul><li>sudo : This allows me to execute the command as the superuser. This gives me “special” permissions.</li><li>docker exec : This allows me to execute commands inside a container.</li><li>-it : “i” stands for interactive and “t” stands for terminal. This is used to interact or access the container’s shell.</li><li>ubuntu_container : This is the name of the container.</li><li>bash : This initiates the interactive Bash shell within the container.</li></ul><p>The above command will open up the Bash terminal. Once the Bash terminal opens, you can input the following commands:</p><pre>#this will update the packages within the container<br>apt-get update<br><br>#this will upgrade the packages within the container<br>apt-get upgrade -y<br><br>#this will install the Apache2 service to the container<br>apt-get install apache2 -y <br><br>#this will start the Apache2 service<br>service apache2 start</pre><p>You can add “-y” to your commands if you want to automatically answer yes to prompts as the command executes.</p><p>All of the above commands should be run while in the Bash terminal. You should see “root” while in the terminal. Once all commands are run, type “exit” to exit the Bash shell.</p><p>To ensure that my Apache installation was successful, and the service was started, I copied the public IP address of my AWS EC2 instance into my internet browser. You should see something like the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Q61f7g8uSGbcWntPJM2SVg.png" /></figure><p>You can also ensure the service has been started by checking the status with the command below.</p><pre>#this will check the status of your Apache2 service<br>service apache2 status</pre><h3>Create a custom webpage</h3><p>Now that the container is updated and Apache2 is installed, we can create a custom webpage. You can create a custom webpage by creating an index.html file:</p><pre>#this command will create the file<br>touch index.html<br><br>#this command will open up the editing screen<br>vi index.html</pre><p>One the vi command is run, we want to press “i” to insert text into the file.</p><p>Copy and paste the below into the editor. Modify the text as you see fit.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Level Up in Tech Week 17 Project&lt;h1&gt;<br>    &lt;p&gt;This is a basic HTML webpage running inside a Docker container.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Once all edits have been made, to exit, you will need to press ESC. Then “:” and then “wq”. This will save the file and exit the editing terminal.</p><p>Since this file was not created within our actual container, we need to copy this file into the ubuntu container. Utilize the following command to do so.</p><pre>sudo docker cp index.html ubuntu_container:/var/www/html/index.html</pre><p><em>(I originally missed this copying step and it required some Googling to figure out what I was missing.)</em></p><p>You should see a success message output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*HyMpWjGJ4E51G6_vK8viBQ.png" /></figure><p>Next, we will want to verify that we can reach the webpage from a browser. You can complete this by copying the public IP address of your instance and pasting into an internet browser. You should expect to see the custom webpage and not the default Apache2 webpage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*OOaGKb2Pk3avTfCjqbj4hA.png" /></figure><h3>Cleanup</h3><p>Since this is just a tutorial, I’m going to do some clean up to free up space on my system. These are good commands to know when working with Docker. With the below commands, you only need to enter enough of the ID so that it’s unique. In the screenshot below, you can see I only needed to enter the first 3 numbers of each ID.</p><pre>#stop container<br>sudo docker container stop [CONTAINER ID] <br><br>#remove container<br>sudo docker container rm [CONTAINER ID]<br><br>#remove image<br>sudo docker image rm [IMAGE ID]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*V9QawKXcAcgEBkZMsE41Qg.png" /><figcaption>You can run “sudo docker ps -a” and “sudo docker image ls” to ensure there isn’t anything remaining.</figcaption></figure><h3>Conclusion</h3><p>In this article, we walked through how to create a container, update and install different packages, and create a custom webpage.</p><h3>Helpful References:</h3><ul><li><a href="https://docs.docker.com/get-started/overview/#the-docker-platform">Docker overview</a></li><li><a href="https://hub.docker.com/_/ubuntu">ubuntu</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad72bd95f9e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Python Boto3 to stop Instances with Lambda]]></title>
            <link>https://medium.com/@madison.hersom/how-to-use-python-boto3-to-stop-instances-with-lambda-d3560bfd2f05?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3560bfd2f05</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[instance]]></category>
            <category><![CDATA[eventbridge]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 02:03:20 GMT</pubDate>
            <atom:updated>2024-02-21T22:53:47.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PAqgg4Vob-3gPW3v" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*w8mGBPRd55RCw1LGnRoO5w.png" /></figure><h3>Definitions</h3><p><strong>What is Python? </strong>Python is a programming language known for its simplicity, human readability, and versatility across various applications.</p><p><strong>What is Boto3?</strong> Review the below AWS documentation to learn more.</p><p><a href="https://aws.amazon.com/sdk-for-python/">AWS SDK for Python - Boto3 - AWS</a></p><p><strong>What is AWS Lambda? </strong>AWS Lambda is defined as an event-driven computing platform provided by AWS. Developers are able to run code without provisioning or managing servers by setting up events that will automatically trigger or execute the code.</p><p><a href="https://aws.amazon.com/pm/lambda/?gclid=CjwKCAiA29auBhBxEiwAnKcSqjWAoYJitFeeL3PXOXsDZ3wpqfwkBm1loykHPRMhDyygla1rjEzmshoC1WEQAvD_BwE&amp;trk=73f686c8-9606-40ad-852f-7b2bcafa68fe&amp;sc_channel=ps&amp;ef_id=CjwKCAiA29auBhBxEiwAnKcSqjWAoYJitFeeL3PXOXsDZ3wpqfwkBm1loykHPRMhDyygla1rjEzmshoC1WEQAvD_BwE:G:s&amp;s_kwcid=AL!4422!3!651212652666!e!!g!!lambda!909122559!45462427876">AWS Lambda</a></p><h3>Use Case</h3><p>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 EC2 instances after all engineers are clocked out. No one should be working past 7:00 PM.</p><h3>Prerequisites</h3><ol><li>Create a free tier account: <a href="https://aws.amazon.com/">https://aws.amazon.com/</a>.</li><li>Identify which integrated development environment (IDE) you will use for the Python code. I am going to use AWS Cloud9.</li><li>Review the links listed under Helpful References toward the bottom of the article. All of the script information is pulled directly from this documentation.</li><li>Basic understanding of AWS EC2 Instances and Lambda Functions.</li></ol><p>This use case can be broken up into three main sections:</p><ol><li>Create a Python script that stops all running EC2 instances.</li><li>Create a Lambda function using Python 3.8 or higher runtime to run your script.</li><li>Add a trigger to the Lambda to ensure it runs on a set schedule daily.</li></ol><p>Let’s get started.</p><h3>Create a Python script that stops all running EC2 instances</h3><p>When it comes to Boto3, Amazon has done a fantastic job documenting what is needed for utilizing their resources. Refer to the Helpful Reference section below to locate where I pulled the information from.</p><p>Listed below are the main elements of what the below script is doing:</p><ol><li>Pulling a list of the running instances with a few exceptions I defined</li><li>Printing a list of the instance ID’s needed to run the stop instance function</li><li>Running a function that will programmatically stop all AWS EC2 Instances that meet the requirements</li></ol><pre>import boto3<br><br># Define a function to stop an EC2 instance.<br>def stop_instance(client, instance_id):<br>    # Use the stop_instances() method to stop the specified EC2 instance.<br>    response = client.stop_instances(InstanceIds=[instance_id])<br>    print(instance_id, &#39;stopped&#39;)<br><br># Create an EC2 client using boto3.<br>ec2 = boto3.client(&#39;ec2&#39;)<br><br># Use the describe_instances() method to retrieve information about EC2 instances.<br>response = ec2.describe_instances()<br><br># Iterate through the reservations in the response.<br>for reservation in response[&#39;Reservations&#39;]:<br>    # Iterate through the instances in each reservation.<br>    for instance in reservation[&#39;Instances&#39;]:<br>        # Check if the instance is in the &#39;running&#39; state and not the specified instance ID.<br>        if instance[&#39;State&#39;][&#39;Name&#39;] == &#39;running&#39; and instance[&#39;InstanceId&#39;] != &#39;INSERT ANY INSTANCE IDS YOU WANT TO EXCLUDE&#39;:<br>            # Check if the instance name contains &quot;Environment: Dev&quot;.<br>            instance_name = next((tag[&#39;Value&#39;] for tag in instance.get(&#39;Tags&#39;, []) if tag[&#39;Key&#39;] == &#39;Name&#39;), None)<br>            has_dev_environment = instance_name and &#39;Environment: Dev&#39; in instance_name<br>            <br>            if has_dev_environment:<br>                print(f&quot;Skipping instance {instance[&#39;InstanceId&#39;]} with &#39;Environment: Dev&#39; in the name.&quot;)<br>            else:<br>                # Print instance information.<br>                print(instance[&#39;InstanceId&#39;], instance[&#39;State&#39;][&#39;Name&#39;])<br>                <br>                # Stop the running instance using the stop_instance function.<br>                stop_instance(ec2, instance[&#39;InstanceId&#39;])</pre><p>To prepare for the Lambda function:</p><ol><li>Save the script in Notepad</li><li>Zip the file</li><li>Upload to a bucket in AWS S3</li></ol><p>I tested this script before inserting it into my lambda function. I tested this by created a few test instances and then ran the script in Cloud9. I was able to confirm the script successfully stopped all EC2 instances in the AWS dashboard.</p><p><em>Note: If you’re using Cloud9, make sure you add an exception so the instance running the Cloud9 environment does not get terminated.</em></p><h3>Create a Lambda function using Python 3.8 or higher runtime to run your script.</h3><p>Refer to the Helpful References section below to locate where I pulled the information from. The script below will programmatically create a Lambda function.</p><p>Note: There are different options to save the code for the function. I used a zip file that is stored in S3. Coding will need to be modified if you do something different.</p><pre>import boto3<br><br># Create an AWS Lambda client<br>lambda_client = boto3.client(&#39;lambda&#39;)<br><br># Define the IAM role ARN<br>role = &#39;INPUT IAM LAMBDA ROLE ARN&#39;<br><br># Create a Lambda function<br>response = lambda_client.create_function(<br>    FunctionName=&#39;stopInstances&#39;,  # Specify the function name<br>    Runtime=&#39;python3.8&#39;,  # Set the runtime environment<br>    Role=role,  # Provide the IAM role ARN<br>    Handler=&#39;INSERT FILE NAME.INSERT FUNCTION NAME&#39;,  # Specify the handler in the format &#39;filename.function&#39;<br>    Code={&#39;S3Bucket&#39;: &#39;INSERT BUCKET NAME&#39;, &#39;S3Key&#39;: &#39;INSERT OBJECT NAME&#39;},  # Define the code source in an S3 bucket<br>    Description=&#39;Stop all instances at end of day&#39;,  # Add a description for the function<br>)<br><br># Print the function name and ARN<br>print(response[&#39;FunctionName&#39;], response[&#39;FunctionArn&#39;])</pre><p>After running the above script in Cloud9, I was able to confirm that I successfully created a Lambda function within the AWS Dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*5YTcUuaAVViaTzuTAXKggg.png" /></figure><p>Helpful Tip: I had a hard time figuring out what specific ARN was needed in the Role parameter. Navigate to AWS &gt; IAM &gt; Roles. Search for the Lambda function to pull the ARN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*s70vQzZaANNUtqO9gYmqUQ.png" /></figure><h3>Add a trigger to the Lambda to ensure it runs on a set schedule daily.</h3><p>Refer to the Helpful References section below to locate where I pulled the information from. Outlined below are the main elements of what the below script will accomplish:</p><ol><li>Create a rule in EventBridge that will schedule the Lambda function to run every day at 7:00 PM.</li><li>Associating the EventBridge rule to the specific Lambda function</li></ol><pre>import boto3<br><br># Create an EventBridge client<br>event_client = boto3.client(&#39;events&#39;)<br><br># Define a rule and schedule it to trigger at 7 PM every day using a correct cron expression<br>response = event_client.put_rule(<br>    Name=&#39;NightyNight&#39;,  # Specify the name of the rule<br>    ScheduleExpression=&#39;cron(0 19 * * ? *)&#39;  # Set the cron expression for 7 PM every day<br>)<br><br># Retrieve and print the ARN from the response<br>rule_arn = response[&#39;RuleArn&#39;]<br>print(rule_arn)<br><br># Create an event source mapping for the Lambda function<br>function_name = &#39;stopInstances&#39;<br><br># Create an EventBridge target for the rule<br>event_client.put_targets(<br>    Rule=&#39;NightyNight&#39;,<br>    Targets=[<br>        {<br>            &#39;Id&#39;: &#39;NightyNight7&#39;,  # Unique ID for the target<br>            &#39;Arn&#39;: &#39;INSERT LAMBDA ARN&#39;<br>        },<br>    ]<br>)</pre><h3>Conclusion</h3><p>With the above three scripts, you will be able to <em>automatically </em>stop all EC2 instances with a scheduled Lambda function daily. This will help minimize costs by stopping instances after all employees are no longer working.</p><h3>Helpful References</h3><ul><li>Describe Instances: <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2/client/describe_instances.html">https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2/client/describe_instances.html</a></li><li>Stop Instances: <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2/client/stop_instances.html">https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2/client/stop_instances.html</a></li><li>Create Lambda Function: <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda/client/create_function.html">https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda/client/create_function.html</a></li><li>Create rule: <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/events/client/put_rule.html">https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/events/client/put_rule.html</a></li></ul><p>Link to my GitHub repository:</p><ul><li><a href="https://github.com/mhersom/GH-blue-dec-2023/blob/cb95bf9f3f2d72dabc5b239408a1ae625aaaacfe/Stop_Instances.py">https://github.com/mhersom/GH-blue-dec-2023/blob/cb95bf9f3f2d72dabc5b239408a1ae625aaaacfe/Stop_Instances.py</a></li><li><a href="https://github.com/mhersom/GH-blue-dec-2023/blob/main/create_lambda.py">https://github.com/mhersom/GH-blue-dec-2023/blob/main/create_lambda.py</a></li><li><a href="https://github.com/mhersom/GH-blue-dec-2023/blob/main/trigger_event.py">https://github.com/mhersom/GH-blue-dec-2023/blob/main/trigger_event.py</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3560bfd2f05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Python to Pull File Information]]></title>
            <link>https://medium.com/@madison.hersom/using-python-to-pull-file-information-b2f1ebf6976d?source=rss-148de943bc14------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2f1ebf6976d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[for-loop-in-python]]></category>
            <category><![CDATA[os-module]]></category>
            <category><![CDATA[lists-in-python]]></category>
            <dc:creator><![CDATA[Madison Hersom]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 01:28:38 GMT</pubDate>
            <atom:updated>2024-02-22T20:12:19.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G_D_hXUErToppxWc" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Use Case</h3><p>Your company needs to learn about the files located on various machines. You have been asked to build a script that extracts information such as the name and size about the files in the current working directory and stores it in a list of dictionaries. Create a script that generates a list of dictionaries about files in the working directory and also print the list of files.</p><h3>Prerequisites</h3><ol><li>Identify which integrated development environment (IDE) you will use for the Python code. I am going to use AWS Cloud9.</li><li>Basic understanding of Python. Some helpful concepts include: lists, dictionary, and the os module.</li></ol><p>This use case can be broken up into three main questions:</p><ol><li>How do I access the current working directory?</li><li>How do I pull the file name and file size?</li><li>How do I iterate through the current working directory to get this information?</li></ol><p>Let’s get started.</p><h3>How do I access the current working directory?</h3><p>First, we want to import the os module. Refer to the Helpful References section toward the bottom of the article to learn more about the os module.</p><p>The os.getcwd() string will return the files we are seeking.</p><p>The os.listdir() string will return a list of all of the files in the current working directory.</p><p>We want to create an empty list that we will utilize later.</p><p>Copy and paste the below script into a file on the IDE. You will want to ensure the file has the “.py” extension. This will tell the system that it’s a Python file.</p><pre>import os<br><br># Get the current working directory<br>cwd = os.getcwd()<br><br># Generate file information<br>directory = os.listdir(cwd)<br><br>files_list = []  # Initialize an empty list to store file information</pre><h3>How do I pull the file name and file size?</h3><p>We will continue using the os module to pull the file name and file size.</p><p>The os.path.basename() will provide us the file name.</p><p>The os.path.getsize will provide us the size of the file in bytes.</p><p>The file_info variable will pull our two key values (name and size) and format the returned response in an easy to read format.</p><p>By appending the list, we will be able to store the list information generated from our requests. We created an empty list previously to prepare for these additions.</p><p>Copy and paste the below script into the same file in your IDE.</p><pre># How to get the file name and size.<br>def get_file_info(file_path):<br>    file_name = os.path.basename(file_path)<br>    file_size = os.path.getsize(file_path)<br>    file_info = {&#39;File Name: &#39;: file_name, &#39;File Size: &#39;: file_size}<br>    files_list.append(file_info)<br>    print(files_list)</pre><h3>How do I iterate through the current working directory to get this information?</h3><p>We will want to use a “for loop” to iterate through the file directory. For loops are perfect for iterating through lists.</p><pre># Iterate through each file in the directory<br>for file_name in directory:<br>    file_path = os.path.join(cwd, file_name)<br>    get_file_info(file_path)</pre><p>Lastly, we need to print our list of files and file sizes.</p><pre># Print the list of dictionaries<br>for file_info in files_list:<br>    print(file_info)</pre><p>Copy and paste the above items into the same file in your IDE. Save the file.</p><h3>Conclusion</h3><p>Now, if you put the Python code altogether, you’ll create a script that will generate a list of dictionaries about files in the working directory, provide file information (e.g. name and size), and print the list of the files.</p><h3>Helpful References</h3><ul><li>os Module: <a href="https://docs.python.org/3/library/os.html">https://docs.python.org/3/library/os.html</a>.</li><li>For loops: <a href="https://wiki.python.org/moin/ForLoop">https://wiki.python.org/moin/ForLoop</a></li><li>Here is the link to my code in GitHub: <a href="https://github.com/mhersom/GH-blue-dec-2023/blob/cb95bf9f3f2d72dabc5b239408a1ae625aaaacfe/Week_14_Project.py">https://github.com/mhersom/GH-blue-dec-2023/blob/cb95bf9f3f2d72dabc5b239408a1ae625aaaacfe/Week_14_Project.py</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2f1ebf6976d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>