<?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 Ayomide Olowogorioye on Medium]]></title>
        <description><![CDATA[Stories by Ayomide Olowogorioye on Medium]]></description>
        <link>https://medium.com/@ayolowo9?source=rss-053dabde9043------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vuhplQOD69BEjLcR</url>
            <title>Stories by Ayomide Olowogorioye on Medium</title>
            <link>https://medium.com/@ayolowo9?source=rss-053dabde9043------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:00:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayolowo9/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[Mastering Automation: Bash Scripting for Repetitive Linux Tasks]]></title>
            <link>https://medium.com/@ayolowo9/mastering-automation-bash-scripting-for-repetitive-linux-tasks-0258ba50471e?source=rss-053dabde9043------2</link>
            <guid isPermaLink="false">https://medium.com/p/0258ba50471e</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Ayomide Olowogorioye]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 12:21:59 GMT</pubDate>
            <atom:updated>2024-12-01T20:03:12.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*VkEn4z2_W5rojQXxeOjYAQ.png" /><figcaption>Technical Diagram</figcaption></figure><h4>Introduction</h4><p>Understanding the Linux operating system and Bash command-line interface is a foundational skill for aspiring cloud engineers. To strengthen my proficiency in essential Linux commands and Bash scripting, I took on a <strong>Capture the Flag (CTF)</strong> challenge from <a href="https://learntocloud.guide/phase1/ctf"><strong>Learn to Cloud</strong></a>. This project also incorporated advanced cloud engineering tools such as <strong>GitHub Actions</strong>, <strong>Terraform for infrastructure as code (IaC)</strong>, and <strong>DynamoDB for backend state locking</strong>. Together, these tools enabled secure and robust infrastructure deployment while allowing me to automate repetitive Linux tasks through scripting.</p><h4>Objectives</h4><ul><li>Set up Terraform backend.</li><li>Write Terraform configuration.</li><li>Create a CI/CD workflow using GitHub Actions.</li><li>Deploy Terraform configurations.</li><li>SSH into the EC2 instance.</li><li>Develop a Bash script.</li><li>Transfer Bash script to the instance.</li><li>Execute and analyze results.</li></ul><p><strong><em>Let’s get started, shall we?….</em></strong></p><h4><strong>Step 1: Set Up Terraform Backend</strong></h4><p><strong>1. Create the S3 Bucket<br></strong>You can manually create the S3 bucket via the AWS Management Console(umm…don’t!), AWS CLI, or Terraform.</p><blockquote>p.s. The bucket must exist before Terraform can use it for storing state.</blockquote><p><strong>Using AWS CLI:</strong></p><pre>aws s3api create-bucket --bucket terraform-backend-ltc --region us-east-1<br># If you&#39;re in a region that enforces bucket location constraints (like us-east-2), use:<br>aws s3api create-bucket --bucket terraform-backend-ltc --region us-east-2 --create-bucket-configuration LocationConstraint=us-east-2<br># Enable versioning on the bucket to keep historical state files:<br>aws s3api put-bucket-versioning --bucket terraform-backend-ltc --versioning-configuration Status=Enabled</pre><p><strong>2. Create the DynamoDB Table<br></strong>The DynamoDB table is used for state locking to prevent multiple users or CI/CD systems from modifying the state file simultaneously.</p><p><strong>Using AWS CLI:</strong></p><pre>aws dynamodb create-table \<br>    --table-name terraform-lock-table \<br>    --attribute-definitions AttributeName=LockID,AttributeType=S \<br>    --key-schema AttributeName=LockID,KeyType=HASH \<br>    --billing-mode PAY_PER_REQUEST</pre><p><strong>3. Configure the Backend in Terraform<br></strong>Update your terraform block in the main.tf file to configure the backend:</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;terraform-backend-ltc&quot;<br>    key            = &quot;terraform/state.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>    dynamodb_table = &quot;terraform-lock-table&quot; # Optional, for state locking<br>    encrypt        = true                   # Encrypt state files<br>  }<br>}</pre><h4>Step 2: Write Terraform Configuration</h4><p>The Terraform configuration for this project was stored in the <a href="https://github.com/learntocloud/ltc-linux-challenge"><strong>ltc-linux-challenge</strong></a> repository. After forking the repository, I cloned it locally and customized the configuration files for my requirements.</p><h4>Step 3: Create a CI/CD Workflow using GitHub Actions</h4><p>I set up a GitHub Actions workflow to automate Terraform operations such as apply and destroy. Using <strong>two branches</strong> (main and dev), the workflow could be triggered on a push to the main branch or via manual input.</p><p>In the code snippet below, I’ve specified various triggers. First, I’ve listed workflow_dispatch, which allows me to manually trigger the job through the GitHub interface if needed, to apply or destroy my deployed infrastructure using input functions. I’ve also configured it to trigger on push to the main branch or on a pull_request from the main branch. This ensures that the action only runs when there’s a push or pull request to the main branch.</p><blockquote>P.S. To learn about how to authenticate GitHub actions using OpenId connect, have a look at my <a href="https://medium.com/@ayolowo9/using-github-actions-to-deploy-terraform-configuration-to-aws-a-ci-cd-workflow-fff3b420ee62">previous project</a> where I provided a brief overview.</blockquote><pre>name: cicd workflow<br><br>on:<br>  # Trigger the workflow manually and allow input for Terraform actions<br>  workflow_dispatch:<br>    inputs:<br>      action:<br>        description: &quot;Terraform action to run&quot;<br>        required: true<br>        default: &quot;apply&quot;<br>        type: choice<br>        options:<br>          - apply<br>          - destroy<br><br>  # Trigger the workflow on push and pull request events for the &quot;main&quot; branch<br>  push:<br>    branches: [&quot;main&quot;]<br><br>  pull_request:<br>    branches: [&quot;main&quot;]</pre><p>Now that we have everything in place to run the action, it’s time to define what we want our jobs to do!</p><pre>jobs:<br>  plan:<br>    # The type of runner that the job will run on<br>    name: Terraform Execution<br>    runs-on: ubuntu-latest<br><br>    # Steps represent a sequence of tasks that will be executed as part of the job<br>    steps:<br>      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it<br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br><br>      - name: Use Node.js<br>        uses: actions/setup-node@v4.0.4<br>        with:<br>          node-version: 20<br><br>      - name: Hashicorp - Terraform setup<br>        uses: hashicorp/setup-terraform@v3.1.2<br><br>      # To speed up the workflow, we cache the .terraform directory and terrraform providers<br>      # To avoid redownloading the providers everytime the workflow runs<br>      - name: Cache Terraform providers<br>        uses: terraform-cache/terraform-cache@v1<br><br>      - name: Configure AWS Credentials for github actions<br>        uses: aws-actions/configure-aws-credentials@v4.0.2<br>        with:<br>          audience: sts.amazonaws.com<br>          aws-region: ${{secrets.AWS_REGION}}<br>          role-to-assume: ${{secrets.ROLE_TO_ASSUME}} #change to reflect IAM role’s ARN<br><br>      # Runs a set of terraform commands using the runners shell<br>      - name: Terraform Init<br>        run: |<br>          cd aws<br>          terraform init<br><br>      - name: Terraform Validate<br>        run: |<br>          terraform fmt -recursive<br>          terraform validate<br>        continue-on-error: false</pre><p>The code to execute Terraform configuration with a conditional statement if the input given is <strong>apply</strong> or <strong>destroy</strong>:</p><pre>      - name: Execute Terraform<br>        run: |<br>          cd aws<br>          terraform init<br>          if [[ &quot;${{ github.event.inputs.action }}&quot; == &quot;apply&quot; ]]; then<br>            terraform apply -auto-approve<br>          elif [[ &quot;${{ github.event.inputs.action }}&quot; == &quot;destroy&quot; ]]; then<br>            terraform destroy -auto-approve<br>          fi</pre><p>Now deploy your configuration to your cloud provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*UDxgnLTLC16_MENCl6kTOg.png" /></figure><h4>Step 4: SSH into the EC2 instance</h4><p>After deploying the infrastructure, the public IP of the EC2 instance was retrieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*NZuorcJ78Kt66qr7vCjZGA.png" /></figure><p>In your CLI run the following command:</p><pre>ssh ec2-user@&lt;ctf_instance_public_ip&gt;<br># When prompted for a password, enter: `CTFpassword123!`</pre><p>Once logged in, you’ll see a welcome message with instructions for your first challenge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxZNpra572qt2rBywWvfCA.png" /></figure><h4>Step 5: Develop a Bash script</h4><p>The Capture the Flag challenge consists of 7 different tasks. The bash script was written to complete each task without needing to manually input them into the Linux CLI repeatedly.</p><blockquote>Note: If you are new to Linux/Bash scripting and looking to learn more effectively, I urge you not to just copy and paste these codes, as this would only slow your learning progress : )</blockquote><p>That being said, here is a snippet, you can access the full code <a href="https://github.com/Ayolowo/ltc-linux-challenge-phase1/blob/dev/aws/ctf_script.sh">here</a>:</p><pre>#!/bin/bash<br><br># This script contains the commands for solving tasks related to LTC CTF challenges.<br><br>echo &quot;--------------------------------------------------------------------------&quot;<br>echo &quot;1. Find a hidden file&quot;<br>echo &quot;--------------------------------------------------------------------------&quot;<br># Access the hidden file and display its content<br>cd /home/ec2-user/ctf_challenges/<br>cat .hidden_flag<br><br>echo &quot;--------------------------------------------------------------------------&quot;<br>echo &quot;2. Locate a file with &#39;secret&#39; in its name&quot;<br>echo &quot;--------------------------------------------------------------------------&quot;<br># Find files containing &#39;secret&#39; in their name<br>cd<br>sudo find  -type f -name &quot;*secret*&quot;<br># Display contents of a specific secret file<br>echo<br>cat very_secret_file.txt</pre><h4>Step 6: Transfer the Bash script to the instance</h4><p>There are two ways to go about running our bash script in the EC2 Instance</p><ul><li>By transferring the file using <strong>scp</strong></li><li>By using the <strong>vim</strong> or <strong>leafpad </strong>command<strong> </strong>within the instance to create the script and manually write or transfer the code</li></ul><p>To transfer the script to the EC2 instance, I used scp:</p><pre># run this command in a different terminal not within the instance itself<br>scp &lt;name_of_script&gt; ec2-user@&lt;ctf_instance_ip&gt;:/home/ec2-user/ctf_challenges<br># when prompted use the same password</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*aIAxbnIgkjrxCLroePoq5Q.png" /></figure><h4>Step 7: Execute and analyze results</h4><p>Now to run our bash script within our Linux EC2 Instance. First, switch the directory into the folder you transferred your created script using the <strong>cd</strong> command.</p><pre># run the bash script, we need this because of lack of permission<br>chmod +x ./ctf_script.sh &amp;&amp; ./ctf_script.sh</pre><p>The command chmod +x ./ctf_script.sh &amp;&amp; ./ctf_script.sh performs two actions:</p><ol><li><strong>chmod +x ./ctf_script.sh</strong><br>This changes the permissions of the file ctf_script.sh to make it executable. The +x flag adds executable permissions to the script.</li><li><strong>&amp;&amp;</strong><br>This is a logical AND operator. It ensures that the second command (./ctf_script.sh) runs only if the first command (chmod +x ./ctf_script.sh) succeeds.</li><li><strong>./ctf_script.sh</strong><br>This runs the script ctf_script.sh in the current directory (./ specifies the current directory).</li></ol><p><strong>Results</strong></p><p>The script successfully automated all tasks, providing an efficient and repeatable solution for solving Linux challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*tUD_5-ZKY82SJQxyeF1H7w.png" /></figure><h4><strong>Conclusion</strong></h4><p>By tackling the <strong>Capture the Flag challenge</strong>, I enhanced my Linux and Bash scripting skills, reinforced best practices for infrastructure as code using <strong>Terraform</strong>, and automated deployments through <strong>GitHub Actions</strong>. The process demonstrated the power of integrating tools like <strong>DynamoDB</strong> for state locking and <strong>AWS CLI</strong> for seamless cloud management.</p><p>Big thanks to <strong>Learn to Cloud</strong> for providing such an engaging platform that combines fun challenges with real-world applications. It’s exciting to see how mastering automation can elevate one’s journey in cloud engineering, preparing me for increasingly complex challenges ahead.</p><blockquote>Capture the Flag gives me a nostalgic feeling of the game mode on <strong>Call of Duty</strong>.</blockquote><p>Have feedback or suggestions? I’d love to hear your thoughts in the comments or connect to discuss further!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0258ba50471e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Serverless Customer Management System with Python, Terraform, Lambda, FastAPI and other…]]></title>
            <link>https://medium.com/@ayolowo9/building-a-serverless-customer-management-system-with-python-terraform-lambda-fastapi-and-other-4c4b267ee220?source=rss-053dabde9043------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c4b267ee220</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Ayomide Olowogorioye]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 12:14:52 GMT</pubDate>
            <atom:updated>2024-11-21T12:14:52.277Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building a Serverless Customer Management System with Python, Terraform, Lambda, FastAPI and other AWS services</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*3nTD4z26WqfgEtrDbJsJZQ.png" /></figure><h4><strong>Introduction</strong></h4><p>Managing customer data efficiently is crucial for any business. I built a <strong>serverless customer management system</strong> using AWS services, Terraform, and Python in this project. This article will guide you through the architecture, code, and results of the implemented system.</p><h4>Prerequisites</h4><ul><li>An AWS account</li><li>GitHub account</li><li>Local environment setup; Terraform, AWS CLI, and an IDE (like VS Code)</li></ul><h4>Objectives</h4><ul><li>Load customer data into a DynamoDB table and S3 bucket.</li><li>Use FastAPI for querying customer data via HTTP endpoints.</li><li>Leverage AWS Lambda and API Gateway for a scalable, serverless API solution.</li></ul><p><strong><em>Let&#39;s get started, shall we?….</em></strong></p><h4><strong>Step 1: Create a GitHub Repository</strong></h4><p>Start by creating a GitHub repository for this <a href="https://github.com/Ayolowo/serverless-customer-app/blob/main/Readme.md">project</a>. Clone it to your local machine</p><pre>git clone &lt;repo_url&gt;<br>cd project-directory</pre><p>This repository will house your project files, including code, Terraform configurations, and the JSON data file.</p><h4>Step 2: Prepare the Data</h4><p>Create a customerdata.json file to hold your customer information. You could leverage ChatGPT with the right prompt to provide you with the type of data you need as I did……yeah I&#39;m not a creep :)</p><p>Below is a sample snippet:</p><pre>[<br>    {<br>        &quot;customerId&quot;: &quot;CUST001&quot;,<br>        &quot;name&quot;: &quot;John Doe&quot;,<br>        &quot;email&quot;: &quot;john.doe@example.com&quot;,<br>        &quot;phone&quot;: &quot;+1234567890&quot;,<br>        &quot;address&quot;: {<br>            &quot;street&quot;: &quot;123 Elm St&quot;,<br>            &quot;city&quot;: &quot;Somewhere&quot;,<br>            &quot;state&quot;: &quot;CA&quot;,<br>            &quot;zip&quot;: &quot;90210&quot;<br>        },<br>        &quot;transactionHistoryUrl&quot;: &quot;https://s3-bucket-name.s3.amazonaws.com/transactions/CUST001.json&quot;,<br>        &quot;createdAt&quot;: &quot;2023-09-12T21:50:00Z&quot;<br>    }<br>]</pre><h4>Step 3: Set Up a Virtual Environment</h4><p>Next, set up a Python virtual environment and install all necessary dependencies:</p><pre>python -m venv env<br>source env/bin/activate  # For Linux/MacOS<br>env\Scripts\activate     # For Windows<br>pip install -r requirements.txt</pre><h4>Step 4: Create Python Scripts for AWS Services</h4><p>Create Python scripts to:</p><ol><li>Upload transaction files to an S3 bucket.</li><li>Create and populate a DynamoDB table with customer data.</li></ol><p>For example:</p><ul><li><strong>S3 Script</strong>: Check if the bucket exists, and if not, create it.</li><li><strong>DynamoDB Script</strong>: Define a class to handle table creation, check for table existence, and populate it with data from customerdata.json.</li></ul><p>Here I provided snippets for the S3 and Dynamodb scripts, but you can access the complete code in this repo for <a href="https://github.com/Ayolowo/serverless-customer-app/blob/main/app/s3.py">S3</a> and <a href="https://github.com/Ayolowo/serverless-customer-app/blob/main/app/dynamo.py">Dynamodb</a>.</p><pre># Create S3 bucket for customer csv files<br>def bucket_exists(bucket_name, region=&#39;us-east-1&#39;):<br>    s3 = boto3.client(&#39;s3&#39;)<br>    try:<br>        s3.head_bucket(Bucket=bucket_name)<br>        return True<br>    except ClientError as e:<br>        if e.response[&#39;Error&#39;][&#39;Code&#39;] == &#39;404&#39;:<br>            print(f&quot;Bucket &#39;{bucket_name}&#39; does not exist.&quot;)<br>        else:<br>            # Log any other error<br>            print(f&quot;Error checking bucket existence: {e}&quot;)<br>        return False<br><br>def create_s3_bucket(bucket_name, region=&#39;us-east-1&#39;):<br>    # Call the bucket_exists function to check for existence<br>    if bucket_exists(bucket_name, region=&#39;us-east-1&#39;):<br>        print(f&quot;Bucket &#39;{bucket_name}&#39; already exists in &#39;{region}&#39;&quot;)<br>        return True<br>    <br>    try:<br>        s3 = boto3.client(&#39;s3&#39;, region_name=region)<br>        response = s3.create_bucket(Bucket=bucket_name)<br>        print(&quot;Bucket created successfully with the following response:&quot;)<br>        print(f&quot;Bucket &#39;{bucket_name}&#39; was created in the &#39;{region}&#39; region.&quot;) # type: ignore<br><br>    except ClientError as e:<br>        logging.error(e)<br>        return False<br>    return True</pre><pre># Create Dynamodb table for customer data<br>class Customers:<br>    &quot;&quot;&quot;Encapsulates an Amazon DynamoDB table of customer data.&quot;&quot;&quot;<br><br>    def __init__(self, dyn_resource):<br>        self.dyn_resource = dyn_resource<br>        self.table = None<br><br>    def exists(self, customers_table):<br>        try:<br>            table = self.dyn_resource.Table(customers_table)<br>            table.load()<br>            exists = True<br>        except ClientError as err:<br>            if err.response[&quot;Error&quot;][&quot;Code&quot;] == &quot;ResourceNotFoundException&quot;:<br>                exists = False<br>            else:<br>                logger.error(<br>                    &quot;Couldn&#39;t check for existence of %s. Here&#39;s why: %s: %s&quot;,<br>                    customers_table,<br>                    err.response[&quot;Error&quot;][&quot;Code&quot;],<br>                    err.response[&quot;Error&quot;][&quot;Message&quot;],<br>                )<br>                raise<br>        else:<br>            self.table = table<br>        return exists<br><br>    def create_table(self, customers_table):<br>        try:<br>            self.table = self.dyn_resource.create_table(<br>                TableName=customers_table,<br>                KeySchema=[<br>                    {&quot;AttributeName&quot;: &quot;name&quot;, &quot;KeyType&quot;: &quot;HASH&quot;},  # Partition key<br>                    {&quot;AttributeName&quot;: &quot;customerId&quot;, &quot;KeyType&quot;: &quot;RANGE&quot;},  # Sort key<br>                ],<br>                AttributeDefinitions=[<br>                    {&quot;AttributeName&quot;: &quot;name&quot;, &quot;AttributeType&quot;: &quot;S&quot;},<br>                    {&quot;AttributeName&quot;: &quot;customerId&quot;, &quot;AttributeType&quot;: &quot;S&quot;},<br>                ],<br>                ProvisionedThroughput={<br>                    &quot;ReadCapacityUnits&quot;: 10,<br>                    &quot;WriteCapacityUnits&quot;: 10,<br>                },<br>            )<br>            self.table.wait_until_exists()<br>        except ClientError as err:<br>            logger.error(<br>                &quot;Couldn&#39;t create table %s. Here&#39;s why: %s: %s&quot;,<br>                customers_table,<br>                err.response[&quot;Error&quot;][&quot;Code&quot;],<br>                err.response[&quot;Error&quot;][&quot;Message&quot;],<br>            )<br>            raise<br>        else:<br>            return self.table</pre><p>To create your S3 bucket and Dynamodb table:</p><pre>#depending on your python version <br>#you might need to use &#39;python3&#39; instead<br>python s3.py<br>python dynamo.py</pre><h4>Step 5: Develop FastAPI for HTTP Endpoints</h4><p>Create a main.py file to define HTTP endpoints for querying customer data. Use <strong>FastAPI</strong> to handle routes and <strong>Mangum</strong> to adapt FastAPI for AWS Lambda.</p><p>Import all modules needed for your application:</p><pre>from fastapi import FastAPI, HTTPException<br>from collections import OrderedDict<br>from mangum import Mangum<br>from boto3.dynamodb.conditions import Key<br>from botocore.exceptions import ClientError<br>from typing import List<br>import boto3<br>import logging</pre><p>Initialize FastAPI and Mangum:</p><pre># Initialize FastAPI AND Mangum to adapt FastAPI for AWS Lambda<br>app = FastAPI()<br>handler = Mangum(app)</pre><p>The complete FastAPI application can be seen <a href="https://github.com/Ayolowo/serverless-customer-app/blob/main/app/main.py">here</a>.</p><p>Example Endpoints: <strong>Get all customers</strong></p><pre># Initialize customers instance<br>customers_instance = Customers(dynamodb, table_name)<br><br>@app.get(&quot;/customers&quot;, response_model=List[dict])<br>async def get_all_customers():<br>    return customers_instance.get_all_customers()</pre><p>Example: <strong>Query a Single Customer</strong></p><pre>@app.get(&quot;/customers/{customerId}&quot;, response_model=List[dict])<br>async def query_customer(customerId: str):<br>    customers = customers_instance.query_customer(customerId)<br>    if not customers:<br>        raise HTTPException(status_code=404, detail=&quot;No customer details found for the specified customerId.&quot;)<br>    return customers</pre><blockquote>P.S. Ensure to test your FastAPI application locally before deploying to Lambda</blockquote><pre># Test FastApi application<br>uvicorn main:app --reload</pre><h4>Step 6: Package Lambda Code and Dependencies</h4><p>Create a dependencies folder, and install all dependencies from your requirements.txt file into the folder using pip:</p><pre>mkdir dependencies<br>pip install -r requirements.txt -t dependencies/</pre><p>Then zip your dependencies, along with your main.py:</p><pre>zip -r app.zip .<br>zip -u dependencies/app.zip main.py</pre><h4>Step 7: Write Terraform Configuration</h4><p>Use <strong>Terraform</strong> to define and deploy your AWS infrastructure.</p><ul><li><strong>Lambda Function</strong>: Deploy the packaged application.</li><li><strong>IAM Role</strong>: Grant Lambda permissions to access other AWS resources.</li><li><strong>API Gateway</strong>: Create endpoints for your FastAPI methods.</li></ul><pre># Create a lambda function to run python code<br>data &quot;aws_iam_policy_document&quot; &quot;assume_role&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;lambda.amazonaws.com&quot;]<br>    }<br><br>    actions = [&quot;sts:AssumeRole&quot;]<br>  }<br>}<br><br># IAM role for aws Lambda to assume<br>resource &quot;aws_iam_role&quot; &quot;iamrolelambda&quot; {<br>  name               = &quot;iamrolelambda&quot;<br>  assume_role_policy = data.aws_iam_policy_document.assume_role.json<br>}<br><br>resource &quot;aws_lambda_function&quot; &quot;terraform_function&quot; {<br>  # If the file is not in the current working directory you will need to include a<br>  # path.module in the filename.<br>  filename      = &quot;${path.module}/dependencies/app.zip&quot;<br>  function_name = &quot;app_function&quot;<br>  role          = aws_iam_role.iamrolelambda.arn<br>  handler       = &quot;main.handler&quot;<br><br>  runtime = &quot;python3.12&quot;<br>}<br><br># Block to import RestAPI from AWS<br>import {<br>  to = aws_api_gateway_rest_api.app_function-API<br>  id = &quot;yourid&quot;<br>}<br><br>resource &quot;aws_api_gateway_rest_api&quot; &quot;app_function-API&quot; {<br>  name = &quot;app_function-API&quot;<br><br>}</pre><p>In this scenario, I made use of ‘terraform import’ to:</p><p>Import the IAM role needed for Lambda to assume, and the API Gateway created on AWS.</p><blockquote>P.S. Ensure your IAM role complies with AWS&#39;s least privileged access to AWS resources.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*NW2I2YhInMzkgRtSBmr3fA.png" /></figure><blockquote>P.S. Make sure to set your handler to main.handler or if your script is named “lambda” then it should be lambda.handler. Remember we already set our handler in our main.py to Mangum(app).</blockquote><p>Deploy your configuration:</p><pre>terraform init<br>terraform plan<br>terraform apply</pre><h4>Step 8: Deploy and Configure API Gateway</h4><p><strong>1. Test with an API Gateway Event</strong></p><p>When using the Lambda Console’s “Test” feature, AWS Lambda expects the event payload to match the integration source (e.g., API Gateway). To ensure proper testing, simulate an HTTP API Gateway event. You can either use a pre-configured event template or create a custom one.</p><p><strong>2. Validate Lambda Runtime</strong></p><p>Ensure that the Lambda function is configured with a runtime compatible with <strong>FastAPI</strong> and <strong>Mangum</strong>, such as Python 3.12. A mismatch in runtime can lead to unexpected errors.</p><p><strong>3. Configure API Gateway Methods<br></strong>In your API Gateway console:</p><ul><li>Create endpoints corresponding to your FastAPI routes.</li><li>Configure methods such as <strong>GET</strong>, <strong>POST</strong>, <strong>PUT</strong>, and <strong>DELETE</strong>, ensuring each triggers the appropriate Lambda function.</li><li>Use proper method request and response mappings to handle data exchange effectively.</li></ul><p><strong>4. Deploy the API<br></strong>Once methods are configured, deploy the API to a stage (e.g., dev, prod). This deployment generates a public endpoint URL for testing and consumption.</p><p><strong>5. Verify with API Gateway<br></strong>Test the integration by calling the API Gateway endpoints using tools like <strong>Postman</strong>, <strong>cURL</strong>, or your browser. Ensure that:</p><ul><li>Lambda functions are executed correctly.</li><li>Responses match the expected format.</li><li>Any necessary debugging or adjustments are made to fix issues.</li></ul><h4>Step 9: Results</h4><p>Here are sample results from querying the deployed API:</p><ul><li><strong>Querying All Customers<br>API Endpoint: </strong>GET /customers<br><strong>Result:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*a2FKd3jpgpjPTimwqyD_aA.png" /></figure><ul><li><strong>Querying a Single Customer<br>API Endpoint: </strong>GET /customers/{customerId}<br><strong>Request: </strong>GET /customers/CUST001<br><strong>Result:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*HVGWCounjJPRt6ui8uJlMw.png" /></figure><h4>Conclusion</h4><p>This project demonstrates the power and flexibility of serverless architecture for managing customer data. By combining AWS services like S3, DynamoDB, Lambda, and API Gateway with Python and Terraform, we’ve built a highly scalable, cost-effective, and efficient system.</p><p>The use of FastAPI ensures quick development and reliable APIs, while Mangum bridges the gap between Lambda and API Gateway, making serverless deployments seamless. This approach not only simplifies infrastructure management but also enables developers to focus on delivering value through application logic.</p><p>Feel free to explore the GitHub <a href="https://github.com/Ayolowo/serverless-customer-app/blob/main/Readme.md">repository</a> to dive into the code and adapt it to your needs. Whether you’re building customer management systems, inventory systems, or any other data-driven application, this architecture provides a solid foundation to scale and grow.</p><p>Have feedback or suggestions? I’d love to hear your thoughts in the comments or connect to discuss further!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c4b267ee220" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using GitHub Actions to Deploy Terraform Configuration to AWS: A CI/CD Workflow]]></title>
            <link>https://medium.com/@ayolowo9/using-github-actions-to-deploy-terraform-configuration-to-aws-a-ci-cd-workflow-fff3b420ee62?source=rss-053dabde9043------2</link>
            <guid isPermaLink="false">https://medium.com/p/fff3b420ee62</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Ayomide Olowogorioye]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 19:21:36 GMT</pubDate>
            <atom:updated>2024-10-23T19:21:36.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*u-Adc9VsZETqT_fJZsWvWQ.png" /></figure><p>This project provides a simple guide on deploying your Terraform configuration to AWS using GitHub Actions, without the need to manually input commands step-by-step.</p><p><strong>Prerequisites<br>- A </strong>GitHub account, to create a repository<br>- A preconfigured Terraform configuration (or you could fork a repository) like <a href="https://github.com/Ayolowo/Terraform-cicd">mine</a><br>- An AWS account</p><p><strong>The Objectives</strong></p><ul><li>Establish a trust relationship between AWS IAM and GitHub Actions to authenticate access to AWS using OpenID Connect.</li><li>Create a role for GitHub actions to assume.</li><li>Set up a YAML configuration file in GitHub Actions to automate the workflow.</li><li>Deploy infrastructure to AWS.</li></ul><p><strong>Let’s begin, shall we?<br></strong>To create a trust relationship between AWS IAM and GitHub Actions, and to set up the role for GitHub Actions to assume, I recommend using <a href="https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services">GitHub Docs</a>. Explaining it in full detail here would require a separate post. Plus, you’ll learn a lot from troubleshooting and figuring things out along the way.</p><p>To control when a GitHub Action runs, we use the on syntax to define the criteria that must be met before a job will execute.</p><p>In the code snippet below, I’ve specified various triggers. First, I’ve listed workflow_dispatch, which allows me to manually trigger the job through the GitHub interface if needed. I’ve also configured it to trigger on push to the main branch or on a pull_request from the main branch. This ensures that the action only runs when there’s a push or pull request to the main branch.</p><pre>name: cicd workflow<br><br>on:<br>  # Triggers the workflow on push request event but only for the &quot;main&quot; branch<br>  workflow_dispatch:<br>  push:<br>    branches: [&quot;main&quot;]<br><br>  pull_request:<br>    branches: [&quot;main&quot;]</pre><p>Now that we have everything in place to run the action, it’s time to define what we want our jobs to do!</p><p><strong>Terraform Plan<br></strong>The first job is the plan job, where we initialize the working directory, validate the code, and run the terraform plan command. Before that, we need to check out the repository using the checkout action, install Terraform on the runner instance (in this case, ubuntu-latest), and authenticate with our AWS credentials. Additionally, we’ll use cache actions to cache the Terraform providers and dependencies, speeding up the workflow on future runs.</p><pre># A workflow run is made up of one or more jobs that can run sequentially or in parallel<br>jobs:<br>  plan:<br>    # The type of runner that the job will run on<br>    name: Terraform plan<br>    runs-on: ubuntu-latest<br><br>    # Steps represent a sequence of tasks that will be executed as part of the job<br>    steps:<br>      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it<br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br><br>      - name: Use Node.js<br>        uses: actions/setup-node@v4.0.4<br>        with:<br>          node-version: 20<br><br>      - name: Hashicorp - Terraform setup<br>        uses: hashicorp/setup-terraform@v3.1.2<br><br>      # To speed up the workflow, we cache the .terraform directory and terrraform providers<br>      # To avoid redownloading the providers everytime the workflow runs<br>      - name: Cache Terraform providers<br>        uses: terraform-cache/terraform-cache@v1<br><br>      - name: Configure AWS Credentials for github actions<br>        uses: aws-actions/configure-aws-credentials@v4.0.2<br>        with:<br>          audience: sts.amazonaws.com<br>          aws-region: ${{secrets.AWS_REGION}}<br>          role-to-assume: ${{secrets.ROLE_TO_ASSUME}} #change to reflect IAM role’s ARN<br><br>      # Runs a set of terraform commands using the runners shell<br>      - name: Terraform Init<br>        run: terraform init<br><br>      - name: Terraform Validate<br>        run: |<br>          terraform fmt -recursive<br>          terraform validate<br>        continue-on-error: false<br><br>      - name: Terraform Plan<br>        run: terraform plan</pre><p><strong>Terraform Deploy<br></strong>The next job to run is the deploy phase, where we deploy the infrastructure to AWS.</p><blockquote><strong>Note: Each job within the GitHub Actions workflow uses a separate runner instance to execute the actions specified for that job.</strong></blockquote><p>The code snippet below demonstrates the deployment process. You’ll notice the needs: input, which ensures that the deploy job only runs after the plan phase has been successfully completed.</p><pre>  deploy:<br>    name: Terraform apply<br>    needs: plan<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br><br>      - name: Use Node.js<br>        uses: actions/setup-node@v4.0.4<br>        with:<br>          node-version: 20<br><br>      - name: Configure AWS Credentials for github actions<br>        uses: aws-actions/configure-aws-credentials@v4.0.2<br>        with:<br>          audience: sts.amazonaws.com<br>          aws-region: ${{secrets.AWS_REGION}}<br>          role-to-assume: ${{secrets.ROLE_TO_ASSUME}}<br><br>      - name: Deploy to AWS<br>        run: |<br>          terraform init<br>          terraform apply -auto-approve</pre><p><strong>Here is the complete workflow file with all the steps:</strong></p><pre>name: cicd-workflow<br><br>on:<br>  # Triggers the workflow on push request event but only for the &quot;main&quot; branch<br>  workflow_dispatch:<br>  push:<br>    branches: [&quot;main&quot;]<br><br>  pull_request:<br>    branches: [&quot;main&quot;]<br><br>permissions:<br>  id-token: write<br>  contents: read<br><br># A workflow run is made up of one or more jobs that can run sequentially or in parallel<br>jobs:<br>  plan:<br>    # The type of runner that the job will run on<br>    name: Terraform plan<br>    runs-on: ubuntu-latest<br><br>    # Steps represent a sequence of tasks that will be executed as part of the job<br>    steps:<br>      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it<br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br><br>      - name: Use Node.js<br>        uses: actions/setup-node@v4.0.4<br>        with:<br>          node-version: 20<br><br>      - name: Hashicorp - Terraform setup<br>        uses: hashicorp/setup-terraform@v3.1.2<br><br>      # To speed up the workflow, we cache the .terraform directory and terrraform providers<br>      # To avoid redownloading the providers everytime the workflow runs<br>      - name: Cache Terraform providers<br>        uses: terraform-cache/terraform-cache@v1<br><br>      - name: Configure AWS Credentials for github actions<br>        uses: aws-actions/configure-aws-credentials@v4.0.2<br>        with:<br>          audience: sts.amazonaws.com<br>          aws-region: ${{secrets.AWS_REGION}}<br>          role-to-assume: ${{secrets.ROLE_TO_ASSUME}} #change to reflect IAM role’s ARN<br><br>      # Runs a set of terraform commands using the runners shell<br>      - name: Terraform Init<br>        run: terraform init<br><br>      - name: Terraform Validate<br>        run: |<br>          terraform fmt -recursive<br>          terraform validate<br>        continue-on-error: false<br><br>      - name: Terraform Plan<br>        run: terraform plan<br><br>  deploy:<br>    name: Terraform apply<br>    needs: plan<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br><br>      - name: Use Node.js<br>        uses: actions/setup-node@v4.0.4<br>        with:<br>          node-version: 20<br><br>      - name: Configure AWS Credentials for github actions<br>        uses: aws-actions/configure-aws-credentials@v4.0.2<br>        with:<br>          audience: sts.amazonaws.com<br>          aws-region: ${{secrets.AWS_REGION}}<br>          role-to-assume: ${{secrets.ROLE_TO_ASSUME}}<br><br>      - name: Deploy to AWS<br>        run: |<br>          terraform init<br>          terraform destroy -auto-approve</pre><p><strong>Key Takeaways:</strong></p><ul><li><strong>Using OIDC for Trust</strong>: I established a trust relationship between AWS IAM and GitHub Actions using OpenID Connect (OIDC), allowing actions to assume roles securely without the need for long-lived credentials like access keys.</li><li><strong>Role-Based Access</strong>: Actions assume a role I created on AWS, so no need to store access keys — goodbye, long-lived credentials!</li><li><strong>Environment Variables &amp; Secrets</strong>: I leveraged environment variables and secrets for reusability across workflows, improving flexibility and security.</li><li><strong>Caching Terraform Providers</strong>: Caching the Terraform providers significantly sped up the workflow on subsequent runs, making the process more efficient.</li></ul><p>In this project, I kept things simple with a single branch (main), but in the real world, multiple branches, environments, and approval processes are crucial. We don’t want deployments happening with every commit, it could easily introduce breaking changes to infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fff3b420ee62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Provisioning MYSQL RDS database and EC2 Instance using Terraform]]></title>
            <link>https://medium.com/@ayolowo9/provisioning-mysql-rds-database-and-ec2-instance-using-terraform-4ed8a42f84e9?source=rss-053dabde9043------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ed8a42f84e9</guid>
            <category><![CDATA[terraform-cloud]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[rds-mysql]]></category>
            <dc:creator><![CDATA[Ayomide Olowogorioye]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 22:17:37 GMT</pubDate>
            <atom:updated>2024-12-13T10:49:11.752Z</atom:updated>
            <content:encoded><![CDATA[<h3>Provisioning RDS MYSQL instance and an EC2 Instance using Terraform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FoaTm2F6NVtEPbOkK6J5cg.png" /></figure><p>This tutorial demonstrates how to provision an RDS MySQL and EC2 instances using <strong>Terraform</strong>. The EC2 instance will reside in a public subnet to act as a bastion host for SSH access. Meanwhile, the RDS MySQL instance will be deployed in private subnets for enhanced security. A <strong>NAT Gateway</strong> will enable internet access for the private subnets to allow updates or maintenance tasks.</p><h4>Prerequisites</h4><ol><li><strong>Install Terraform</strong></li></ol><ul><li>Visit <a href="https://developer.hashicorp.com/">Terraform’s official documentation</a> for installation steps.</li></ul><p><strong>2. AWS CLI User Setup</strong></p><ul><li>Use AWS IAM to create a CLI user with appropriate permissions.</li></ul><p><strong>3. Terraform VSCode Extension</strong> <em>(Optional)</em></p><ul><li>Install the extension for syntax highlighting and autocompletion.</li></ul><h4>Resources To Be Created</h4><p>At the end of this tutorial, we will have the following AWS resources created:</p><h4>1. VPC</h4><p>A Virtual Private Cloud (VPC) provides a logically isolated section of the AWS cloud where we can securely deploy resources.</p><h4>2. Subnets</h4><ul><li><strong>One Public Subnet</strong></li><li>This is for deploying the EC2 instance with public internet access.</li><li><strong>Two Private Subnets</strong></li><li>For deploying the RDS MySQL instance, it is accessible only through the EC2 instance.</li></ul><h4>3. NAT Gateway</h4><p>Provides internet access for resources in private subnets while keeping them inaccessible from the public internet.</p><h4>4. Route Tables</h4><ul><li><strong>Public Route Table</strong></li><li>Routes traffic from the public subnet to the Internet Gateway.</li><li><strong>Private Route Table</strong></li><li>Routes traffic from private subnets through the NAT Gateway.</li></ul><h4>5. Security Groups</h4><ul><li><strong>EC2 Security Group</strong></li><li>Allows inbound SSH traffic (port 22) and outbound traffic for package installations.</li><li><strong>RDS Security Group</strong></li><li>Restricts inbound MySQL access (port 3306) to traffic originating from the EC2 instance.</li></ul><h4>6. Compute and Database Instances</h4><ul><li><strong>One EC2 Instance</strong></li><li>Configured as a bastion host for SSH access and MySQL client operations.</li><li><strong>One MySQL RDS Instance</strong></li><li>Deployed in private subnets with no public access.</li></ul><h4>7. Key Pair</h4><ul><li>A .pem file for secure SSH access to the EC2 instance.</li></ul><h4>THE SETUP</h4><p>Terraform configurations are organized across multiple .tf files for modularity and ease of debugging.</p><p><strong>provider.tf<br></strong>To define the Cloud Provider we are using to provision our resources.</p><pre>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}</pre><p><strong>vpc.tf</strong></p><pre># Retrieve the list of AZs in the current AWS region<br>data &quot;aws_availability_zones&quot; &quot;available&quot; {}<br>data &quot;aws_region&quot; &quot;current&quot; {}<br><br># Create VPC<br>resource &quot;aws_vpc&quot; &quot;rds_vpc&quot; {<br>  cidr_block           = var.vpc_cidr<br>  enable_dns_hostnames = true<br>  tags = {<br>    Name = &quot;rds_vpc&quot;<br>  }<br>}<br># Create Internet Gateway<br>resource &quot;aws_internet_gateway&quot; &quot;internet_gateway&quot; {<br>  vpc_id = aws_vpc.rds_vpc.id<br>  tags = {<br>    Name = &quot;internet_access_igw&quot;<br>  }<br>}<br># Create an Elastic IP for the NAT Gateway<br>resource &quot;aws_eip&quot; &quot;nat_eip&quot; {<br>  domain = &quot;vpc&quot;<br>}<br># Create the NAT Gateway in a public subnet<br>resource &quot;aws_nat_gateway&quot; &quot;nat_gateway&quot; {<br>  allocation_id = aws_eip.nat_eip.id<br>  subnet_id     = aws_subnet.public_subnets[&quot;public_subnet_1&quot;].id<br>  tags = {<br>    Name = &quot;nat_gateway&quot;<br>  }<br>  depends_on = [aws_internet_gateway.internet_gateway]<br>}<br><br># Create 3 subnets, 1 public and 2 private<br># Deploy the public subnets<br>resource &quot;aws_subnet&quot; &quot;public_subnets&quot; {<br>  for_each                = var.public_subnets<br>  vpc_id                  = aws_vpc.rds_vpc.id<br>  cidr_block              = cidrsubnet(var.vpc_cidr, 8, each.value + 100)<br>  availability_zone       = tolist(data.aws_availability_zones.available.names)[each.value]<br>  map_public_ip_on_launch = true<br>  tags = {<br>    Name      = each.key<br>    Terraform = &quot;true&quot;<br>  }<br>}<br># Deploy the private subnets<br>resource &quot;aws_subnet&quot; &quot;private_subnets&quot; {<br>  for_each          = var.private_subnets<br>  vpc_id            = aws_vpc.rds_vpc.id<br>  cidr_block        = cidrsubnet(var.vpc_cidr, 8, each.value)<br>  availability_zone = tolist(data.aws_availability_zones.available.names)[each.value]<br>  tags = {<br>    Name      = each.key<br>    Terraform = &quot;true&quot;<br>  }<br>}<br><br># Create route tables for public and private subnets<br>resource &quot;aws_route_table&quot; &quot;public_route_table&quot; {<br>  vpc_id = aws_vpc.rds_vpc.id<br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.internet_gateway.id<br>  }<br>  tags = {<br>    Name      = &quot;public_rtb&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}<br>resource &quot;aws_route_table&quot; &quot;private_route_table&quot; {<br>  vpc_id = aws_vpc.rds_vpc.id<br>  # Define a route for internet-bound traffic via NAT Gateway<br>  route {<br>    cidr_block     = &quot;0.0.0.0/0&quot;                    # Route for all outbound traffic<br>    nat_gateway_id = aws_nat_gateway.nat_gateway.id # NAT Gateway for internet access<br>  }<br>  tags = {<br>    Name      = &quot;private_rtb&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}<br><br># Create route table associations<br>resource &quot;aws_route_table_association&quot; &quot;public&quot; {<br>  depends_on     = [aws_subnet.public_subnets]<br>  route_table_id = aws_route_table.public_route_table.id<br>  for_each       = aws_subnet.public_subnets<br>  subnet_id      = each.value.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;private&quot; {<br>  depends_on     = [aws_subnet.private_subnets]<br>  route_table_id = aws_route_table.private_route_table.id<br>  for_each       = aws_subnet.private_subnets<br>  subnet_id      = each.value.id<br>}</pre><p><strong>EC2.tf</strong></p><pre>data &quot;aws_ami&quot; &quot;ubuntu&quot; {<br>  most_recent = true<br>filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*&quot;]<br>  }<br>  filter {<br>    name   = &quot;virtualization-type&quot;<br>    values = [&quot;hvm&quot;]<br>  }<br>  owners = [&quot;099720109477&quot;] # Canonical<br>}<br>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  ami                         = data.aws_ami.ubuntu.id<br>  instance_type               = &quot;t3.micro&quot;<br>  subnet_id                   = aws_subnet.public_subnets[&quot;public_subnet_1&quot;].id<br>  associate_public_ip_address = true<br>  key_name                    = aws_key_pair.ec2_key_pair.key_name<br>  vpc_security_group_ids = [aws_security_group.ec2_sg.id]<br>  depends_on             = [aws_key_pair.ec2_key_pair, aws_security_group.ec2_sg]<br>  tags = {<br>    Name = &quot;For RDS&quot;<br>  }<br>}<br><br># Security group for EC2 Instance<br>resource &quot;aws_security_group&quot; &quot;ec2_sg&quot; {<br>  name        = &quot;ec2_sg&quot;<br>  description = &quot;Allow SSH inbound traffic&quot;<br>  vpc_id      = aws_vpc.rds_vpc.id<br>  depends_on  = [aws_vpc.rds_vpc]<br>  ingress {<br>    description = &quot;Allow SSH&quot;<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;] # Should restrict to your IP (e.g., x.x.x.x/32)<br>  }<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>  tags = {<br>    Name = &quot;ec2_sg&quot;<br>  }<br>}<br><br># Key Pair for EC2 Instance<br>resource &quot;local_sensitive_file&quot; &quot;tf_key&quot; {<br>  content              = tls_private_key.rsa.private_key_pem<br>  file_permission      = &quot;600&quot;<br>  directory_permission = &quot;700&quot;<br>  filename             = &quot;${aws_key_pair.ec2_key_pair.key_name}.pem&quot;<br>}<br><br>resource &quot;aws_key_pair&quot; &quot;ec2_key_pair&quot; {<br>  key_name   = &quot;ec2_key_pair&quot;<br>  public_key = tls_private_key.rsa.public_key_openssh<br>}<br><br>resource &quot;tls_private_key&quot; &quot;rsa&quot; {<br>  algorithm = &quot;RSA&quot;<br>  rsa_bits  = 4096<br>}</pre><p><strong>RDS.tf</strong></p><pre># Create a RDS Database Instance<br>resource &quot;aws_db_instance&quot; &quot;myrdsinstance&quot; {<br>  engine                 = &quot;mysql&quot;<br>  identifier             = &quot;myrdsinstance&quot;<br>  allocated_storage      = 5<br>  engine_version         = &quot;8.0&quot;<br>  instance_class         = &quot;db.t3.micro&quot;<br>  username               = var.username<br>  password               = var.password<br>  parameter_group_name   = &quot;default.mysql8.0&quot;<br>  vpc_security_group_ids = [&quot;${aws_security_group.rds_sg.id}&quot;]<br>  skip_final_snapshot    = true<br>  publicly_accessible    = false<br>  db_subnet_group_name   = aws_db_subnet_group.rds_subnets.name<br>  multi_az               = true<br>}<br><br>resource &quot;aws_db_subnet_group&quot; &quot;rds_subnets&quot; {<br>  name       = &quot;my-db-subnet-group&quot;<br>  subnet_ids = [aws_subnet.private_subnets[&quot;private_subnet_1&quot;].id, aws_subnet.private_subnets[&quot;private_subnet_2&quot;].id]<br>}<br><br># To Create a security group for RDS Database Instance<br>resource &quot;aws_security_group&quot; &quot;rds_sg&quot; {<br>  name   = &quot;rds_sg&quot;<br>  vpc_id = aws_vpc.rds_vpc.id<br>  ingress {<br>    from_port   = 3306<br>    to_port     = 3306<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [aws_instance.web.private_ip]<br>  }<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><strong>variables.tf</strong></p><pre>variable &quot;aws_region&quot; {<br>  type    = string<br>  default = &quot;us-east-1&quot;<br>}<br><br>variable &quot;vpc_cidr&quot; {<br>  type    = string<br>  default = &quot;10.0.0.0/16&quot;<br>}<br><br>variable &quot;public_subnets&quot; {<br>  default = {<br>    &quot;public_subnet_1&quot; = 0<br>  }<br>}<br><br>variable &quot;private_subnets&quot; {<br>  default = {<br>    &quot;private_subnet_1&quot; = 1<br>    &quot;private_subnet_2&quot; = 2<br>  }<br>}<br>variable &quot;key_name&quot; {<br>  type        = string<br>  default     = &quot;terraform-key-pair&quot;<br>  description = &quot;key pair generated by terraform&quot;<br>}<br><br>variable &quot;username&quot; {<br>  default = &quot;your-username&quot;<br>  type    = string<br>}<br>variable &quot;password&quot; {<br>  default = &quot;your-password&quot;<br>  type    = string<br>}</pre><p><strong>outputs.tf</strong></p><pre>output &quot;security_group_id&quot; {<br>  value = aws_security_group.rds_sg.id<br>}<br><br>output &quot;db_instance_endpoint&quot; {<br>  value = aws_db_instance.myrdsinstance.endpoint<br>}<br><br>output &quot;db_instance_id&quot; {<br>  value = aws_db_instance.myrdsinstance.id<br>}<br><br>output &quot;vpc_id&quot; {<br>  value = aws_vpc.rds_vpc.id<br>}<br><br>output &quot;ec2_public_ipv4&quot; {<br>  value = aws_instance.web.public_ip<br>}<br><br>output &quot;ec2_id&quot; {<br>  value = aws_instance.web.id<br>}</pre><h4>Running the Configuration</h4><p>Execute the following commands to deploy the resources:</p><pre>terraform init     # Initialize the working directory  <br>terraform validate # Validate the configuration  <br>terraform plan     # Generate and display an execution plan  <br>terraform apply    # Apply the configuration</pre><p>When prompted, type yes to confirm the deployment.</p><h4>Accessing the EC2 and RDS Instances</h4><ol><li><strong>SSH into the EC2 Instance</strong></li></ol><pre>ssh -i &quot;ec2_key_pair.pem&quot; ubuntu@&lt;EC2-PUBLIC-IP&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*OSTyUwERRCGFJBDEGK8L1w.png" /></figure><p><strong>2. Connect to the RDS MySQL Instance</strong></p><pre>mysql -h &lt;RDS-ENDPOINT&gt; -P 3306 -u &lt;USERNAME&gt; -p</pre><h4>Lessons Learned</h4><ol><li><strong>Security</strong>: Avoid storing sensitive data (e.g., passwords) in plain text. Use tools like AWS Secrets Manager.</li><li><strong>State Management</strong>: Store state files securely using Terraform Cloud or S3 backend to ensure safe collaboration and disaster recovery.</li></ol><h4>FAQs</h4><ol><li><strong>Why use a NAT Gateway?</strong><br>To allow private subnets to access the internet for updates while maintaining security by blocking inbound internet traffic.</li><li><strong>Why use a private subnet for RDS?</strong><br>The RDS instance should not be publicly accessible. Only the EC2 instance should communicate with it to enhance security.</li></ol><h4>Conclusion</h4><p>Thanks for following along! Feel free to check out the GitHub <a href="https://github.com/Ayolowo/Terraform-cicd">repo</a> for the complete code. I’ll be sharing more projects soon — stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ed8a42f84e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>