<?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 Tayo Efunshile on Medium]]></title>
        <description><![CDATA[Stories by Tayo Efunshile on Medium]]></description>
        <link>https://medium.com/@tayoefunshile?source=rss-f10ea4bb7f26------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jM3z6SsNvQJc5la6xHQ8Wg.png</url>
            <title>Stories by Tayo Efunshile on Medium</title>
            <link>https://medium.com/@tayoefunshile?source=rss-f10ea4bb7f26------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:49:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tayoefunshile/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[Migrating Manually Built DigitalOcean Infrastructure to Terraform Management]]></title>
            <link>https://medium.com/@tayoefunshile/migrating-manually-built-digitalocean-infrastructure-to-terraform-management-5374bed4966e?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/5374bed4966e</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[iac]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Wed, 30 Apr 2025 12:38:21 GMT</pubDate>
            <atom:updated>2025-04-30T12:38:21.073Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>I was tasked with having an already existing infrastructure, managed via an IaC tool (Terraform in this case). So here’s a walk-through on the process of transitioning a manually created DigitalOcean infrastructure consisting of droplets, block storage volumes, volume snapshots, database clusters, firewalls, and floating IPs into a Terraform-managed setup. The project was executed for a k3s Kubernetes cluster running on DigitalOcean droplets. The goal is to generate Terraform configurations that mirror the existing infrastructure, import resources into Terraform’s state, resolve configuration mismatches, and automate future changes via GitHub Actions.</p><p>Key challenges included handling Kubernetes-managed Persistent Volume Claims (PVCs), fixing validation errors, and manually aligning generated configurations with the actual state. This document emphasizes lessons learned, common errors, and manual interventions required to achieve a clean terraform plan.</p><p>I’ve uploaded a bashscript for automating the importation on this repository <a href="https://github.com/Oluty-1/terraform-generate.git"><strong>here</strong></a>, I’ll be making references to it as we go on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6wOpa28p7E_-DwEb6iLMw.png" /></figure><h3>Prerequisites</h3><ul><li><strong>Tools</strong>:</li><li>Terraform (v1.9.0 or later)</li><li><strong>doctl</strong> (DigitalOcean CLI, authenticated with an API token)</li><li>Git</li><li>Bash shell</li><li>Text editor (e.g., VS Code)</li><li><strong>Access</strong>:</li><li>DigitalOcean account with API token</li><li>AWS credentials for S3-compatible state storage (DigitalOcean Spaces)</li><li>GitHub repository with write access</li><li><strong>Knowledge</strong>:</li><li>Basic Terraform concepts (resources, state, providers, modules)</li><li>Familiarity with DigitalOcean resources</li><li>Basic Kubernetes understanding</li><li><strong>Environment</strong>:</li><li>Ubuntu-based system (e.g., Ubuntu 24.04)</li><li>Working directory: ~/DevOps/Inawo/Staging/inawo-api/terraform</li></ul><h3>Step-by-Step Process</h3><h3>Step 1: Understand the Existing Infrastructure</h3><p>Catalog all DigitalOcean resources to ensure complete coverage.</p><ol><li><strong>List Resources</strong>:</li></ol><ul><li><strong>Droplets</strong>:</li></ul><pre>doctl compute droplet list --format ID,Name,Region,Image,Size,PublicIPv4,PrivateIPv4,Tags,Features</pre><ul><li>Example: Droplets named monitoring, production, staging, vpn with features like backups, monitoring, ipv6, private_networking.</li><li><strong>Volumes</strong>:</li></ul><pre>doctl compute volume list --format ID,Name,Size,Region,DropletIDs</pre><p>Note PVCs with names like pvc-6334efff-... (Kubernetes-managed).</p><ul><li><strong>Database Clusters</strong>:</li></ul><pre>doctl databases list --format ID,Name,Engine,Version,Region,Size</pre><ul><li>Example: db-postgresql-fra01-production.</li><li><strong>Firewalls</strong>:</li></ul><pre>doctl compute firewall list --format ID,Name,InboundRules,OutboundRules,Tags</pre><p><strong>Document</strong>:</p><ul><li>Create a spreadsheet or text file listing resource IDs, names, regions, sizes, tags, and features.</li><li>Flag Kubernetes-managed resources (PVCs, CSI snapshots) for exclusion from Terraform.</li></ul><p><strong>Common Error</strong>: Importing PVCs or CSI snapshots causes conflicts with the k3s CSI driver. Verify PVCs with:</p><p><strong>Lesson Learned</strong>: Exclude resources with pvc- prefixes, as they’re dynamically managed by Kubernetes.</p><h3>Step 2: Set Up Terraform Environment</h3><p>Initialize a Terraform project with a modular structure.</p><ol><li><strong>Create Directory</strong>: Create the directory in which yo wanna work in.</li><li><strong>Run the Import Script</strong>:<br>Use the provided generate_tf.sh to set up the directory structure, provider configs, and main module: make the scrip executable:</li></ol><pre>chmod +x generate_tf.sh ./generate_tf.sh</pre><ul><li>Creates: compute/, database/, network/, storage/, project/ directories.</li><li>Generates: main.tf, providers.tf, outputs.tf, variables.tf.</li></ul><p><strong>3. Configure State Backend</strong>:<br>The script sets up an S3-compatible backend in providers.tf. For this to work, create an s3 bucket on aws, and rename the configuration in the providers section in line 105 of the script</p><pre>  backend &quot;s3&quot; {<br>    bucket         = &quot;Test-terraform-state&quot;  <br>    key            = &quot;digitalocean/terraform.tfstate&quot;         <br>    region         = &quot;us-east-1&quot;                 <br>  }</pre><p>4. Set AWS credentials for Spaces: since the testing is being done locally, have aws credentials set in order for terraform to be able to connect to the s3 bucket.</p><p><strong>5. Initialize Terraform</strong>:</p><pre>terraform init</pre><p><strong>Why This Structure?</strong></p><ul><li><strong>Modular Design</strong>: Separating compute, database, network, storage, and project into modules improves organization and scalability.</li><li><strong>S3 Backend</strong>: Ensures state is stored remotely, preventing conflicts in team environments and enabling CI/CD.</li><li><strong>Explicit Provider Version</strong>: Locks digitalocean to 2.50.0 for consistency.</li></ul><p><strong>Common Error</strong>: Missing AWS credentials cause terraform init to fail. Ensure environment variables are set.</p><h3>Step 3: Generate Terraform Configurations</h3><p>The generate_tf.sh script automates configuration generation using doctl. Below, we break down the <strong>droplet section</strong> to explain its logic and how it handles importation, as it’s representative of the script’s approach.</p><h4>Droplet Section Breakdown</h4><p>The script’s droplet section performs two tasks: generating .tf files and importing resources.</p><ol><li><strong>Fetch Droplets</strong>:</li></ol><pre>droplets=$(doctl compute droplet list --format ID,Name --no-header)</pre><ul><li>Queries DigitalOcean for all droplets, extracting ID and Name (e.g., 487709967 monitoring).</li></ul><p><strong>2. Create Supporting Files</strong>:</p><ul><li><strong>Variables</strong> (compute/variables.tf):</li></ul><pre>  cat &gt; compute/variables.tf &lt;&lt; &#39;EOF&#39;<br>variable &quot;region&quot; {<br>  description = &quot;DigitalOcean region&quot;<br>  type        = string<br>  default     = &quot;fra1&quot;<br>}<br>EOF</pre><p>Allows region customization.</p><ul><li><strong>Outputs</strong> (compute/outputs.tf):</li></ul><pre>output &quot;droplet_ips&quot; {<br>  description = &quot;IPs of all droplets&quot;<br>  value = {<br>    &quot;monitoring&quot; = digitalocean_droplet.droplet_monitoring.ipv4_address<br>    # ... other droplets<br>  }<br>}<br>output &quot;droplet_ids&quot; {<br>  description = &quot;IDs of all droplets&quot;<br>  value = {<br>    &quot;monitoring&quot; = digitalocean_droplet.droplet_monitoring.id<br>    # ... other droplets<br>  }<br>}</pre><p>Exposes droplet IPs and IDs for use in other modules or outputs.</p><p><strong>3. Generate Droplet Resource Files</strong>:</p><pre>while IFS= read -r line; do<br>  id=$(echo &quot;$line&quot; | awk &#39;{print $1}&#39;)<br>  name=$(echo &quot;$line&quot; | awk &#39;{$1=&quot;&quot;; sub(/^ +/, &quot;&quot;); print}&#39;)<br>  safe_name=$(sanitize_name &quot;$name&quot;)<br>  # ... details extraction<br>  cat &gt; &quot;compute/droplet_${safe_name}.tf&quot; &lt;&lt; EOF<br>resource &quot;digitalocean_droplet&quot; &quot;droplet_${safe_name}&quot; {<br>  name   = &quot;${name}&quot;<br>  region = &quot;${region}&quot;<br>  size   = &quot;${size}&quot;<br>  image  = &quot;${image_slug}&quot;<br>  tags   = [$formatted_tags]<br>}<br>EOF<br>done &lt;&lt;&lt; &quot;$droplets&quot;</pre><p><strong>Logic</strong>:</p><ul><li><strong>Sanitization</strong>: sanitize_name converts names to lowercase and replaces special characters (e.g., monitoring → monitoring).</li><li><strong>Details Extraction</strong>:</li><li>Uses doctl compute droplet get to fetch region, memory, vcpus, image, and tags.</li><li>Maps memory-vcpus to size slugs (e.g., 2048-1 → s-1vcpu-2gb).</li><li>Normalizes image strings (e.g., Ubuntu 24.04 (LTS) x64 → ubuntu-24-04-x64).</li><li><strong>Output</strong>: Creates files like compute/droplet_monitoring.tf with minimal attributes.</li><li><strong>Why Minimal?</strong>: Avoids unconfigurable attributes (e.g., volume_ids) and reduces initial errors. Features like backups are omitted to prevent forced replacements.</li></ul><p><strong>4. Import Droplets</strong>:</p><pre>while IFS= read -r line; do<br>  id=$(echo &quot;$line&quot; | awk &#39;{print $1}&#39;)<br>  name=$(echo &quot;$line&quot; | awk &#39;{$1=&quot;&quot;; sub(/^ +/, &quot;&quot;); print}&#39;)<br>  safe_name=$(sanitize_name &quot;$name&quot;)<br>  terraform import &quot;module.compute.digitalocean_droplet.droplet_${safe_name}&quot; &quot;$id&quot;<br>done &lt;&lt;&lt; &quot;$droplets&quot;</pre><p><strong>Logic</strong>:</p><ul><li>Iterates over droplets, using their IDs to import into Terraform state.</li><li>Addresses resources as module.compute.digitalocean_droplet.droplet_${safe_name} to match the module structure.</li><li>Imports ensure Terraform recognizes existing droplets without recreating them.</li><li><strong>Why After Generation?</strong>: Importing after creating .tf files ensures Terraform has resource definitions to map to state.</li></ul><p><strong>Why This Approach?</strong></p><ul><li><strong>Automation</strong>: Using doctl avoids manual .tf file creation.</li><li><strong>Modularity</strong>: Placing droplets in compute/ keeps the project organized.</li><li><strong>Error Handling</strong>: The script exits on import failures, alerting users to issues.</li><li><strong>Minimal Configs</strong>: Starting with basic attributes reduces validation errors, allowing manual refinements later.</li></ul><p><strong>Common Errors</strong>:</p><ul><li><strong>Invalid Size Slug</strong>: The script’s fallback (s-${vcpus}vcpu-$((memory / 1024))gb) may produce incorrect slugs (e.g., s-1vcpu-2gb instead of s-1vcpu-2gb-amd). Check doctl output for exact slugs.</li><li><strong>Image Slug Errors</strong>: Misparsed images (e.g., ubuntu-2410x64b320f2ef-...) due to appended VPC IDs. Manually correct to ubuntu-24-10-x64.</li><li><strong>Import Failures</strong>: Typos in safe_name or missing .tf files cause terraform import to fail. Verify file existence and names.</li></ul><p><strong>Other Resources</strong>:<br>The script follows a similar pattern for databases, firewalls, floating IPs, volumes, and snapshots:</p><ul><li>Generates .tf files with doctl data.</li><li>Creates variables.tf and outputs.tf.</li><li>Imports resources using IDs.</li><li>Skips PVCs for volumes and snapshots using grep -q &quot;^pvc-&quot;.</li></ul><h3>Step 4: Import Resources into Terraform State</h3><p>The script imports all resources after generating .tf files.</p><ol><li><strong>Run Imports</strong>:</li></ol><ul><li>The script’s import steps (e.g., terraform import module.compute.digitalocean_droplet.droplet_monitoring 5365757967) map existing resources to Terraform state.</li><li>Verify with:</li></ul><pre>terraform state list</pre><ol><li><strong>Handle Errors</strong>:</li></ol><ul><li><strong>Resource Not Found</strong>: Ensure IDs match doctl output.</li></ul><p><strong>Lesson Learned</strong>: Importing in a single script run ensures consistency but requires accurate .tf files first.</p><h3>Step 5: Resolve Configuration Mismatches</h3><p>The generated .tf files are minimal and often mismatch the actual state, requiring manual edits.</p><ol><li><strong>Run Initial Plan</strong>:</li></ol><pre>terraform validate <br>terraform plan</pre><ul><li>Expect differences (e.g., forced droplet replacements, missing firewall rules).</li></ul><p><strong>2. Common Issues and Manual Fixes</strong>:</p><ul><li><strong>Droplets</strong>:</li><li><strong>Missing Features</strong>: Add backups, monitoring, ipv6, vpc_uuid:</li></ul><pre>resource &quot;digitalocean_droplet&quot; &quot;droplet_monitoring&quot; {<br>  name      = &quot;monitoring&quot;<br>  region    = &quot;fra1&quot;<br>  size      = &quot;s-1vcpu-2gb-amd&quot;<br>  image     = &quot;ubuntu-24-04-x64&quot;<br>  tags      = [&quot;critical&quot;]<br>  backups   = true<br>  monitoring = true<br>  ipv6      = true<br>}</pre><ul><li><strong>Size Mismatch</strong>: Update to exact slugs (e.g., s-1vcpu-2gb-amd).</li><li><strong>Image Mismatch</strong>: Correct to ubuntu-24-04-x64 or ubuntu-24-10-x64.</li><li><strong>Error</strong>: Forced replacements due to missing features. Use doctl compute droplet get --format Features to verify.</li></ul><p><strong>Firewalls</strong>:</p><ul><li><strong>Placeholder Rules</strong>: The script generates dummy rules:</li></ul><pre>inbound_rule {<br>  protocol         = &quot;tcp&quot;<br>  port_range       = &quot;22&quot;<br>  source_addresses = [&quot;0.0.0.0/0&quot;]<br>}</pre><ul><li><strong>Fix</strong>: Run terraform state show module.network.digitalocean_firewall.firewall_&lt;name&gt; and copy actual rules:</li></ul><pre>inbound_rule {<br>  protocol         = &quot;tcp&quot;<br>  port_range       = &quot;22&quot;<br>  source_addresses = [&quot;0.0.0.0/0&quot;, &quot;::/0&quot;]<br>}<br>inbound_rule {<br>  protocol         = &quot;tcp&quot;<br>  port_range       = &quot;443&quot;<br>  source_addresses = [&quot;0.0.0.0/0&quot;, &quot;::/0&quot;]<br>}</pre><ul><li><strong>Error</strong>: Missing rules cause Terraform to remove them. Always verify with doctl.</li></ul><p><strong>Databases</strong>:</p><ul><li><strong>Size Mismatch</strong>: Update size (e.g., db-amd-1vcpu-2gb instead of db-s-1vcpu-1gb).</li><li><strong>Error</strong>: Incorrect sizes trigger updates. Check doctl databases list.</li><li><strong>Volumes/Snapshots</strong>:</li><li><strong>PVC Conflicts</strong>: The script skips PVCs, but snapshots like pvc-982125b2-...-1743260800939 may be imported. Remove them:</li></ul><pre>terraform state rm module.storage.digitalocean_volume_snapshot.snapshot_pvc_982125b2_627f_4a40_96cc_65d8rt613b75_1743298250939<br>rm storage/snapshot_pvc_984565b2_627f_4a40_96cc_65d8cdfn37b75_1743260800939.tf</pre><p><strong>3. Iterate</strong>:</p><ul><li>Edit .tf files based on terraform plan output.</li><li>Re-run:</li></ul><pre>terraform validate<br>terraform plan</pre><ul><li>Aim for “No changes.”</li></ul><p><strong>Common Errors</strong>:</p><ul><li><strong>Forced Replacements</strong>: Droplets are recreated if features (e.g., backups) or sizes differ. Align configs with doctl output.</li><li><strong>Drift</strong>: Resources deleted outside Terraform (e.g., vpn droplet) cause recreation plans. Remove from state:</li></ul><pre>terraform state rm module.compute.digitalocean_droplet.droplet_vpn<br>rm compute/droplet_vpn.tf</pre><p><strong>Lesson Learned</strong>: Manual edits are critical due to incomplete doctl data and Kubernetes complexities. Always cross-check with doctl and terraform state show.</p><h3>Conclusion</h3><p>This process successfully migrated a DigitalOcean infrastructure to Terraform, handling droplets, databases, firewalls, floating IPs, and volumes while navigating Kubernetes PVCs. Manual configuration edits were crucial to align generated files with the actual state.</p><p>Most of the errors referred to here were ones I encountered during the configuration process. yours might differ, but whatever the differences are, usingdoctl and terraform state showwill always help you diagnose and fix the errors till you get a perfect terraform setup for your infrastruture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5374bed4966e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transfering Manually Built AWS Infrastructure Into Terraform.]]></title>
            <link>https://medium.com/@tayoefunshile/transfering-manually-built-aws-infrastructure-into-terraform-7585fa1cc5a1?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/7585fa1cc5a1</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 21:18:20 GMT</pubDate>
            <atom:updated>2024-12-23T21:18:20.126Z</atom:updated>
            <content:encoded><![CDATA[<p>There are scenarios where resources on an infrastructure are created and configured manually on AWS console, which is fine, but not ideal because it becomes stressful and time consuming when you need to manually delete, recreate and configure certain resources multiple times during testing and troubleshooting, this is where <strong>Infrastructure As Code (IAC)</strong> comes in.</p><p>And in a case where the infrastructure has already been built, Terraform has a feature that allows for manual importation of resources and it’s configuration. But there’s a faster and better tool for doing this, <strong>Terraformer</strong>, this tool auto generates .tf files and the terraform.tfstate files for resources being imported. And this process can be automates using <strong>bash scripting</strong>.</p><p>Prerequisites:</p><ol><li>Install Terraform: refer to <a href="https://medium.com/aws-tip/automating-infrastructure-management-terraform-intro-c31573a80614"><strong>this on how to</strong></a>.</li><li>Install Terraformer:</li></ol><p>For the installation of terraformer, here’s the full<strong> </strong><a href="https://github.com/GoogleCloudPlatform/terraformer?tab=readme-ov-file"><strong>github resource and documentation</strong></a>, I’m using a linux OS, so the relevant command for the installation process for me is this:</p><pre>export PROVIDER=all<br>curl -LO &quot;https://github.com/GoogleCloudPlatform/terraformer/releases/download/$(curl -s https://api.github.com/repos/GoogleCloudPlatform/terraformer/releases/latest | grep tag_name | cut -d &#39;&quot;&#39; -f 4)/terraformer-${PROVIDER}-linux-amd64&quot;<br>chmod +x terraformer-${PROVIDER}-linux-amd64<br>sudo mv terraformer-${PROVIDER}-linux-amd64 /usr/local/bin/terraformer</pre><p>Steps:</p><ol><li>List out all the resources on the AWS account</li><li>Sort the resources to account for dependencies</li><li>Initialize Terraform</li><li>Write a bash script to automate the process of using terraformer to auto-generate state files and .tf files for the resources on the aws account.</li></ol><p>Here’s a list of resources on aws arranged in order to account for dependencies</p><pre>    # Network Foundation<br>    &quot;vpc&quot;<br>    &quot;subnet&quot;<br>    &quot;route_table&quot;<br>    &quot;igw&quot;<br>    &quot;nat&quot;<br>    &quot;transit_gateway&quot;<br>    &quot;vpc_peering&quot;<br>    <br>    # Security &amp; Identity<br>    &quot;sg&quot;<br>    &quot;nacl&quot;<br>    &quot;iam&quot;<br>    &quot;kms&quot;<br>    &quot;secretsmanager&quot;<br>    &quot;identitystore&quot;<br>    &quot;cognito&quot;<br>    <br>    # Networking Advanced<br>    &quot;customer_gateway&quot;<br>    &quot;vpn_connection&quot;<br>    &quot;vpn_gateway&quot;<br>    &quot;route53&quot;<br>    <br>    # Compute<br>    &quot;ec2_instance&quot;<br>    &quot;auto_scaling&quot;<br>    &quot;eks&quot;<br>    &quot;lambda&quot;<br>    &quot;batch&quot;<br>    &quot;elastic_beanstalk&quot;<br>    &quot;workspaces&quot;<br>    <br>    # Containers<br>    &quot;ecr&quot;<br>    &quot;ecrpublic&quot;<br>    &quot;ecs&quot;<br>    <br>    # Load Balancing &amp; Routing<br>    &quot;elb&quot;<br>    &quot;alb&quot;<br>    &quot;api_gateway&quot;<br>    <br>    # Databases<br>    &quot;dynamodb&quot;<br>    &quot;rds&quot;<br>    &quot;redshift&quot;<br>    &quot;docdb&quot;<br>    &quot;elasticache&quot;<br>    &quot;qldb&quot;<br>    <br>    # Storage<br>    &quot;s3&quot;<br>    &quot;ebs&quot;<br>    &quot;efs&quot;<br>    &quot;eip&quot;<br>    <br>    # Monitoring &amp; Logging<br>    &quot;cloudwatch&quot;<br>    &quot;logs&quot;<br>    &quot;cloudtrail&quot;<br>    &quot;config&quot;<br>    &quot;xray&quot;<br>    <br>    # Application Services<br>    &quot;appsync&quot;<br>    &quot;sns&quot;<br>    &quot;sqs&quot;<br>    &quot;sfn&quot;<br>    &quot;ses&quot;<br>    &quot;kinesis&quot;<br>    &quot;firehose&quot;<br>    &quot;media_store&quot;<br>    &quot;media_package&quot;<br>    &quot;medialive&quot;<br>    <br>    # Management &amp; Governance<br>    &quot;cloudformation&quot;<br>    &quot;organization&quot;<br>    &quot;servicecatalog&quot;<br>    &quot;opsworks&quot;<br>    &quot;cloud9&quot;<br>    &quot;resourcegroups&quot;<br>    &quot;budgets&quot;<br>    <br>    # Security Services<br>    &quot;waf&quot;<br>    &quot;waf_regional&quot;<br>    &quot;wafv2_cloudfront&quot;<br>    &quot;wafv2_regional&quot;<br>    &quot;accessanalyzer&quot;<br>    &quot;acm&quot;<br>    &quot;securityhub&quot;<br>    <br>    # Misc<br>    &quot;cloudfront&quot;<br>    &quot;cloudhsm&quot;<br>    &quot;codebuild&quot;<br>    &quot;codecommit&quot;<br>    &quot;codedeploy&quot;<br>    &quot;codepipeline&quot;<br>    &quot;datapipeline&quot;<br>    &quot;devicefarm&quot;<br>    &quot;glue&quot;<br>    &quot;iot&quot;<br>    &quot;msk&quot;<br>    &quot;swf&quot;<br>)</pre><p>The command for using terraformer to import a specific resource, say the vpc for example, and generating the state file for it is:</p><pre>terraformer import aws --resources=vpc</pre><p>But we can’t do this one after the other for all the resources, so i just ran a loop using bash script to run the command for all the reources. Here’s what the full script looks like:</p><pre>#!/bin/bash<br><br># Carefully ordered to respect resource dependencies<br><br># Recommended Import Order with Dependencies<br>RESOURCES=(<br>    # Network Foundation<br>    &quot;vpc&quot;<br>    &quot;subnet&quot;<br>    &quot;route_table&quot;<br>    &quot;igw&quot;<br>    &quot;nat&quot;<br>    &quot;transit_gateway&quot;<br>    &quot;vpc_peering&quot;<br>    <br>    # Security &amp; Identity<br>    &quot;sg&quot;<br>    &quot;nacl&quot;<br>    &quot;iam&quot;<br>    &quot;kms&quot;<br>    &quot;secretsmanager&quot;<br>    &quot;identitystore&quot;<br>    &quot;cognito&quot;<br>    <br>    # Networking Advanced<br>    &quot;customer_gateway&quot;<br>    &quot;vpn_connection&quot;<br>    &quot;vpn_gateway&quot;<br>    &quot;route53&quot;<br>    <br>    # Compute<br>    &quot;ec2_instance&quot;<br>    &quot;auto_scaling&quot;<br>    &quot;eks&quot;<br>    &quot;lambda&quot;<br>    &quot;batch&quot;<br>    &quot;elastic_beanstalk&quot;<br>    &quot;workspaces&quot;<br>    <br>    # Containers<br>    &quot;ecr&quot;<br>    &quot;ecrpublic&quot;<br>    &quot;ecs&quot;<br>    <br>    # Load Balancing &amp; Routing<br>    &quot;elb&quot;<br>    &quot;alb&quot;<br>    &quot;api_gateway&quot;<br>    <br>    # Databases<br>    &quot;dynamodb&quot;<br>    &quot;rds&quot;<br>    &quot;redshift&quot;<br>    &quot;docdb&quot;<br>    &quot;elasticache&quot;<br>    &quot;qldb&quot;<br>    <br>    # Storage<br>    &quot;s3&quot;<br>    &quot;ebs&quot;<br>    &quot;efs&quot;<br>    &quot;eip&quot;<br>    <br>    # Monitoring &amp; Logging<br>    &quot;cloudwatch&quot;<br>    &quot;logs&quot;<br>    &quot;cloudtrail&quot;<br>    &quot;config&quot;<br>    &quot;xray&quot;<br>    <br>    # Application Services<br>    &quot;appsync&quot;<br>    &quot;sns&quot;<br>    &quot;sqs&quot;<br>    &quot;sfn&quot;<br>    &quot;ses&quot;<br>    &quot;kinesis&quot;<br>    &quot;firehose&quot;<br>    &quot;media_store&quot;<br>    &quot;media_package&quot;<br>    &quot;medialive&quot;<br>    <br>    # Management &amp; Governance<br>    &quot;cloudformation&quot;<br>    &quot;organization&quot;<br>    &quot;servicecatalog&quot;<br>    &quot;opsworks&quot;<br>    &quot;cloud9&quot;<br>    &quot;resourcegroups&quot;<br>    &quot;budgets&quot;<br>    <br>    # Security Services<br>    &quot;waf&quot;<br>    &quot;waf_regional&quot;<br>    &quot;wafv2_cloudfront&quot;<br>    &quot;wafv2_regional&quot;<br>    &quot;accessanalyzer&quot;<br>    &quot;acm&quot;<br>    &quot;securityhub&quot;<br>    <br>    # Misc<br>    &quot;cloudfront&quot;<br>    &quot;cloudhsm&quot;<br>    &quot;codebuild&quot;<br>    &quot;codecommit&quot;<br>    &quot;codedeploy&quot;<br>    &quot;codepipeline&quot;<br>    &quot;datapipeline&quot;<br>    &quot;devicefarm&quot;<br>    &quot;glue&quot;<br>    &quot;iot&quot;<br>    &quot;msk&quot;<br>    &quot;swf&quot;<br>)<br><br><br># Import Resources<br>for resource in &quot;${RESOURCES[@]}&quot;; do<br>    log &quot;Importing ${resource}...&quot;<br>    terraformer import aws --resources=${resource} --regions=us-east-1<br>done<br><br># Generate Import Summary<br>echo &quot;Import completed. Generated Terraform files in $(pwd)&quot;</pre><p>Create a file called “terraform_import.sh”, paste the script in it, and make it executable by running the command:</p><pre>chmod +x terraform_import.sh</pre><p>Next is to initialize Terraform, to do this, create a providers.tf file, and paste this into it(<a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs"><strong>gotten directly from terraform documentation</strong></a>):</p><pre># provider.tf<br>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>  <br>  # Configure backend (recommended)<br>#  backend &quot;s3&quot; {<br>#    bucket         = &quot;your-terraform-state-bucket&quot;<br>#    key            = &quot;terraform.tfstate&quot;<br>#    region         = &quot;us-east-1&quot;<br>#    dynamodb_table = &quot;terraform-lock&quot;<br>#    encrypt        = true<br>#  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>  # If using multiple accounts<br>  assume_role {<br>    role_arn = &quot;arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME&quot;<br>  }<br>}</pre><p>Then run the command “terraform init” to initialize terraform and have the dependencies downloaded.</p><p>Now that the bash script and terraform has been intialized, execute the bash script by using the command:</p><pre>./terraform_import.sh</pre><p>This will create a folder a folder called “generate”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*YJO7HkuefpKwrN4Cl6n50A.png" /></figure><p>Within which, folders for all the resources will be created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*U-6GKNmIiKWVowrcY8TXyw.png" /></figure><p>And in the resource folder, tf files for the resources and statefile is creates. here’s what it looks like for ECS for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*iFoy-RLsZlUIeKLbxOc_rw.png" /><figcaption>Cluster, service, Task definition and statefile created</figcaption></figure><p>The scripts runs the import command for all the aws resources, and imports the entire infrastructure locally on your computer.</p><p>After this, to verify the infrastrute state files that’s been generated locally, run the command:</p><pre>terraform plan</pre><p>This will compare the aws infrastructure on the consile to the current state file, and if there are any disparities or missing resources, it will be shown in the output.</p><p>After this, you can chose to store the state file remotely, and subsequently manage the infrastructure from code rather than console.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7585fa1cc5a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD for Docker Containers and Secret Management. Using Github Actions and Terraform]]></title>
            <link>https://medium.com/@tayoefunshile/ci-cd-for-docker-containers-and-secret-management-using-github-actions-and-terraform-8f2c7980dba2?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f2c7980dba2</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 11:57:23 GMT</pubDate>
            <atom:updated>2024-09-06T11:57:23.357Z</atom:updated>
            <content:encoded><![CDATA[<p>So… I have an application running all well and good, the one I used for <a href="https://medium.com/@tayoefunshile/containerizing-a-go-application-using-docker-d8d4dba766a9"><strong>this project</strong></a><strong>. </strong>But with continuous updates and changes to the source code, a CI/CD pipeline will be needed to automate the deployment.</p><p>For this project, asides building the infrastructure for the Continuous Integration and Continuous Delivery, I’ll also be incorporating secrets management practices in order to ensure that sensitive information aren’t exposed at any point during the entire process from the source code to the deployment.</p><p>In this project, I’ll be using:</p><ul><li>Github actions for the CI/CD</li><li>Docker for containerization</li><li>Dockerhub to store the Docker Images</li><li>Amazon ECS for deployment</li><li>AWS Secrets Manager to store environment variables</li></ul><h3>Github Workflow</h3><p>Since it’s the same source code, I’ll be creating a new branch (named it “<em>Secrets_Management</em>”) on the Github repository. create a folder names “.github” and a folder called “workflows”, in which the yaml workflow file will be written. Your folder structure should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*-71YKbQvYzBpI23a3WFSoQ.png" /></figure><p>And in the workflow, you’ll be interacting with Dockerhb and AWS, so in order for the workflow to have the permission to do so, Dockerhub tokens and AWS Credentials will need to be added to the repository’s Github secrets.</p><p>Here’s my workflow, and i’ll break it down for easy inderstanding:</p><pre>name: Build and Push Docker Image<br><br>on:<br>  push:<br>    branches:<br>      # - Secrets_Management<br>  pull_request:<br>    branches:<br>      # - Secrets_Management<br><br>env:<br>  # Credentials for dockerhub<br>  DOCKER_HUB_USERNAME: ${{ secrets.DOCKER_HUB_USERNAME }}<br>  DOCKER_HUB_ACCESS_TOKEN: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}<br>  # Credentials for AWS<br>  AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>  AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>  # AWS region<br>  AWS_REGION: us-east-2<br>  # ECS-specific variables<br>  ECS_CLUSTER: apex<br>  ECS_SERVICE: apexappsvc<br>  ECS_TASK_DEFINITION: apexapptask<br>  CONTAINER_NAME: apexapp<br><br><br>jobs:<br>  build:<br>    name: &quot;Build, Push, and Deploy Docker Image to ECS&quot;<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout code<br>      uses: actions/checkout@v2<br><br>    - name: Set up Docker Buildx<br>      uses: docker/setup-buildx-action@v3<br><br>    - name: Cache Docker layers<br>      uses: actions/cache@v3<br>      with:<br>        path: /tmp/.buildx-cache<br>        key: ${{ runner.os }}-buildx-${{ github.sha }}<br>        restore-keys: |<br>          ${{ runner.os }}-buildx-<br><br>    - name: Log in to Docker Hub<br>      uses: docker/login-action@v3<br>      with:<br>        username: ${{ env.DOCKER_HUB_USERNAME }}<br>        password: ${{ env.DOCKER_HUB_ACCESS_TOKEN }}<br><br>    - name: Install Docker Compose<br>      run: |<br>        sudo curl -L &quot;https://github.com/docker/compose/releases/download/$(curl -s https://api.github.com/repos/docker/compose/releases/latest | jq -r .tag_name)/docker-compose-$(uname -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose<br>        sudo chmod +x /usr/local/bin/docker-compose<br><br>    - name: Build and tag Docker image using Docker Compose<br>      id: build<br>      run: |<br>        BUILD_NUMBER=${{ github.run_number }}<br>        docker-compose -f docker-compose.yaml build<br>        docker tag oluty/apexapp:latest ${{ env.DOCKER_HUB_USERNAME }}/apexapp:$BUILD_NUMBER<br>        docker tag oluty/apexapp:latest ${{ env.DOCKER_HUB_USERNAME }}/apexapp:latest<br>        echo &quot;BUILD_NUMBER=$BUILD_NUMBER&quot; &gt;&gt; $GITHUB_ENV<br><br>    - name: Push Docker image<br>      run: |<br>        docker push ${{ env.DOCKER_HUB_USERNAME }}/apexapp:${{ env.BUILD_NUMBER }}<br>        docker push ${{ env.DOCKER_HUB_USERNAME }}/apexapp:latest<br><br>    - name: Install AWS CLI<br>      run: |<br>        pip install --user awscli<br>    <br>    - name: Update ECS Service<br>      run: |<br>        aws ecs update-service \<br>          --region ${{ env.AWS_REGION }} \<br>          --cluster ${{ env.ECS_CLUSTER }} \<br>          --service ${{ env.ECS_SERVICE }} \<br>          --force-new-deployment</pre><p>Here’s a breakdown:</p><h4>1. Workflow Name and Triggers</h4><ul><li><strong>name: Build and Push Docker Image</strong>: This is the name of the workflow.</li><li><strong>on: push and pull_request</strong>: The workflow is triggered on a push or a pull request to specific branches, in this case,Secrets_Management branch.</li></ul><h4>2. Environment Variables</h4><ul><li><strong>env:</strong> This section defines environment variables used throughout the workflow. The variables include:</li><li><strong>DOCKER_HUB_USERNAME</strong> and <strong>DOCKER_HUB_ACCESS_TOKEN</strong>: Credentials for logging in to Docker Hub, retrieved securely from GitHub Secrets.</li><li><strong>AWS_ACCESS_KEY_ID</strong> and <strong>AWS_SECRET_ACCESS_KEY</strong>: AWS credentials, also retrieved from GitHub Secrets.</li><li><strong>AWS_REGION</strong>: The AWS region where the ECS cluster is located.</li><li><strong>ECS_CLUSTER, ECS_SERVICE, ECS_TASK_DEFINITION, CONTAINER_NAME</strong>: ECS-specific variables used to identify the ECS cluster, service, task definition, and container.</li></ul><h4>3. Job Definition</h4><ul><li><strong>jobs:</strong> This section defines the build job that runs on an Ubuntu runner (runs-on: ubuntu-latest).</li></ul><h4>Steps within the build job:</h4><p><strong>1) Checkout Code</strong></p><ul><li><strong>actions/checkout@v2</strong>: This action checks out the code from the repository so that it can be used in the workflow.</li></ul><p><strong>2) Set up Docker:</strong></p><p>This part was copied directly from <a href="https://github.com/marketplace/actions/build-and-push-docker-images"><strong>docker marketplace</strong></a>. It basically just sets up docker for the workflow</p><p><strong>3) Log in to Docker Hub</strong></p><ul><li><strong>docker/login-action@v3</strong>: Logs in to Docker Hub using the credentials provided in the environment variables (DOCKER_HUB_USERNAME and DOCKER_HUB_ACCESS_TOKEN).</li></ul><p><strong>4) Install Docker Compose</strong></p><ul><li><strong>run:</strong> Installs Docker Compose using a command that downloads the latest release from GitHub and makes it executable.</li></ul><p><strong>5) Build and Tag Docker Image using Docker Compose</strong></p><ul><li><strong>run:</strong></li><li><strong>BUILD_NUMBER=${{ github.run_number }}</strong>: Assigns a unique build number to each run of the workflow.</li><li><strong>docker-compose -f docker-compose.yaml build</strong>: Builds the Docker image using docker-compose.yaml.</li><li><strong>docker tag</strong>: Tags the built image with both the unique build number and the latest tag, this makes versioning easier when publishing to Dockerhub.</li></ul><p><strong>6) Push Docker Image</strong></p><ul><li><strong>run:</strong> Pushes both the versioned and latest tags of the Docker image to Docker Hub.</li></ul><p><strong>7) Install AWS CLI</strong></p><ul><li><strong>run:</strong> Installs the AWS CLI using pip to interact with AWS services.</li></ul><p><strong>8) Update ECS Service</strong></p><ul><li><strong>run:</strong> This step updates the ECS service to deploy the new Docker image. The command forces a new deployment in the specified ECS cluster and service, triggering the deployment of the newly pushed image.</li></ul><p>The workflow is done, Next is to setup ECS. This can be done manually on the AWS console, but for the sake of automation and re-usability, I’ll be using an IAC took. CloudFormation and Terraform will do just fine. I’ll be using Terraform for this one.</p><p>Checkout <a href="https://awstip.com/automating-infrastructure-management-terraform-intro-c31573a80614"><strong>this blog post</strong></a> for a walk through on what terraform is and how you can install it.</p><p>Before setting up the infrastructure, we need to store the secrets, cuz we’ll be referencing it when creating some other resources.</p><h3>Managing Secrets</h3><p>Now, for the secrets management. There are 2 environment variables previously kept in the github repository in a <em>.env</em> file, the PORT and DB_URL, which I would like to store inside AWS secret manager. The idea of secret management is to have sensitive information needed for successful deployment of the application to be injected into the container at runtime, that way, this information are never revealed in the source code or at any point in the development lifecycle.</p><h4>Step 1: Store Secrets in AWS Secrets Manager</h4><ol><li>Go to the AWS Secrets Manager Console.</li><li>Choose “Store a new secret.”</li><li>Select the “Other type of secrets” option.</li></ol><ul><li>For PORT, store just the string.</li><li>For DB_URL, store just the full connection string.</li></ul><p>4. Give your secrets names.</p><p>5. Save the secret.</p><h3>ECS Infrastructure</h3><p>Now that that’s ready, let’s take a look at the resources that need to be created for the ECS Infrastructure, these include:</p><ul><li>Cluster</li></ul><p>Task Definition</p><ul><li>IAM role</li><li>Service</li><li>Target group</li><li>Security Group</li><li>Load Balancer</li></ul><p>All of which I’ll be writing terraform configuration files for. All of these resource configuration files can be gotten from <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs"><strong>Terraform Registry</strong></a>, copy and paste, then make the adjustments you need.</p><p>Create a folder in the repository for the Terraform files. First, the <strong>provider.tf</strong> file.</p><pre>provider &quot;aws&quot; {<br>  region = var.REGION<br>}</pre><ul><li>provider &quot;aws&quot;: This declares that you&#39;re using the AWS provider for Terraform, which allows you to manage AWS resources.</li></ul><p>Then the <strong>cluster.tf</strong> file:</p><pre># ECS Cluster<br>resource &quot;aws_ecs_cluster&quot; &quot;apex_cluster&quot; {<br>  name = &quot;apex&quot;<br><br>  setting {<br>    name  = &quot;containerInsights&quot;<br>    value = &quot;enabled&quot;<br>  }<br><br>  tags = {<br>    Name = &quot;apex&quot;<br>  }<br>}</pre><p><strong>1. Resource Block</strong></p><ul><li><strong>resource “aws_ecs_cluster” “apex_cluster” { … }</strong>:</li><li>The resource is identified by the logical name apex_cluster, which is used later in the Terraform configuration to reference this cluster.</li></ul><p><strong>2. Cluster Name</strong></p><ul><li><strong>name = “apex”</strong>: Specifies the name of the ECS cluster as “apex”. This name is used within AWS to identify the cluster.</li></ul><p><strong>3. Cluster Settings</strong></p><ul><li><strong>name = “containerInsights”</strong>: This setting specifies that you want to enable containerInsights, which is a feature in ECS that provides more detailed monitoring of your containers through Amazon CloudWatch.</li><li><strong>value = “enabled”</strong>:</li><li>This explicitly enables the containerInsights feature for the cluster.</li></ul><p><strong>4. Tags</strong></p><ul><li><strong>Name = “apex”</strong>: Tags the ECS cluster with the key Name and the value apex.</li></ul><p>Next, we write the <strong>iam.tf</strong> file:</p><pre>resource &quot;aws_iam_role&quot; &quot;ecs_task_execution_role&quot; {<br>  name = &quot;ecsTaskExecutionRole&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Action = &quot;sts:AssumeRole&quot;<br>        Effect = &quot;Allow&quot;<br>        Principal = {<br>          Service = &quot;ecs-tasks.amazonaws.com&quot;<br>        }<br>      }<br>    ]<br>  })<br>}<br><br># Attach the AmazonECSTaskExecutionRolePolicy managed policy to the role<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs_task_execution_policy_attachment&quot; {<br>  role       = aws_iam_role.ecs_task_execution_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy&quot;<br>}<br><br># Custom policy for accessing Secrets Manager<br>resource &quot;aws_iam_policy&quot; &quot;ecs_task_secrets_policy&quot; {<br>  name        = &quot;ecsTaskSecretsPolicy&quot;<br>  description = &quot;Policy granting ECS tasks permission to access secrets in Secrets Manager&quot;<br><br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Action = [<br>          &quot;secretsmanager:GetSecretValue&quot;<br>        ]<br>        Effect = &quot;Allow&quot;<br>        Resource = [<br>          &quot;arn:aws:secretsmanager:us-east-2:302225372317:secret:ApexSecrets_DB_URL-IYnCpn&quot;,<br>          &quot;arn:aws:secretsmanager:us-east-2:302225372317:secret:ApexSecrets-tRFSbw&quot;<br>        ]<br>      }<br>    ]<br>  })<br>}<br><br># Attach the custom secrets policy to the ECS Task Execution Role<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs_task_secrets_policy_attachment&quot; {<br>  role       = aws_iam_role.ecs_task_execution_role.name<br>  policy_arn = aws_iam_policy.ecs_task_secrets_policy.arn<br>}</pre><h4>1. IAM Role for ECS Task Execution</h4><ul><li><strong>Resource Block: </strong><strong>aws_iam_role</strong></li><li><strong>name = &quot;ecsTaskExecutionRole&quot;</strong>: The role is named ecsTaskExecutionRole.</li><li><strong>assume_role_policy = jsonencode({ ... })</strong>: This policy defines the entities that can assume this role. In this case, it allows ECS tasks to assume this role using the sts:AssumeRole action.</li><li><strong>Service = &quot;ecs-tasks.amazonaws.com&quot;</strong>: The principal that can assume this role is ECS tasks, identified by the service ecs-tasks.amazonaws.com.</li></ul><h4>2. Attach Managed Policy to ECS Task Execution Role</h4><ul><li><strong>Resource Block: </strong><strong>aws_iam_role_policy_attachment</strong></li><li><strong>role = aws_iam_role.ecs_task_execution_role.name</strong>: Attaches the managed policy AmazonECSTaskExecutionRolePolicy to the ecsTaskExecutionRole. This policy provides the necessary permissions for ECS tasks to interact with ECS services, such as pulling images from ECR or logging to CloudWatch.</li></ul><h4>3. Custom IAM Policy for Secrets Manager Access</h4><ul><li><strong>Resource Block: </strong><strong>aws_iam_policy</strong></li><li><strong>name = &quot;ecsTaskSecretsPolicy&quot;</strong>: Creates a custom IAM policy named ecsTaskSecretsPolicy.</li><li><strong>description = &quot;Policy granting ECS tasks permission to access secrets in Secrets Manager&quot;</strong>: Provides a description of what this policy is intended to do.</li><li><strong>policy = jsonencode({ ... })</strong>: The policy allows ECS tasks to access specific secrets in AWS Secrets Manager.</li><li><strong>Action = [&quot;secretsmanager:GetSecretValue&quot;]</strong>: Specifies the action allowed by this policy, which is to get the secret values.</li><li><strong>Resource = [&quot;arn:aws:secretsmanager:us-east-2:652576875425:secret:ApexSecrets_DB_URL-IYnCpn&quot;, &quot;arn:aws:secretsmanager:us-east-2:342689754648:secret:ApexSecrets-tRFSbw&quot;]</strong>:</li><li>Lists the ARNs of the specific secrets that the ECS task is allowed to access. This ensures that the ECS task can only access the specified secrets.</li></ul><h4>4. Attach Custom Policy to ECS Task Execution Role</h4><ul><li><strong>Resource Block: </strong><strong>aws_iam_role_policy_attachment</strong></li><li><strong>role = aws_iam_role.ecs_task_execution_role.name</strong>: Attaches the custom ecsTaskSecretsPolicy to the ecsTaskExecutionRole.</li></ul><p>Next, the <strong>task-definition.tf</strong> file</p><pre>resource &quot;aws_ecs_task_definition&quot; &quot;apexapptask&quot; {<br>  family                   = var.TASK_FAMILY<br>  network_mode             = &quot;awsvpc&quot;<br>  requires_compatibilities = [&quot;FARGATE&quot;]<br>  cpu                      = &quot;1024&quot;<br>  memory                   = var.MEMORY<br>  task_role_arn            = &quot;arn:aws:iam::302225372317:role/ecsTaskExecutionRole&quot;<br>  execution_role_arn       = &quot;arn:aws:iam::302225372317:role/ecsTaskExecutionRole&quot;<br><br>  container_definitions = jsonencode([<br>    {<br>      name      = var.CONTAINER_NAME<br>      image     = var.DOCKER_IMAGE<br>      cpu       = 0<br>      essential = true<br><br>      portMappings = [<br>        {<br>          name          = &quot;apexapp-3000-tcp&quot;<br>          containerPort = var.PORT<br>          hostPort      = var.PORT<br>          protocol      = &quot;tcp&quot;<br>          appProtocol   = &quot;http&quot;<br>        }<br>      ]<br><br>      secrets = [<br>        {<br>          name      = &quot;DB_URL&quot;<br>          valueFrom = var.DB_URL_SECRET<br>        },<br>        {<br>          name      = &quot;PORT&quot;<br>          valueFrom = var.PORT_SECRET<br>        }<br>      ]<br><br>      logConfiguration = {<br>        logDriver = &quot;awslogs&quot;<br>        options = {<br>          &quot;awslogs-group&quot;         = &quot;/ecs/apexapptask&quot;<br>          &quot;mode&quot;                  = &quot;non-blocking&quot;<br>          &quot;awslogs-create-group&quot;  = &quot;true&quot;<br>          &quot;max-buffer-size&quot;       = &quot;25m&quot;<br>          &quot;awslogs-region&quot;        = var.REGION<br>          &quot;awslogs-stream-prefix&quot; = &quot;ecs&quot;<br>        }<br>      }<br><br>      environment    = []<br>      mountPoints    = []<br>      volumesFrom    = []<br>      systemControls = []<br>    }<br>  ])<br><br>  tags = {<br>    Name = var.TASK_FAMILY<br>  }<br>}</pre><p>This was copied from the terraform registry, and the main changes made are:</p><ul><li><strong>family = var.TASKFAMILY</strong>: Specifies the family name of the task definition.</li><li><strong>cpu = &quot;1024&quot;</strong> and <strong>memory = &quot;2048&quot;</strong>: I chose these memory spaces as it’s the least we can get, and I don’t need much cuz it’s a small application, and also for minimal cost.</li><li><strong>task_role_arn and </strong><strong>execution_role_arn</strong>: Both set to &quot;arn:aws:iam::302225372317:role/ecsTaskExecutionRole&quot;, this specifies the IAM role that the task will use.</li></ul><p><strong>Container Definitions</strong></p><ul><li><strong>name = var.CONTAINER_NAME</strong>: Names the container apexapp as fined in the variables file.</li><li><strong>image = var.DOCKER_IMAGE</strong>: Specifies the Docker image to use for the container, pulling the latest version tagged as latest as defined in the variables file.</li><li><strong>essential = true</strong>: Marks the container as essential, meaning the task will fail if this container fails or stops.</li></ul><p><strong>Port Mappings</strong></p><ul><li><strong>portMappings = [...]</strong>: Maps the container port 3000 to the host port 3000, using TCP protocol with HTTP as the application protocol as defined in the vars.tf file. these porn numbers are specifit to this particular application.</li><li><strong>name = &quot;apexapp-3000-tcp&quot;</strong>: Provides a name for this specific port mapping for easier identification.</li></ul><p><strong>Secrets Management</strong></p><ul><li><strong>secrets = [...]</strong>: Specifies secrets to be injected into the container at runtime from AWS Secrets Manager.</li><li><strong>name = &quot;DB_URL&quot;</strong> and <strong>name = &quot;PORT&quot;</strong>: Refers to the environment variables DB_URL and PORT, with the values sourced from Secrets Manager using their respective ARNs.</li><li><strong>valueFrom = &quot;arn:aws:secretsmanager:us-east-2:302225372317:secret:ApexSecrets_DB_URL-IYnCpn&quot;</strong>: Specifies the ARN of the secret in Secrets Manager to fetch the value for the respective environment variable.</li></ul><p><strong>Log Configuration</strong></p><ul><li><strong>logConfiguration = { ... }</strong>:</li><li>Configures the container to use AWS CloudWatch Logs for logging.</li><li><strong>logDriver = &quot;awslogs&quot;</strong>:</li><li>Sets the log driver to AWS CloudWatch.</li><li><strong>awslogs-region = &quot;us-east-2&quot;</strong>:</li><li>Specifies the region for CloudWatch Logs.</li></ul><p>Next, the load balancer target group <strong>targetgroup.tf</strong> file:</p><pre>resource &quot;aws_lb_target_group&quot; &quot;apexapp_tg&quot; {<br>  name        = var.TG_NAME<br>  port        = var.PORT<br>  protocol    = &quot;HTTP&quot;<br>  vpc_id      = data.aws_vpc.default.id<br>  target_type = &quot;ip&quot;<br><br>  health_check {<br>    path                = &quot;/health&quot;<br>    interval            = 30<br>    timeout             = 5<br>    healthy_threshold   = 3<br>    unhealthy_threshold = 2<br>    matcher             = &quot;200&quot;<br>  }<br><br>  deregistration_delay = 300<br><br>  tags = {<br>    Name = var.TG_NAME<br>  }<br>}</pre><ol><li><strong>resource &quot;aws_lb_target_group&quot; &quot;apexapp_tg&quot;</strong>: This block creates an AWS Load Balancer Target Group, which is used to route requests to your ECS service.</li><li><strong>name</strong>: The name of the target group, specified by var.TG_NAME.</li><li><strong>port</strong>: The port on which the target group listens for incoming traffic, defined by var.PORT. This should match the port your application is running on within the container.</li><li><strong>protocol</strong>: The protocol used by the target group, set to &quot;HTTP&quot;. This means it will route HTTP traffic to your ECS service.</li><li><strong>vpc_id</strong>: The ID of the VPC where the target group is created, which references the default VPC ID from the data source (data.aws_vpc.default.id).</li><li><strong>health_check</strong>: <strong>path</strong>: The path that the load balancer uses to check the health of your service. In this application, the path is/health.</li></ol><ul><li><strong>interval</strong>: The time, in seconds, between health checks. Here, it is set to 30 seconds.</li><li><strong>timeout</strong>: The amount of time, in seconds, to wait for a response before considering the health check failed. Set to 5 seconds in this example.</li><li><strong>healthy_threshold</strong>: The number of consecutive successful health checks required before considering a target healthy. Here, it’s set to 3.</li><li><strong>unhealthy_threshold</strong>: The number of consecutive failed health checks required before considering a target unhealthy. Set to 2 in this example.</li><li><strong>deregistration_delay</strong>: The amount of time, in seconds, that the load balancer waits before forcibly terminating deregistering targets. This allows existing connections to complete before the target is removed. Here, it is set to 300 seconds (5 minutes).</li></ul><p>Next, the security group <strong>secgrp.tf</strong> file:</p><pre># Security Group<br>resource &quot;aws_security_group&quot; &quot;apexapp_sg&quot; {<br>  name        = var.SG_NAME<br>  description = &quot;Security group for ECS tasks in the apexappsvc service&quot;<br>  vpc_id      = data.aws_vpc.default.id<br><br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  ingress {<br>    from_port   = var.PORT<br>    to_port     = var.PORT<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<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><br>  tags = {<br>    Name = &quot;var.SG_NAME&quot;<br>  }<br>}</pre><ol><li><strong>resource &quot;aws_security_group&quot; &quot;apexapp_sg&quot;</strong>: This block creates a Security Group in AWS.</li><li><strong>name</strong>: The name of the security group, set to the value of var.SG_NAME.</li></ol><p><strong>Inbound Rules</strong></p><ol><li><strong>ingress (Port 80)</strong>: <strong>from_port and </strong><strong>to_port</strong>: Both are set to 80, allowing HTTP traffic.</li></ol><ul><li><strong>cidr_blocks</strong>: The rule allows traffic from any IP address (0.0.0.0/0), which means the ECS service will accept traffic from anywhere on the internet.</li></ul><ol><li><strong>ingress (Application Port)</strong>: <strong>from_port and </strong><strong>to_port</strong>: Both are set to var.PORT, allowing traffic on the specific port the application uses. The port value is dynamic and defined by the variable var.PORT.</li></ol><ul><li><strong>cidr_blocks</strong>: Again, this rule allows traffic from any IP address (0.0.0.0/0).</li></ul><p>Next, the load balancer configuration file <strong>alb.tf</strong>:</p><pre># Application Load Balancer<br>resource &quot;aws_lb&quot; &quot;apexapp_alb&quot; {<br>  name               = var.ALB_NAME<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [aws_security_group.apexapp_sg.id]<br>  subnets            = data.aws_subnets.default.ids<br><br>  tags = {<br>    Name = var.ALB_NAME<br>  }<br>}<br><br># Listener for Application Load Balancer<br>resource &quot;aws_lb_listener&quot; &quot;apexapp_http_listener&quot; {<br>  load_balancer_arn = aws_lb.apexapp_alb.arn<br>  port              = &quot;80&quot;<br>  protocol          = &quot;HTTP&quot;<br><br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.apexapp_tg.arn<br>  }<br>}</pre><ol><li><strong>resource &quot;aws_lb&quot; &quot;apexapp_alb&quot;</strong>: This block creates an Application Load Balancer (ALB) in AWS.</li><li><strong>name</strong>: The name of the load balancer, set to the value of var.ALB_NAME.</li><li><strong>load_balancer_type</strong>: Specifies the type of load balancer. &quot;application&quot; indicates that this is an Application Load Balancer, which is suitable for HTTP and HTTPS traffic.</li><li><strong>security_groups</strong>: Associates the security group apexapp_sg (created earlier) with the ALB. This security group controls the traffic allowed to reach the ALB.</li><li><strong>subnets</strong>: Specifies the subnets in which the ALB is deployed. It uses the default VPC subnets obtained from the data source (data.aws_subnets.default.ids).</li><li><strong>resource &quot;aws_lb_listener&quot; &quot;apexapp_http_listener&quot;</strong>: This block creates a listener for the Application Load Balancer, which listens for incoming traffic on the specified port.</li><li><strong>port</strong>: The port on which the listener listens for incoming traffic, set to 80, which is the default for HTTP traffic.</li><li><strong>protocol</strong>: The protocol used by the listener, set to &quot;HTTP&quot;. This listener will route HTTP traffic to the ALB.</li></ol><p>Next, the <strong>service.tf</strong> file:</p><pre># Data sources to get default VPC and subnets<br>data &quot;aws_vpc&quot; &quot;default&quot; {<br>  default = true<br>}<br><br>data &quot;aws_subnets&quot; &quot;default&quot; {<br>  filter {<br>    name   = &quot;vpc-id&quot;<br>    values = [data.aws_vpc.default.id]<br>  }<br>}<br><br># ECS Service<br>resource &quot;aws_ecs_service&quot; &quot;apexapp_svc&quot; {<br>  name            = var.SERVICE_NAME<br>  cluster         = aws_ecs_cluster.apex_cluster.id<br>  task_definition = aws_ecs_task_definition.apexapptask.arn<br>  desired_count   = 1<br>  launch_type     = &quot;FARGATE&quot;<br><br>  network_configuration {<br>    subnets          = data.aws_subnets.default.ids<br>    security_groups  = [aws_security_group.apexapp_sg.id]<br>    assign_public_ip = true<br>  }<br><br>  load_balancer {<br>    target_group_arn = aws_lb_target_group.apexapp_tg.arn<br>    container_name   = var.CONTAINER_NAME<br>    container_port   = var.PORT<br>  }<br><br>  depends_on = [<br>    aws_lb_listener.apexapp_http_listener<br>  ]<br><br>  tags = {<br>    Name = var.SERVICE_NAME<br>  }<br>}</pre><h4><strong>Data Sources:</strong></h4><ul><li><strong>Default VPC (</strong><strong>data &quot;aws_vpc&quot; &quot;default&quot;)</strong>:</li><li>This data source fetches the default VPC in your AWS account. The default = true argument ensures that the data source only returns the default VPC.</li><li><strong>Default Subnets (</strong><strong>data &quot;aws_subnets&quot; &quot;default&quot;)</strong>:</li><li>This data source retrieves all subnets associated with the default VPC by filtering with the vpc-id. The subnets are essential for networking configurations in your ECS service.</li></ul><p><strong>ECS Service (</strong><strong>resource &quot;aws_ecs_service&quot; &quot;apexapp_svc&quot;)</strong>:</p><ul><li><strong>name</strong>: The name of the ECS service, defined by var.SERVICE_NAME.</li><li><strong>cluster</strong>: Specifies the ECS cluster where the service will run. This references the previously defined ECS cluster (aws_ecs_cluster.apex_cluster.id).</li><li><strong>task_definition</strong>: References the ARN of the ECS task definition (aws_ecs_task_definition.apexapptask.arn) that will be used by this service.</li><li><strong>desired_count</strong>: Sets the number of tasks (containers) you want to run for this service. I’ve set it to 1, which means only one instance of the container will run.</li><li><strong>launch_type</strong>: Specifies the launch type, which is set to &quot;FARGATE&quot; in this case.</li><li><strong>network_configuration</strong>:</li><li><strong>security_groups</strong>: Specifies the security groups to associate with the ECS tasks. This references a security group that’s been previously defined(aws_security_group.apexapp_sg.id).</li><li><strong>assign_public_ip</strong>: Assigns a public IP address to the Fargate tasks, which is useful for the containers to access the internet.</li><li><strong>load_balancer</strong>:</li><li><strong>target_group_arn</strong>: Specifies the ARN of the target group for the load balancer. The load balancer routes traffic to the container instances in this service.</li><li><strong>container_name</strong>: References the container&#39;s name defined in the ECS task definition (var.CONTAINER_NAME).</li><li><strong>container_port</strong>: Specifies the port on which the container is listening (var.PORT).</li><li><strong>depends_on</strong>:</li><li>Ensures that the ECS service is not created until the load balancer listener (aws_lb_listener.apexapp_http_listener) is fully set up.</li></ul><p>Then finally, the variables file which defined all variables used across all the resource configuration files. <strong>vars.tf</strong>:</p><pre>variable &quot;REGION&quot; {<br>  default = &quot;us-east-2&quot;<br>}<br><br>variable &quot;CLUSTER_NAME&quot; {<br>  default = &quot;apex&quot;<br>}<br><br>variable &quot;MEMORY&quot; {<br>  default = &quot;2048&quot;<br>}<br><br>variable &quot;PORT&quot; {<br>  default = &quot;3000&quot;<br>}<br><br>variable &quot;DOCKER_IMAGE&quot; {<br>  default = &quot;oluty/apexapp:latest&quot;<br>}<br><br>variable &quot;CONTAINER_NAME&quot; {<br>  default = &quot;apexapp&quot;<br>}<br><br>variable &quot;DB_URL_SECRET&quot; {<br>  default = &quot;arn:aws:secretsmanager:us-east-2:302225372317:secret:ApexSecrets_DB_URL-IYnCpn&quot;<br>}<br><br>variable &quot;PORT_SECRET&quot; {<br>  default = &quot;arn:aws:secretsmanager:us-east-2:302225372317:secret:ApexSecrets-tRFSbw&quot;<br>}<br><br>variable &quot;TASK_FAMILY&quot; {<br>  default = &quot;apexapptask&quot;<br>}<br><br>variable &quot;SERVICE_NAME&quot; {<br>  default = &quot;apexappsvc&quot;<br>}<br><br>variable &quot;ALB_NAME&quot; {<br>  default = &quot;apexappelbecs&quot;<br>}<br><br>variable &quot;TG_NAME&quot; {<br>  default = &quot;apexecstg&quot;<br>}<br><br>variable &quot;SG_NAME&quot; {<br>  default = &quot;apexappecs-sg&quot;<br>}</pre><p>Now that all the configuration files have been written, your folder structure should look similar to this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*57oH-SW_Vpakm0ceWrWt2A.png" /></figure><p>After this, cd into the folder on gitbash, initialize terraform, check for any syntax errors and make the necessary corrections if there are any errors.</p><pre># To initialize terraform <br>Terraform init<br># To check for any syntax errors<br>Terraform Validate<br># Put it into an easier format<br>terraform fmt</pre><p>To see the full breakdown of what will happen and changes that will be made when you execute the configuration, run the command.</p><pre>terraform plan</pre><p>And the output should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*kZKYjnDFS2PoDc7rVkWUJA.png" /></figure><p>Then you can execute terraform with the command:</p><pre>terraform apply</pre><p>Which will take a while, but when completed, your resources and infrastructure should be created and setup on AWS, which you can confirm from the console.</p><p>Now that the Workflow is completed, the ECS Infrastructure is setup, and secrets management has been configured as well, it’s time to test. The workflow is set to trigger on every push to the git repository. So push the codes to the github, which should trigger the workflow and deploy the application.</p><p>You can check the AWS console to view the status of the application on the ECS dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrjxQWhzmUgzQumDHuOamg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-GORzNvboICUlEC3qz8Vw.png" /><figcaption>Application is running</figcaption></figure><p>To access the deployed application, click on the running task…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*V2MZUrfjZurNmWnV1PSiJw.png" /></figure><p>Copy the assigned public ip</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*0UxK0982bBukssmMYJFiBg.png" /></figure><p>This particular application is accessible on /health, and listens on port 300, so putting it into the browser with the port number and /health, i can sucessfully access the deployed application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*TsDzNom7dygg5rvh8imTkg.png" /><figcaption>Application is up and running</figcaption></figure><p>Now that it’s all up and running, to tear it all down, simply run the command:</p><pre>terraform destroy</pre><p>This should tear down the ECS infrastructure and stop the application</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f2c7980dba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerizing & Deploying a Go Application on EC2 using Ansible]]></title>
            <link>https://medium.com/@tayoefunshile/containerizing-deploying-a-go-application-on-ec2-using-ansible-c908033a4c81?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/c908033a4c81</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 20:29:06 GMT</pubDate>
            <atom:updated>2024-08-27T20:31:16.936Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re new to ansible, check out <a href="https://medium.com/@tayoefunshile/installing-services-on-your-local-computer-using-ansible-aa5c173de5ea"><strong>my previous post</strong></a><strong> </strong>for a brief introduction to what ansible is, what it does and how it can be installed.</p><p>In this project, I’ll be using ansible to automate the containerization and deployment of a Go application on an ec2 instance running on Ubuntu. he same Go Application used in <a href="https://medium.com/@tayoefunshile/containerizing-a-go-application-using-docker-d8d4dba766a9"><strong>this previous task.</strong></a></p><p>Prerequisites:</p><ul><li>Linux control machine</li><li>Ansible installed on the control machine</li></ul><p>Steps:</p><ul><li>Go application</li><li>AWS config (to put in the AWS access and secrets keys to allow ansible to access your aws account)</li><li>Install boto3 (Ansible needs it to access certain resources like AWS)</li><li>Write playbook</li></ul><p>The Go Application is on my GitHub, feel free to check out the ansible playbook as well, or use your application source code.</p><p>To begin, you can either use an ec2 instance as your control machine, or your local computer, and have ansible installed on it. Create a folder in which the ansible playbook will be written in,</p><p>I want the playbook to be reusable, so al ot of the values used will be passed into it as variables, so here’s my variables file:</p><pre>ansible_user: tayo<br>instance_name: Apex<br>key_name: mykey<br>instance_type: t2.micro<br>region: us-east-2<br>ami: ami-085f9c64a9b75eed5<br>security_group: jenkins-docker-sg</pre><p>And here’s the content of the playbook:</p><pre>---<br>- name: Setup virtual environment and install amazon.aws collection<br>  hosts: myserver<br>  gather_facts: false<br><br>  tasks:<br>    - name: Ensure python3-venv is installed<br>      apt:<br>        name: python3-venv<br>        state: present<br><br>    - name: Create Python virtual environment<br>      ansible.builtin.shell: python3 -m venv /home/tayo/myvenv<br>      args:<br>        creates: /home/tayo/myvenv/bin/activate<br><br>    - name: Install Ansible in the virtual environment<br>      ansible.builtin.shell: |<br>        source /home/tayo/myvenv/bin/activate<br>        pip install ansible<br>      args:<br>        executable: /bin/bash<br><br>    - name: Install boto3 and botocore in the virtual environment<br>      ansible.builtin.shell: |<br>        source /home/tayo/myvenv/bin/activate<br>        pip install boto3 botocore<br>      args:<br>        executable: /bin/bash<br><br>    - name: Set ansible_python_interpreter to use virtual environment<br>      set_fact:<br>        ansible_python_interpreter: /home/tayo/myvenv/bin/python<br><br>    - name: Install amazon.aws collection<br>      ansible.builtin.shell: |<br>        source /home/tayo/myvenv/bin/activate<br>        ansible-galaxy collection install amazon.aws<br>      args:<br>        executable: /bin/bash<br><br>- name: Setup ec2 instance<br>  hosts: localhost<br>  gather_facts: False<br>  vars:<br>    ansible_python_interpreter: /home/tayo/myvenv/bin/python<br><br>  tasks:<br>    - name: Create key pair<br>      ec2_key:<br>        name: mykey<br>        region: &quot;{{ region }}&quot;<br>      register: keyout<br><br>    - name: print key<br>      debug:<br>        var: keyout<br><br>    - name: Save private key to file (optional)<br>      copy:<br>        content: &quot;{{ keyout.key.private_key }}&quot;<br>        dest: ./mykey.pem<br>      when: keyout.changed<br><br>    - name: Set file permissions for the private key<br>      file:<br>        path: ./mykey.pem<br>        mode: &#39;0400&#39;<br>        owner: &quot;{{ ansible_user }}&quot;<br>        group: &quot;{{ ansible_user }}&quot;<br>      when: keyout.changed<br><br>    - name: Create a security group<br>      ec2_group:<br>        name: &quot;{{ security_group }}&quot;<br>        description: Jenkins and Docker SG<br>        region: &quot;{{ region }}&quot;<br>        rules:<br>          - proto: tcp<br>            from_port: 22<br>            to_port: 22<br>            cidr_ip: 0.0.0.0/0<br>          - proto: tcp<br>            from_port: 8080<br>            to_port: 8080<br>            cidr_ip: 10.0.0.0/8<br>          - proto: tcp<br>            from_port: 3000<br>            to_port: 3000<br>            cidr_ip: 0.0.0.0/0<br><br>    - name: launch ec2 instance<br>      ec2_instance:<br>        name: &quot;{{ instance_name }}&quot;<br>        key_name: &quot;{{ key_name }}&quot;<br>        # vpc_subnet_id: subnet-5ca1ab1e<br>        instance_type: &quot;{{ instance_type }}&quot;<br>        security_group: &quot;{{ security_group }}&quot;<br>        # network:<br>        #   assign_public_ip: true<br>        image_id: &quot;{{ ami }}&quot;<br>        region: &quot;{{ region }}&quot;<br>        exact_count: 1<br>        tags:<br>          Name: &quot;{{ instance_name }}&quot;<br>        wait: yes<br>        wait_timeout: 500<br>      register: ec2<br><br>    - name: Add new EC2 instance to the host group<br>      add_host:<br>        hostname: &quot;{{ item.public_dns_name }}&quot;  # This uses the public DNS name of the instance<br>        ansible_ssh_private_key_file: ./mykey.pem<br>        ansible_user: ubuntu <br>        groupname: jenkins_server<br>      with_items: &quot;{{ ec2.instances }}&quot;<br>      when: ec2.instances is defined and ec2.instances | length &gt; 0<br><br>    - name: Wait for SSH to come up<br>      wait_for:<br>        host: &quot;{{ item.public_dns_name }}&quot;<br>        port: 22<br>        delay: 60<br>        timeout: 320<br>        state: started<br>      with_items: &quot;{{ ec2.instances }}&quot;<br><br>- name: provision ec2 instance with Jenkins and Docker<br>  hosts: jenkins_server<br>  become: yes<br><br>  tasks:<br>    - name: Update apt and install dependencies<br>      apt:<br>        update_cache: yes<br>        name:<br>          - openjdk-11-jdk<br>          - apt-transport-https<br>          - ca-certificates<br>          - curl<br>          - software-properties-common<br>        state: present<br><br>    - name: Add Docker GPG key<br>      apt_key:<br>        url: https://download.docker.com/linux/ubuntu/gpg<br>        state: present<br><br>    - name: Add Docker repository<br>      apt_repository:<br>        repo: deb https://download.docker.com/linux/ubuntu focal stable<br>        state: present<br><br>    - name: Install Docker<br>      apt:<br>        name: docker-ce<br>        state: present<br><br>    - name: Ensure Docker service is started<br>      service:<br>        name: docker<br>        state: started<br>        enabled: yes<br><br>    - name: Add Ubuntu user to Docker group<br>      user:<br>        name: ubuntu<br>        groups: docker<br>        append: yes<br><br>    - name: Pull source code from GitHub<br>      git:<br>        repo: &#39;https://github.com/Oluty-1/apex-network_mod.git&#39;<br>        dest: /home/apex<br><br>    - name: Change directory to the project directory<br>      ansible.builtin.shell: cd /home/apex<br><br>    - name: Install Docker Compose<br>      ansible.builtin.shell: |<br>        curl -L &quot;https://github.com/docker/compose/releases/download/v2.3.3/docker-compose-$(uname -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose<br>        chmod +x /usr/local/bin/docker-compose<br>      args:<br>        executable: /bin/bash<br><br>    - name: Run docker-compose up<br>      ansible.builtin.shell: docker-compose up -d<br>      args:<br>        chdir: /home/apex  # Set the working directory<br><br>- name: Remove local key files for security<br>  hosts: localhost<br>  gather_facts: false<br>  tasks:<br>    - name: Remove local key files for security<br>      file:<br>        path: ./mykey.pem<br>        state: absent</pre><h4><strong>Part 1: Setup Virtual Environment and Install </strong><strong>amazon.aws Collection</strong></h4><p>This section ensures that the necessary Python tools and dependencies are installed in a controlled environment, which is important for consistency and isolation. Most of which are gotten from the Ansible AWS module documentation.</p><p><strong>1) Ensure </strong><strong>python3-venv is installed:</strong></p><ul><li>Installs the Python package that allows you to create virtual environments (python3-venv). A virtual environment helps to keep project-specific dependencies isolated from the global Python environment, avoiding potential conflicts.</li></ul><p><strong>2) Create Python virtual environment:</strong></p><ul><li>Creates a virtual environment at /home/tayo/myvenv. This is where all the Python packages and tools specific to this project will be installed.</li></ul><p><strong>3) Install Ansible in the virtual environment:</strong></p><ul><li>Activates the virtual environment and installs Ansible using pip. Installing Ansible within the virtual environment ensures that this project uses a specific version of Ansible, independent of other projects.</li></ul><p><strong>4) Install </strong><strong>boto3 and </strong><strong>botocore in the virtual environment:</strong></p><ul><li>These are AWS SDK libraries for Python, needed to interact with AWS services. They’re installed in the virtual environment to keep the project dependencies consistent.</li></ul><p><strong>5) Set </strong><strong>ansible_python_interpreter to use the virtual environment:</strong></p><ul><li>Configures Ansible to use the Python interpreter from the virtual environment, ensuring that all tasks executed by Ansible will use the environment-specific tools and packages.</li></ul><p><strong>6)Install </strong><strong>amazon.aws collection:</strong></p><ul><li>Installs the amazon.aws Ansible collection, which contains modules and plugins for managing AWS resources..</li></ul><h4><strong>Part 2: Setup EC2 Instance</strong></h4><p>To log into an ec2 instance, we need the keypair (pem file) public ipv4 address and instance AMI. So that’s what we’ll be creating here. This part of the playbook provisions a new EC2 instance on AWS and configures it for use.</p><p><strong>1) Create key pair:</strong></p><ul><li>Creates an SSH key pair on AWS, which is used for securely accessing the EC2 instance.</li></ul><p><strong>2) Save private key to file and set permissions:</strong></p><ul><li>Stores the private key locally with restricted permissions, ensuring that only the owner can read it. This is important for security.</li></ul><p><strong>3) Create a security group:</strong></p><ul><li>Defines the network inbound rules for accessing the EC2 instance, allowing traffic on ports 22 (SSH), 8080, and 3000.</li></ul><p><strong>4) Launch EC2 instance:</strong></p><ul><li>Creates a new EC2 instance using the specified configurations (instance type, security group, AMI, keypair etc.).</li></ul><p><strong>5) Add new EC2 instance to the host group:</strong></p><ul><li>Dynamically adds the new EC2 instance to the docker_server Ansible group, allowing subsequent tasks to target this instance.</li></ul><p><strong>6) Wait for SSH to come up:</strong></p><ul><li>Waits until the EC2 instance is fully booted and SSH is available, ensuring that the next steps can connect successfully.</li></ul><h4><strong>Part 3: Provision EC2 Instance with Docker and Docker Compose</strong></h4><p>This section installs and configures and Docker and Docker Compose on the EC2 instance. These modules are also gotten directly from ansible documentation</p><p><strong>1) Update apt and install dependencies:</strong></p><ul><li>Installs essential packages, required for and Docker dependencies.</li></ul><p><strong>2) Add Docker GPG key and repository:</strong></p><ul><li>Adds the GPG key and Docker’s official repository to the system to install Docker securely.</li></ul><p><strong>3) Install Docker:</strong></p><ul><li>Installs Docker on the EC2 instance.</li></ul><p><strong>4) Ensure Docker service is started:</strong></p><ul><li>Starts the Docker service and ensures it will start on boot.</li></ul><p><strong>5) Add Ubuntu user to Docker group:</strong></p><ul><li>Adds the ubuntu user to the Docker group, allowing Docker commands to be run without sudo.</li></ul><p><strong>6) Pull source code from GitHub:</strong></p><ul><li>Clones a GitHub repository to the EC2 instance, setting up the application code.</li></ul><p><strong>7) Install Docker Compose:</strong></p><ul><li>Installs Docker Compose, a tool for defining and running multi-container Docker applications.</li></ul><p><strong>8) Run </strong><strong>docker-compose up:</strong></p><ul><li>Uses Docker Compose to build and start the application containers in detached mode.</li></ul><h4>Part 4: Remove Local Key Files for Security</h4><p>This final section cleans up any sensitive data that was stored locally during the setup process.</p><ol><li><strong>Remove local key files for security:</strong></li></ol><ul><li>Deletes the local copy of the private key used for SSH access to the EC2 instance, ensuring that sensitive credentials are not left on the local machine.</li></ul><p>To run the ansible playbook, use the command:</p><pre>ansible-playbook -i inventory ec2provision.yaml</pre><p>This will carry out the tasks listed out in the playbook, you can chech your AWS console to see the resources that have bee created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3G3bVNG0b8SJMyKlwykCQ.png" /></figure><p>And to verify that the application is up and running, paste the public address of the instace it was deployed on, and the port number 3000 into a browser and….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVJtY8hzg-pmcSEkph-00Q.png" /></figure><p>Depending on your application, you should see the application running.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c908033a4c81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Ansible]]></title>
            <link>https://medium.com/@tayoefunshile/introduction-to-ansible-e9a1d61fe0a9?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9a1d61fe0a9</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[playbook]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 13:47:53 GMT</pubDate>
            <atom:updated>2024-08-27T13:47:53.418Z</atom:updated>
            <content:encoded><![CDATA[<p>Ansible is a tool for automating IT tasks, but let’s break it down with a simple analogy.</p><p>Imagine you are the manager of a large hotel. Each room in the hotel represents a server in your IT infrastructure. Now, managing each room (server) manually would be time-consuming and prone to errors. You need a way to efficiently manage all these rooms.</p><p>In this analogy:</p><ul><li>Ansible is like the hotel management software that you, the manager, use to automate tasks across all the rooms (servers).</li><li>Playbooks are like the checklists and procedures that the software uses to perform specific tasks in each room.</li><li>Modules are the individual tasks, like cleaning a room, restocking the minibar, or setting the thermostat, that the software can perform.</li></ul><p>How Ansible Works:</p><p>1) Playbooks:</p><ul><li>Definition: Playbooks are written in YAML, a simple, human-readable language.</li><li>Analogy: Think of a playbook as a detailed checklist for a hotel employee. It specifies what needs to be done, step by step. For example, “clean the bathroom, replace the towels, and set the room temperature to 19°C.”</li></ul><p>2) Modules:</p><ul><li>Definition: Modules are reusable scripts that perform specific tasks.</li><li>Analogy: Each module is like a specific task on the checklist. There are modules for installing software, restarting services, and configuring files. In our hotel analogy, modules would be the tasks like “clean bathroom” or “restock minibar.”</li></ul><p>3) Inventory:</p><ul><li>Definition: The inventory file lists all the servers (or rooms) that Ansible can manage.</li><li>Analogy: This is like having a roster of all the rooms in the hotel, specifying which ones need what kind of service.</li></ul><p>4) Control Node and Managed Node:</p><ul><li>Definition: The control node is where Ansible runs, and managed nodes are the servers it controls.</li><li>Analogy: The control node is like the manager’s office where the hotel management software is run. Managed nodes are the individual rooms in the hotel.</li></ul><p>5) Agentless:</p><ul><li>Definition: Ansible does not require any special software (agent) to be installed on the servers it manages.</li><li>Analogy: Imagine the hotel management software can control room services without needing any special device in each room. It uses standard protocols (like sending commands over the network) to get things done.</li></ul><p>Putting It All Together:</p><p>When you run Ansible, it’s like hitting “start” on your hotel management software. It reads the playbook (checklist), connects to each room (server) listed in the inventory, and performs the tasks (modules) specified. The result is that all rooms (servers) are managed consistently and efficiently, without the need for manual intervention.</p><p>So, in simple terms, Ansible is a tool that helps you automate and manage your IT infrastructure, making sure everything is set up and running as it should be, just like how hotel management software ensures all rooms are clean, stocked, and comfortable for guests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9a1d61fe0a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerizing a Go application using Docker]]></title>
            <link>https://medium.com/@tayoefunshile/containerizing-a-go-application-using-docker-d8d4dba766a9?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8d4dba766a9</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 21:31:25 GMT</pubDate>
            <atom:updated>2024-08-13T21:31:25.275Z</atom:updated>
            <content:encoded><![CDATA[<p>I wanna setup a CI/CD pipeline for a go application, I met a friend to give me a source code that I could practice with, but I was unable to run the application on my computer without installing a few dependencies due to my local machine being different from his. This would be a problem if a large number of developers were needed to maintain and manage the application, due to every developer’s environment being different. This is where the concept of containerization comes in, this creates similar environment for every developer involved.</p><p><strong>Prerequisite:</strong></p><ul><li>Install Docker: You can check the <a href="https://docs.docker.com/engine/install/ubuntu/"><strong>docker documentation</strong></a> for how to do this depending on the OS of your environment</li></ul><p>If you’d like more detailed overview on docker, you can check out my <a href="https://medium.com/@tayoefunshile/container-technology-docker-54c624e68acd"><strong>previous post</strong></a> on docker as a container technology.</p><p>For this project, I’ll be writing a Dockerfile for <a href="https://github.com/tejiriaustin/apex-network.git"><strong>this sourcecode</strong></a>, it is a go application, so the base image I’ll be using is golang(which you can find on <a href="https://hub.docker.com/">dockerhub</a>).</p><p>For starters, I forked the code into my github, and cloned it into my local machine, then rearranged the file structure to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*CC4J8yG6wekVfp3A2iDRDA.png" /></figure><p>I moved the application code into the “src” folder so i can keeo the docker files outside. The dockerfile for the web app looks like this:</p><pre># Step 1: Build the Go application<br>FROM golang:1.20-alpine AS build_image<br><br>LABEL &quot;Project&quot;=&quot;Apex_Network&quot;<br>LABEL &quot;Author&quot;=&quot;Tejiri&quot;<br># Set the working directory inside the container<br>WORKDIR /build<br><br># Copy the Go source code into the container<br>COPY src/go.mod .<br>COPY src/ .<br>COPY .env .<br><br># Download go dependencies<br>RUN go mod download<br><br># Build the Go application<br>RUN go build -o /build/apex_network<br><br><br><br># Step 2: Create a minimal container to run the application<br>FROM alpine:latest<br><br># Set a working directory in the new container<br>WORKDIR /app<br><br># Copy the built Go binary from the builder stage<br>COPY --from=build_image /build/apex_network ./apex_network<br><br># Expose the application port<br>EXPOSE 3000<br><br># Command to run the application<br>CMD [ &quot;./apex_network&quot;, &quot;apex_network_api&quot; ]<br><br></pre><h4>Step 1: Build the Go Application</h4><p><strong>1) Base Image</strong>:</p><ul><li>FROM golang:1.20-alpine AS build_image: Uses an official Go image based on Alpine Linux for building the application.</li></ul><p><strong>2) Metadata</strong>:</p><ul><li>LABEL &quot;Project&quot;=&quot;Apex_Network&quot; and LABEL &quot;Author&quot;=&quot;Tejiri&quot;: Adds metadata to the image for easier management and tracking.</li></ul><p><strong>3) Working Directory</strong>:</p><ul><li>WORKDIR /build: Sets the working directory inside the container to /build.</li></ul><p><strong>4) Copying Files</strong>:</p><ul><li>COPY src/go.mod .: Copies the go.mod file, which contains the Go module&#39;s dependencies, to the working directory.</li><li>COPY src/ .: Copies the entire source code from the src directory into the working directory.</li><li>COPY .env .: Copies the .env file, which contains environment variables, into the working directory.</li></ul><p><strong>5) Downloading Dependencies</strong>:</p><ul><li>RUN go mod download: Downloads the Go module dependencies defined in the go.mod file.</li></ul><p><strong>6) Building the Application</strong>:</p><ul><li>RUN go build -o /build/apex_network: Compiles the Go application and outputs the binary as apex_network in the /build directory.</li></ul><h4>Step 2: Create a Minimal Container to Run the Application</h4><p><strong>1) Base Image</strong>:</p><ul><li>FROM alpine:latest: Uses the latest Alpine Linux image, which is minimal and secure, to run the application.</li></ul><p><strong>2) Working Directory</strong>:</p><ul><li>WORKDIR /app: Sets the working directory in the container to /app.</li></ul><p><strong>3) Copying the Built Application</strong>:</p><ul><li>COPY --from=build_image /build/apex_network ./apex_network: Copies the built Go binary from the builder stage to the /app directory in the final image.</li></ul><p><strong>4) Exposing the Application Port</strong>:</p><ul><li>EXPOSE 3000: Exposes port 3000, which is where your Go application is expected to run.</li></ul><p><strong>5) Running the Application</strong>:</p><ul><li>CMD [ &quot;./apex_network&quot;, &quot;apex_network_api&quot; ]: Sets the command to run the apex_network binary with apex_network_api as an argument when the container starts.</li></ul><p>If you look at the Dockerfile, you’ll notice it’s in 2 stages, this is called a <strong>Multi-Stage Build</strong></p><ul><li><strong>Multi-Stage Builds:</strong> This is a best practice to reduce the size of the final image. The Go compiler and build dependencies are included only in the first stage, and the final image only contains the compiled binary and the runtime environment.</li><li><strong>Minimal Runtime Image:</strong> By using alpine:latest in the runtime stage, you keep the container lightweight, which improves performance and reduces the attack surface.</li></ul><p>Now that the dockerfile is ready, I wrote a docker compose file, which basically manages the dockerfile. here’s what it looks like:</p><pre>version: &quot;3.8&quot;<br>services:<br>  apexapp:<br>    build:<br>      context: .<br>      dockerfile: Docker-files/app/Dockerfile<br>    image: oluty/apexapp<br>    container_name: apexapp<br>    ports:<br>      - &quot;3000:3000&quot;<br>    env_file:<br>      - ./.env </pre><ul><li>version: &quot;3.8&quot;: Specifies the version of the Docker Compose file format. Version 3.8 is compatible with a variety of Docker features and is widely used.</li><li><strong>Build</strong>:</li><li>context: .: Specifies the build context, meaning the directory containing your Docker Compose file is the root context for the build.</li><li>dockerfile: Docker-files/app/Dockerfile: Points to the specific Dockerfile to be used for building the image. In this case, it&#39;s located at Docker-files/app/Dockerfile.</li><li><strong>Image</strong>:</li><li>image: oluty/apexapp: Names the built Docker image as oluty/apexapp. This is the name that will be used to reference the image, both locally and if pushed to a Docker registry.</li><li><strong>Container Name</strong>:</li><li>container_name: apexapp: Names the running container apexapp. This makes it easier to manage the container (e.g., with docker ps, docker stop apexapp, etc.).</li><li><strong>Ports</strong>:</li><li>ports: &quot;3000:3000&quot;: Maps port 3000 on your host machine to port 3000 on the container. This allows access to the Go application running inside the container from your host machine or network.</li><li><strong>Environment File</strong>:</li><li>env_file: ./.env: Specifies the .env file to be used for environment variables. The .env file should be located in the same directory as the docker-compose.yml file. This file contains environment variables that the container can use (in this case, the port number and the db URL).</li></ul><p>After this is all done, you can test it by running the commands:</p><pre># To build the application<br>docker compose build<br><br># To start the application<br>docker compose up</pre><p>Which will display when the container starts as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*fFf6_XyL3F9M-tRMUightg.png" /></figure><p>And to view the started containers, you can run the command</p><pre>docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*O3CyoRYp3iAPFPU_u0OxPA.png" /></figure><p>Now that the container is tested to be working, you can push it to a docker repository like dockerhub.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8d4dba766a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Ansible Secrets with Ansible Vault]]></title>
            <link>https://medium.com/@tayoefunshile/managing-ansible-secrets-with-ansible-vault-c9f03661c33a?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9f03661c33a</guid>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[secrets]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 00:49:45 GMT</pubDate>
            <atom:updated>2024-08-07T19:57:19.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing secrets is a crucial aspect of maintaining the security and integrity of your applications and infrastructure. Secrets can include passwords, API keys, SSH keys, database credentials, and any other sensitive information that needs to be kept confidential. Poor management of these secrets can lead to unauthorized access, data breaches, and a range of other security issues.</p><p>To ensure secrets are securely stored, various tools and practices are used, one of which is Ansible Vault.</p><h4>Ansible Vault</h4><p>Ansible Vault is a feature within Ansible that provides a way to securely store and manage sensitive data. It allows you to encrypt entire files or specific variables, which can then be included in your playbooks without exposing sensitive information in plaintext.</p><p>Using the same playbook I used in <a href="https://medium.com/@tayoefunshile/fact-variables-and-notification-via-email-in-ansible-1d8ccfcd3cc4"><strong>the previous blog</strong></a>, I’ll be defining the variables I wanna encrypt outside the playbook</p><p>creating a seperate folder “group_vars”, and a file named “all” in which ill be defining the variables:</p><pre>mailtrap_username: bfw38236e5592h<br>mailtrap_password: 62jda01f6wuf39</pre><p>To reference the variables inside the playbook, I’ll make a slight modification, the new version will look like this:</p><pre>---<br>- name: Provisioning Server &amp; Notification<br>  hosts: myserver<br>  become: yes<br>  gather_facts: yes<br>  <br>  tasks:<br>    - name: Install Apache<br>      apt:<br>        name: apache2<br>        state: present<br>      register: install_apache_result<br><br>    - debug:<br>        var: install_apache_result.changed<br><br>    - name: Start Apache<br>      service:<br>        name: apache2<br>        state: started<br>        enabled: yes<br>      register: start_apache_result<br><br>    - debug:<br>        var: start_apache_result.changed<br><br>    - name: Sending an e-mail using mailtrap SMTP servers<br>      mail:<br>        host: smtp.mailtrap.io<br>        port: 587<br>        username: &quot;{{ mailtrap_username }}&quot;<br>        password: &quot;{{ mailtrap_password }}&quot;<br>        to: tayoefun@gmail.com<br>        subject: Ansible Task Completion Notification<br>        body: |<br>          The task &quot;Install Apache&quot; and &quot;Start Apache&quot; has been completed.<br>          Install Apache changed status: {{ install_apache_result.changed }}<br>          Start Apache changed status: {{ start_apache_result.changed }}<br>      delegate_to: localhost</pre><p>This time, whenever the playbook runs, it searches for the defined variables within the directory.</p><p>To encrypt the variable folder “all”, cd into the folder where the variable file is, and run the command:</p><pre>ansible-vault encrypt all</pre><p>You will be prompted to enter a password. Make sure to remember this password, as you will need it to decrypt the file later.</p><p>Once it’s successfully encrypted, it’s content changes to smth that looks like this:</p><pre>$ANSIBLE_VAULT;1.1;AES256<br>32393934623161376542363334366436333765653836656330633263643064626432646639356438<br>6435303630383138653162316562613230643130396634380a333761643635323166666633653066<br>36343261386133313830626664656238343966663336346639653363383032343561386461323137<br>3135303062633863330a346361623862653162323464383964396236623831353363393933663364<br>66373733643034356430666561613735353964303931333262336130386338346466343033616234<br>6562663431363838327136837</pre><p>to decrypt the file, use the command:</p><pre>ansible-vault decrypt all</pre><p>To edit the content of the file, use the command</p><pre>ansible-vault edit all</pre><p>To execute the playbook, use the command:</p><pre>ansible-playbook -i inventory email.yaml --ask-vault-pass</pre><p>This will prompt you to put in the vault password that was set earlier.</p><p>And if you wanna make it non interactive, store the vault password in a text file and reference it when running the playbook. I saved mine in a separate file named “<em>vault_pass.txt</em>” outside the project directory:</p><pre>ansible-playbook -i inventory email.yaml --vault-password-file ../vault_pass.txt</pre><p>And with that command, the playbook should run successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nF3fxWcVBXKzqe5YWpZtA.png" /></figure><p>I’ll be pushing all the codes into my <a href="https://github.com/Oluty-1/A_Secrets_Management.git"><strong>GitHub repository</strong></a>, so feel free to check them out</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9f03661c33a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fact Variables and Notification via Email in Ansible]]></title>
            <link>https://medium.com/@tayoefunshile/fact-variables-and-notification-via-email-in-ansible-1d8ccfcd3cc4?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d8ccfcd3cc4</guid>
            <category><![CDATA[email]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[playbook]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 19:34:50 GMT</pubDate>
            <atom:updated>2024-08-05T19:34:50.908Z</atom:updated>
            <content:encoded><![CDATA[<p>I have spoken about how Ansible can be used to carry out tasks on a machine in <a href="https://medium.com/@tayoefunshile/installing-services-on-your-local-computer-using-ansible-aa5c173de5ea"><strong>a previous post</strong></a><strong>. </strong>This time around, I’ll be talking about how you can store the output of tasks into variables, and how they can be printed and used.</p><p>Using the same playbook from <a href="https://medium.com/@tayoefunshile/installing-services-on-your-local-computer-using-ansible-aa5c173de5ea"><strong>the previous</strong></a> post, I’ll update the playbook to include <em>register</em> and <em>debug</em></p><pre>---<br>- name: Provisioning Server<br>  hosts: myserver<br>  become: yes<br>  gather_facts: yes<br>  <br>  tasks:<br>    - name: Install Apache<br>      apt:<br>        name: apache2<br>        state: present<br>      register: install_apache_result<br><br>    - debug:<br>        var: install_apache_result<br><br>    - name: Start Apache<br>      service:<br>        name: apache2<br>        state: started<br>        enabled: yes<br>      register: start_apache_result<br><br>    - debug:<br>        var: start_apache_result</pre><p>Register Variable:</p><ul><li>register: install_apache_result captures the result of the Install Apache task, which is then used in the email body to indicate if the task caused any changes.</li><li><strong>Debug install_apache_result</strong>: Outputs the result of the Install Apache task.</li></ul><p>Running this will give you the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_yjV4u21krY_HXYye0zNQ.png" /></figure><p>It prints out a large JSON, which is unnecessary, as the only thing we need to know is if there was a change. So I modify the command to install_apache_result.changed</p><p>Now the result is a lot more precise:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*MTqxZNhemzuRluOZ0DT8rw.png" /></figure><h4>Sending Email Notification via Ansible</h4><p>To send an email via ansible, you can go through <a href="https://docs.ansible.com/ansible/2.9/modules/mail_module.html#mail-module"><strong>ansible module documentation</strong></a> to search for a module for email, do a simple copy &amp; paste of the module directly into the playbook as a task, and fill in the necessary details.</p><p>Gmail SMTP servers wasn’t available, so I used <a href="https://mailtrap.io/"><strong>mailtrip</strong></a> SMTP server.</p><p><strong>Sign Up for Mailtrap</strong>:</p><ul><li>Create an account at <a href="https://mailtrap.io/">Mailtrap</a>.</li><li>Go to your inbox, then “SMTP Settings”, and note the SMTP credentials provided which includes the <em>username</em> and <em>password</em> to be used in the playbook.</li></ul><p>The updated playbook will look like this:</p><pre>---<br>- name: Provisioning Server<br>  hosts: myserver<br>  become: yes<br>  gather_facts: yes<br>  <br>  tasks:<br>    - name: Install Apache<br>      apt:<br>        name: apache2<br>        state: present<br>      register: install_apache_result<br><br>    - debug:<br>        var: install_apache_result.changed<br><br>    - name: Start Apache<br>      service:<br>        name: apache2<br>        state: started<br>        enabled: yes<br>      register: start_apache_result<br><br>    - debug:<br>        var: start_apache_result.changed<br><br>    - name: Sending an e-mail using mailtrap SMTP servers<br>      mail:<br>        host: smtp.mailtrap.io<br>        port: 587<br>        username: 6t299f357ec3ff<br>        password: t5a01f861g7sh6<br>        to: tayoefun@gmail.com<br>        subject: Ansible Task Completion Notification<br>        body: |<br>          The task &quot;Install Apache&quot; and &quot;Start Apache&quot; has been completed.<br>          Change status: {{ install_apache_result.changed }}<br>          Start status: {{ start_apache_result.changed }}<br>      delegate_to: localhost</pre><p>With the email task added, once Apache is installed and Started, an email is sent to the inbox of the mail provided in the playbook.</p><ul><li><strong>mail:</strong> The module used to send emails.</li><li><strong>host:</strong> The SMTP server to use (smtp.mailtrap.io).</li><li><strong>port:</strong> The port on which the SMTP server is running (587).</li><li><strong>username:</strong> The username for SMTP authentication.</li><li><strong>password:</strong> The password for SMTP authentication.</li><li><strong>to:</strong> The recipient email address (tayoefun@gmail.com).</li><li><strong>subject:</strong> The subject of the email (Ansible Task Completion Notification).</li><li><strong>body:</strong> The body of the email, which includes the change status of the Install Apache and Start Apache tasks.</li><li><strong>delegate_to:</strong> Executes this task on the local machine (localhost) instead of the remote host.</li></ul><p>And that, is how an e-mail notification can be configured using ansible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d8ccfcd3cc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Services on Your Local Computer Using Ansible]]></title>
            <link>https://medium.com/@tayoefunshile/installing-services-on-your-local-computer-using-ansible-aa5c173de5ea?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa5c173de5ea</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 13:54:10 GMT</pubDate>
            <atom:updated>2024-08-27T14:52:25.781Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re already familiar with what ansible is, feel free to skip this introduction and scroll down to the Example.</p><h4>Introduction to Ansible</h4><p>Imagine a large orchestra with many musicians, each playing different instruments. To create beautiful music, all these musicians need to play in harmony, following the same sheet music, and starting and stopping at the right moments. The person responsible for making this happen is the conductor.</p><p>In this analogy:</p><ul><li><strong>Musicians</strong> are like the servers and applications in your IT environment.</li><li><strong>Sheet Music</strong> represents the configurations and tasks that need to be executed on these servers.</li><li><strong>The Conductor</strong> is Ansible.</li></ul><h4>How Ansible Works</h4><ul><li><strong>Sheet Music (Playbooks):</strong> Just like sheet music contains detailed instructions for musicians, Ansible uses playbooks, which are simple YAML files containing instructions on what tasks to perform and how to configure systems.</li><li><strong>The Conductor (Ansible):</strong> Ansible, as the conductor, reads the playbooks and ensures that all the servers (musicians) execute their tasks in harmony. It sends out commands to each server and makes sure they follow the specified instructions.</li><li><strong>Musicians (Servers and Applications):</strong> The servers execute the commands sent by Ansible, ensuring that each one is configured correctly, software is installed, services are started, and so on.</li></ul><p><strong>Key Features</strong></p><ul><li><strong>Agentless</strong>: Unlike other tools that require an agent installed on each server, Ansible communicates over SSH and doesn’t need any special software installed on the servers.</li><li><strong>Idempotent</strong>: Ansible ensures that tasks are only done if necessary. If a server is already correctly configured, Ansible will not repeat the task.</li><li><strong>Simple and Readable:</strong> Playbooks are written in YAML, which is easy to read and write.</li></ul><p><strong>In Practice</strong></p><p>Using Ansible, you can automate repetitive tasks such as:</p><p>- Installing and configuring software<br>- Managing and deploying applications<br>- Ensuring consistent environments across development, staging, and production</p><h4>Ansible Inatallation</h4><p>Following the instructions from the <a href="https://docs.ansible.com/ansible/latest/installation_guide/installation_distros.html#installing-ansible-on-ubuntu"><strong>ansible documentation</strong></a>, you can install ansible on you local machine using these commands</p><pre>$ sudo apt update<br>$ sudo apt install software-properties-common<br>$ sudo add-apt-repository --yes --update ppa:ansible/ansible<br>$ sudo apt install ansible</pre><h4>Example:</h4><p>In this example I’ll be installing the apache service on my local computer which run on Ubuntu. What I’ll need to write is the Inventory file (which contains the server, which in this case, is my local machine), and the playbook, which will contain the task to be executed.</p><blockquote>Both the inventory file and playbook should be created in the same folder.</blockquote><p><strong>Inventory</strong> file</p><pre>all:<br>  hosts:<br>    myserver:<br>      ansible_host: 127.0.0.1<br>      ansible_user: tayo<br>      ansible_connection: local</pre><p>In this inventory file:</p><ul><li>all is the top-level group containing all hosts.</li><li>hosts defines the individual hosts.</li><li>myserver is the hostname you are targeting in your playbook.</li><li>ansible_host specifies the IP address of the host.</li><li>ansible_user is the user used to connect to the host.</li><li>ansible_connection: local indicates that the connection is local (this is typically used for running Ansible on the same machine where it&#39;s installed).</li></ul><p>You can get these details by running these commands on the terminal:</p><pre># To show your ip address<br>ip address<br><br># To show the curret user<br>whoami<br></pre><p>The <strong>Playbook</strong></p><pre>---<br>- name: Provisioning server<br>  hosts: myserver<br>  become: yes<br>  gather_facts: yes<br>  <br>  tasks:<br>    - name: Install Apache<br>      apt:<br>        name: apache2<br>        state: present<br><br>    - name: Start Apache service<br>      service:<br>        name: apache2<br>        state: started<br>        enabled: yes</pre><ol><li><strong>Playbook</strong></li></ol><ul><li><strong>name</strong>: The name of the playbook for identification purposes.</li><li><strong>hosts</strong>: Specifies the target hosts (servers) that this playbook will run on. In this case, myserver.</li><li><strong>become</strong>: Indicates that the playbook should execute commands with elevated privileges (like using sudo).</li><li><strong>gather_facts</strong>: Collects useful information about the remote hosts, like IP addresses and OS versions.</li></ul><p>The tasks section contains the steps Ansible will execute on the specified hosts.</p><ul><li><strong>Task 1: Install Apache</strong></li><li><strong>name</strong>: Describes the task. This one installs the Apache web server.</li><li><strong>apt</strong>: This module is used for managing packages on Debian-based systems (like Ubuntu).</li><li><strong>name</strong>: The name of the package to be installed (apache2).</li><li><strong>state</strong>: Ensures that the package is present (installed).</li><li><strong>Task 2: Start Apache Service</strong></li><li><strong>name</strong>: Describes the task. This one starts the Apache service.</li><li><strong>service</strong>: This module manages services on the system.</li><li><strong>name</strong>: The name of the service (apache2).</li><li><strong>state</strong>: Ensures that the service is started.</li><li><strong>enabled</strong>: Ensures that the service is enabled to start on boot.</li></ul><p>Running this playbook will:</p><ol><li>Connect to myserver.</li><li>Use sudo privileges to execute commands.</li><li>Gather information about the server.</li><li>Install the Apache web server.</li><li>Start and enable the Apache service.</li></ol><p>To run the playbook, i use the command:</p><pre>ansible-playbook -i inventory provisioning.yaml --ask-become-pass </pre><p>Here’s a quick breakdown of the command:</p><ul><li>ansible-playbook: The command to run an Ansible playbook.</li><li>-i inventory.yml: Specifies the inventory file to use.</li><li>provisioning.yml: The playbook file that contains the tasks to execute.</li><li>--ask-become-pass: Prompts you for the sudo password needed to run tasks as a superuser.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PF5Oege-Ld1aZ8wz0zOkug.png" /></figure><p>Playbook is sucessfully executed. you can verify by running the command</p><pre>systemctl status apache2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CUu7UlOU_gE0onF-EB_Jqw.png" /></figure><p>Which shows that Apache2 is up and running</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa5c173de5ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Spotify Playlist Using Terraform]]></title>
            <link>https://medium.com/@tayoefunshile/creating-a-spotify-playlist-using-terraform-0764030a2b2d?source=rss-f10ea4bb7f26------2</link>
            <guid isPermaLink="false">https://medium.com/p/0764030a2b2d</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[spotify]]></category>
            <dc:creator><![CDATA[Tayo Efunshile]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 20:03:28 GMT</pubDate>
            <atom:updated>2024-08-01T21:51:05.281Z</atom:updated>
            <content:encoded><![CDATA[<p>You might be pretty familiar with terraform already as an IAC tool, if not, be sure to check out my <a href="https://medium.com/aws-tip/automating-infrastructure-management-terraform-intro-c31573a80614"><strong>previous blog post on the introduction and walkthrough of Terraform</strong></a><strong>.</strong></p><p>In this project, I’ll be creating a playlist on spotify using terraform.</p><p>For starters, <strong>Terraform</strong> and <strong>Docker</strong> will need to be installed in your local machine, and create a folder to store the codes.</p><p>Terraform provider for spotify will also be needed for terraform to access spotify</p><p>The first file to write will be the <strong>providers.tf</strong> file for spotify, which we can find in terraform registry. I’ll be using <a href="https://registry.terraform.io/providers/conradludgate/spotify/latest"><strong>this provider from terrafor registry</strong></a>, and copy the provider code from it.</p><pre>terraform {<br>  required_providers {<br>    spotify = {<br>      source = &quot;conradludgate/spotify&quot;<br>      version = &quot;0.2.7&quot;<br>    }<br>  }<br>}<br><br>provider &quot;spotify&quot; {<br>  # Configuration options<br>  api_key = <br>}</pre><p>In order to connect to spotify, terraform will need an API key, and to get that, you’ll need to log into the <a href="https://developer.spotify.com/"><strong>Spotify Developer Account</strong></a>, navigate to dashboard and “Create App”. Fill in the details and click “Save”. Your dashboard should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RvF7kYnrpy51RkNa3Lp0A.png" /></figure><p>Navigate to settings in the app created, copy the “<strong>Client ID</strong>” and “<strong>Client Secret</strong>”, and save them in a <strong>.env</strong> file in the terraform folder as “SPOTIFY_CLIENT_ID” and “SPOTIFY_CLIENT_SECRET”</p><p>Next is to setup a spotify AUTH Proxy to get the API key and connect spotify with terraform. I’ll be using a package “spotify-auth-proxy” from <a href="https://github.com/conradludgate/terraform-provider-spotify/tree/main/spotify_auth_proxy"><strong>a github reposiory</strong></a>. Run the command:</p><pre>docker run --rm -it -p 27228:27228 --env-file .env ghcr.io/conradludgate/spotify-auth-proxy</pre><p>It will give an output displaying the API key, and a link to authorize the connection to spotify. Upon authorisation, you should get this page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDXcaSgIUOFyVm6ahotAag.png" /></figure><p>Store the value of the API Key in a <strong>terraform.tfvars</strong> file, and create a <strong>vars.tf</strong> file to call the API variable.</p><p><strong>terraform.tfvars</strong> file:</p><pre>api_key = &quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;</pre><p><strong>vars.tf</strong> file:</p><pre>variable &quot;api_key&quot; {<br>    type = string<br>}</pre><p>Now you can reference the variable in the <strong>providers.tf</strong> file.</p><p><strong>provider.tf</strong> file:</p><pre>terraform {<br>  required_providers {<br>    spotify = {<br>      source = &quot;conradludgate/spotify&quot;<br>      version = &quot;0.2.7&quot;<br>    }<br>  }<br>}<br><br>provider &quot;spotify&quot; {<br>  # Configuration options<br>  api_key = svYNhSULf8uzWdGgRlaXYFBDbjrto4gzF9BNXgdfge_JFKnzgzk6fFTl1lkhbmdR<br>}</pre><p>Now, run the command “terraform init”, which installs all the files necessary for the provider to run. Once that’s ready, you’re ready to create the playlist.</p><p>Create another file and name it <strong>playlist.tf,</strong> this will contain the tracks to be on the playlist.</p><p>Now, what I’m trying to do is create a playlist with songs from Drake, Kendrick and J. Cole, and unless I intend on manually putting in the id of individual tracks into the code, I can use a datablock, which extracts the id directly from spotify and uses it in the terraform code. I got the <a href="https://registry.terraform.io/providers/conradludgate/spotify/latest/docs/data-sources/search_track"><strong>code for the data block</strong></a> from the documentation of where I got the spotify provider.</p><p>Here’s what the <strong>playlist.tf</strong> file looks like:</p><pre>resource &quot;spotify_playlist&quot; &quot;playlist&quot; {<br>  name        = &quot;Big 3&quot;<br><br>  tracks = [<br>    data.spotify_search_track.cole.tracks[0].id,<br>    data.spotify_search_track.cole.tracks[1].id,<br>    data.spotify_search_track.cole.tracks[2].id,<br>    data.spotify_search_track.drizzy.tracks[0].id,<br>    data.spotify_search_track.drizzy.tracks[1].id,<br>    data.spotify_search_track.drizzy.tracks[2].id,<br>    data.spotify_search_track.dot.tracks[0].id,<br>    data.spotify_search_track.dot.tracks[1].id,<br>    data.spotify_search_track.dot.tracks[2].id,<br>  ]<br>}<br><br>data &quot;spotify_search_track&quot; &quot;cole&quot; {<br>  artist = &quot;J.Cole&quot;<br>  limit = 10<br>}<br><br>data &quot;spotify_search_track&quot; &quot;drizzy&quot; {<br>  artist = &quot;Drake&quot;<br>  limit = 10<br>}<br><br>data &quot;spotify_search_track&quot; &quot;dot&quot; {<br>  artist = &quot;Kendrick Lamar&quot;<br>  limit = 10<br>}</pre><p>Spotify Playlist Resource</p><ul><li><strong>Resource Block:</strong> Defines a Spotify playlist resource named `playlist`.</li><li><strong>name</strong>: Sets the name of the playlist to “Big 3”.</li><li><strong>tracks</strong>: Specifies the tracks to be added to the playlist. It includes the first three tracks from the search results for each artist (J.Cole, Drake, and Kendrick Lamar). The tracks are referenced by their IDs, which are obtained from the respective data sources.</li></ul><p>Data Sources for Spotify Search Track</p><ul><li><strong>Data Block</strong>: Defines a data source for searching tracks by a specified artist.</li><li><strong>artist</strong>: Specifies the artist name to search for.</li><li><strong>limit</strong>: Limits the search results to 10 tracks.</li></ul><p>Summary</p><ul><li>The code defines a Spotify playlist named “Big 3” and adds tracks from J.Cole, Drake, and Kendrick Lamar.</li><li>It uses data sources to search for tracks by each artist and limits the search results to 10 tracks per artist.</li><li>The first three tracks from each search result are included in the playlist.</li></ul><p>How it Works</p><ol><li>Search for Tracks:</li></ol><ul><li>The data blocks search for tracks by each specified artist (J.Cole, Drake, Kendrick Lamar).</li><li>Each search result is limited to the first 10 tracks.</li></ul><p>2. Create Playlist:</p><ul><li>The resource block creates a playlist named “Big 3”.</li><li>The `tracks` array includes the IDs of the first three tracks from each artist’s search results.</li></ul><p>3. Track Inclusion:</p><ul><li>The tracks are included in the playlist by referencing the `tracks` array from each data source.</li><li>The array accesses the track IDs at the specified indexes (0, 1, 2) for each artist.</li></ul><p>Now that all these are set up, run the commands</p><pre>terraform init<br>terraform plan</pre><p>Terraform plan will show you what terraform will do when ran. here’s what it displays:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lo3b79RFe70x6IpcQr__Sw.png" /></figure><p>Next is to execute terraform with the command using this:</p><pre>terraform apply</pre><p>When it execute, check your spotify account and boom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rx9A_72XlnLwlQuVIWXv-A.png" /></figure><p>The playlist is created.</p><p>All the codes are being uploaded on <a href="https://github.com/Oluty-1/T_Spotify.git"><strong>my github repository</strong></a> for you to check out as well</p><p>That’s the end of this project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0764030a2b2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>