<?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 Olajideadedayo on Medium]]></title>
        <description><![CDATA[Stories by Olajideadedayo on Medium]]></description>
        <link>https://medium.com/@olajideadedayo230?source=rss-de7fc210865a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gC8iLTln3XI4V2vu</url>
            <title>Stories by Olajideadedayo on Medium</title>
            <link>https://medium.com/@olajideadedayo230?source=rss-de7fc210865a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:19:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olajideadedayo230/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[Terraform Infrastructure as Code on AWS: Parameterized EC2 Provisioning, Apache Configuration…]]></title>
            <link>https://medium.com/@olajideadedayo230/terraform-infrastructure-as-code-on-aws-parameterized-ec2-provisioning-apache-configuration-bc5570edcedd?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc5570edcedd</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 03:30:43 GMT</pubDate>
            <atom:updated>2026-09-15T03:30:43.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUkx_TTtB3i1RhxoJbmrKA.png" /></figure><p>Terraform Infrastructure as Code on AWS: Parameterized EC2 Provisioning, Apache Configuration, Troubleshooting &amp; Lifecycle Management</p><p>Build, deploy, troubleshoot, validate, replace, and destroy AWS infrastructure using Terraform — with real-world lessons from EC2 provisioning, SSH connectivity, provisioners, security, cost awareness, and infrastructure lifecycle management.</p><p>Infrastructure as Code (IaC) is more than writing Terraform configuration and running “terraform apply”.</p><p>A production-minded DevOps engineer needs to understand the complete infrastructure lifecycle: how infrastructure is designed, parameterized, provisioned, configured, validated, troubleshot, reconciled, secured, optimized, and eventually destroyed.</p><p>In this hands-on project, I built a parameterized AWS infrastructure environment using Terraform to demonstrate that complete lifecycle.</p><p>The implementation provisions an Amazon EC2 instance running Ubuntu in AWS, configures an Apache web server, applies security controls through an AWS Security Group, uses Terraform variables for reusable configuration, captures infrastructure outputs, and demonstrates Terraform provisioners for server configuration.</p><p>More importantly, the project involved real deployment challenges rather than an idealized tutorial-only workflow.</p><p>During implementation, I encountered and resolved issues involving:</p><p>- EC2 AMI architecture compatibility</p><p>- Windows SSH private-key path handling</p><p>- EC2 key-pair configuration</p><p>- AWS DNS and network connectivity</p><p>- SSH connection timeouts</p><p>- Terraform provisioner failures</p><p>- Terraform resource tainting</p><p>- EC2 public IP changes</p><p>- HTTP service connectivity</p><p>- Controlled Terraform resource replacement</p><p>The infrastructure was subsequently validated through Terraform outputs, SSH connectivity, Apache service status, browser-based HTTP verification, Terraform state inspection, and controlled resource replacement.</p><p>The completed infrastructure was then destroyed through Terraform to demonstrate the full provision → configure → validate → reconcile → replace → destroy lifecycle.</p><p>What You Will Learn</p><p>By following this project, you will see how to:</p><p>- Build AWS infrastructure using Terraform Infrastructure as Code</p><p>- Parameterize Terraform configurations using variables</p><p>- Deploy an Amazon EC2 instance with Terraform</p><p>- Configure an AWS Security Group</p><p>- Use Terraform “file”, “remote-exec”, and “local-exec” provisioners</p><p>- Configure an Apache web server automatically</p><p>- Manage Terraform outputs</p><p>- Validate infrastructure after deployment</p><p>- Troubleshoot real AWS and Terraform deployment failures</p><p>- Perform controlled Terraform resource replacement</p><p>- Understand Terraform state during infrastructure troubleshooting</p><p>- Apply basic AWS security and cost-optimization principles</p><p>- Understand the limitations of Terraform provisioners</p><p>- Identify how the architecture could be evolved toward production</p><p>- Manage the complete Terraform infrastructure lifecycle</p><p>Project Repository</p><p>The complete implementation, Terraform configuration, scripts, screenshots, and project documentation are available on GitHub:</p><p>GitHub:</p><p><a href="https://github.com/olajide-adedayo/terraform-parameterized-aws-infrastructure">https://github.com/olajide-adedayo/terraform-parameterized-aws-infrastructure</a></p><p>Project Focus</p><p>This is intentionally a hands-on Terraform and AWS Infrastructure as Code portfolio project.</p><p>The objective is not simply to demonstrate that Terraform can create an EC2 instance. The objective is to demonstrate the engineering practices surrounding infrastructure automation:</p><p>«Define → Parameterize → Plan → Provision → Configure → Validate → Troubleshoot → Reconcile → Replace → Destroy»</p><p>That lifecycle is the foundation of reliable Infrastructure as Code and is the perspective I will use throughout this tutorial.</p><p>2. Architecture &amp; What We Are Building</p><p>Before writing the Terraform configuration, it is important to understand the infrastructure we are actually building.</p><p>The objective is deliberately simple: use Terraform to provision an AWS EC2 instance, establish the required network access, connect to the server over SSH, install and configure Apache, expose useful Terraform outputs, and manage the infrastructure through its complete lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjnFU5c9t0FQvDn2xSZ18w.png" /><figcaption>Figure: Terraform AWS architecture showing the Infrastructure-as-Code deployment flow from Terraform through AWS EC2, Security Group, Ubuntu, Apache, and application validation.</figcaption></figure><p>This is not intended to represent a complete production application architecture. Instead, it provides a focused environment for demonstrating practical Terraform Infrastructure as Code (IaC) concepts while exposing the operational issues that engineers encounter when infrastructure moves from configuration files into a real AWS environment.</p><p>The Target Architecture</p><p>The project uses the following components:</p><p>- Terraform — Infrastructure as Code and lifecycle management<br>- AWS Provider — Terraform’s interface to AWS<br>- Amazon EC2 — Compute instance hosting the web server<br>- Amazon VPC networking — Provides connectivity for the EC2 instance<br>- Security Group — Controls inbound network access<br>- EC2 Key Pair — Provides SSH authentication<br>- Ubuntu Linux — Operating system running on the EC2 instance<br>- Apache HTTP Server — Web server installed and configured through Terraform<br>- Terraform Variables — Parameterize deployment-specific values<br>- Terraform Outputs — Expose important infrastructure values<br>- Terraform Provisioners — Demonstrate file transfer and remote/local execution</p><p>The simplified flow is:</p><p>Developer<br> |<br> | Terraform configuration<br> v<br>Terraform<br> |<br> | AWS Provider<br> v<br>AWS<br> |<br> + — — — — — — — — — — — — -+<br> | |<br> v v<br>Security Group EC2 Instance<br> | |<br> | SSH : 22 | Ubuntu<br> | HTTP : 80 |<br> + — — — — — — — — — — — →|<br> |<br> v<br> Apache HTTP<br> |<br> v<br> Web Browser</p><p>Terraform is responsible for defining and managing the infrastructure, while the provisioners demonstrate how Terraform can perform additional configuration actions after the EC2 instance becomes available.</p><p>What Happens During Deployment?</p><p>The deployment follows a controlled sequence rather than simply creating an EC2 instance.</p><p>At a high level:</p><p>1. Define infrastructure requirements<br>2. Parameterize deployment values<br>3. Initialize Terraform<br>4. Validate the Terraform configuration<br>5. Generate an execution plan<br>6. Provision AWS resources<br>7. Establish SSH connectivity<br>8. Transfer the Apache installation script<br>9. Execute the configuration script<br>10. Generate Terraform outputs<br>11. Validate the running web server<br>12. Troubleshoot failures when they occur<br>13. Reconcile or replace resources when necessary<br>14. Destroy the infrastructure when testing is complete</p><p>This sequence is important because real infrastructure management does not end when “terraform apply” starts.</p><p>A successful DevOps workflow must also answer questions such as:</p><p>- Did Terraform create the intended resources?<br>- Can the provisioner establish SSH connectivity?<br>- Is the operating system compatible with the selected EC2 instance type?<br>- Is the security group allowing the required traffic?<br>- Is Apache actually running?<br>- Can the application be reached externally?<br>- Does Terraform state correctly represent the infrastructure?<br>- What happens when a resource becomes unhealthy or must be replaced?<br>- Can the environment be cleanly destroyed?</p><p>These questions became particularly important during this project because the deployment encountered several real connectivity, AMI, SSH, and provisioning issues.</p><p>Parameterization Strategy</p><p>Rather than hard-coding every deployment value directly into the Terraform resources, the project uses Terraform variables.</p><p>Examples include:</p><p>- AWS Region<br>- Availability Zone<br>- EC2 instance type<br>- Instance name<br>- Ubuntu AMI mapping<br>- SSH username<br>- SSH private-key path<br>- EC2 key-pair name</p><p>This allows the infrastructure configuration to remain reusable while deployment-specific values can be changed through variables.</p><p>For example, the EC2 instance type is represented by:</p><p>variable “instance_type” {<br> description = “EC2 instance type for the application server”<br> type = string<br> default = “t3.micro”<br>}</p><p>The EC2 resource then consumes the variable:</p><p>instance_type = var.instance_type</p><p>This is one of the fundamental advantages of Terraform: the infrastructure definition describes what the infrastructure should look like, while variables provide the values that determine how a particular deployment is configured.</p><p>Why Use Provisioners in This Project?</p><p>Terraform provisioners are intentionally included because this project is also a learning exercise around server configuration and Terraform lifecycle behavior.</p><p>The EC2 instance uses:</p><p>- “file” provisioner — transfers the Apache configuration script<br>- “remote-exec” provisioner — executes the script on the EC2 instance<br>- “local-exec” provisioner — records the private IP address locally</p><p>The workflow therefore becomes:</p><p>Terraform<br> |<br> v<br>Create EC2<br> |<br> v<br>Establish SSH connection<br> |<br> v<br>Upload web.sh<br> |<br> v<br>Execute web.sh<br> |<br> v<br>Install Apache<br> |<br> v<br>Start Apache<br> |<br> v<br>Validate HTTP service</p><p>However, there is an important engineering consideration.</p><p>Provisioners are not generally the preferred mechanism for production server configuration.</p><p>They are useful for demonstrating Terraform capabilities and for certain controlled scenarios, but production architectures commonly prefer approaches such as:</p><p>- cloud-init / EC2 user data<br>- immutable machine images<br>- AWS Systems Manager<br>- configuration-management tools<br>- container images<br>- CI/CD-driven application deployment</p><p>That distinction matters because this project is designed to demonstrate the mechanics and operational challenges of Terraform provisioners while also understanding where they fit — and where they should eventually be replaced.</p><p>Security Boundary</p><p>The Security Group provides the network access required by the demonstration.</p><p>The project requires:</p><p>- SSH access on TCP port 22 for Terraform/administrator connectivity<br>- HTTP access on TCP port 80 for browser-based Apache verification</p><p>During the hands-on deployment, these rules were used to troubleshoot and validate connectivity.</p><p>For a real production workload, however, security rules should be narrowed as much as practical. For example, SSH should not normally be exposed broadly to the internet when alternatives such as Systems Manager Session Manager, a bastion architecture, VPN/private connectivity, or restricted administrative source ranges are available.</p><p>This project therefore demonstrates both the working configuration and the security considerations that should influence a production implementation.</p><p>Infrastructure Lifecycle</p><p>One of the main themes of this project is that infrastructure has a lifecycle.</p><p>The lifecycle demonstrated in this project is:</p><p>Define<br> ↓<br>Parameterize<br> ↓<br>Plan<br> ↓<br>Provision<br> ↓<br>Configure<br> ↓<br>Validate<br> ↓<br>Troubleshoot<br> ↓<br>Reconcile<br> ↓<br>Replace<br> ↓<br>Destroy</p><p>This lifecycle became especially relevant when the EC2 instance experienced provisioning and connectivity problems.</p><p>Instead of treating a failed deployment as the end of the exercise, the infrastructure was inspected, the problem was investigated, the Terraform state was examined, and the affected resource was ultimately replaced using Terraform’s controlled replacement mechanism.</p><p>That is much closer to real DevOps work than simply demonstrating a successful first “terraform apply”.</p><p>Repository</p><p>The complete Terraform implementation is available on GitHub:</p><p>Repository:<br><a href="https://github.com/olajide-adedayo/terraform-parameterized-aws-infrastructure">https://github.com/olajide-adedayo/terraform-parameterized-aws-infrastructure</a></p><p>The repository contains the Terraform configuration, variables, outputs, provisioning script, example variable file, “.gitignore”, Terraform dependency lock file, and project documentation.</p><p>In the next section, we will prepare the local environment and review the prerequisites required before Terraform can interact with AWS.</p><p>3. Prerequisites &amp; Environment Setup</p><p>Before Terraform can provision AWS infrastructure, the local environment needs to be prepared correctly.</p><p>A large percentage of Terraform problems are not caused by Terraform configuration itself. Authentication, network connectivity, incorrect credentials, incompatible AMIs, missing SSH keys, incorrect file paths, and local operating-system differences can all affect the deployment.</p><p>For this project, the implementation was performed from a Windows workstation using Git Bash and Terraform.</p><p>Required Tools</p><p>The following components are required for this project:</p><p>- An AWS account</p><p>- AWS CLI</p><p>- Terraform</p><p>- Git</p><p>- Git Bash or another terminal</p><p>- An EC2-compatible SSH private key</p><p>- A GitHub repository for version control</p><p>- Internet connectivity to AWS services</p><p>The primary infrastructure components will be created by Terraform, so there is no requirement to manually create the EC2 instance or Security Group through the AWS Management Console.</p><p>AWS Account</p><p>You need an AWS account with sufficient permissions to create and manage the resources used by the project.</p><p>At minimum, the deployment needs access to services and operations associated with:</p><p>- Amazon EC2</p><p>- Amazon VPC</p><p>- Security Groups</p><p>- EC2 Key Pairs</p><p>- AWS API endpoints used by Terraform</p><p>For a learning environment, broad permissions may be used temporarily where appropriate. For production environments, however, permissions should follow the principle of least privilege.</p><p>Terraform</p><p>Terraform is the primary Infrastructure as Code tool used in this project.</p><p>Verify the installation:</p><p>terraform version</p><p>A successful installation should return the installed Terraform version.</p><p>For this project, Terraform was executed from Git Bash on Windows.</p><p>Terraform uses configuration files with the “.tf” extension. The configuration describes the desired infrastructure rather than requiring the engineer to manually create each resource through the AWS Console.</p><p>AWS CLI</p><p>The AWS CLI provides command-line access to AWS services and is useful for authentication checks, troubleshooting, and independent validation.</p><p>Verify the installation:</p><p>aws — version</p><p>The AWS CLI is not a replacement for Terraform in this project.</p><p>Instead, the two tools have different responsibilities:</p><p>Terraform</p><p>- Defines infrastructure</p><p>- Creates and modifies resources</p><p>- Maintains Terraform state</p><p>- Calculates infrastructure changes</p><p>- Manages the infrastructure lifecycle</p><p>AWS CLI</p><p>- Provides direct command-line interaction with AWS</p><p>- Helps verify AWS identity and access</p><p>- Supports troubleshooting</p><p>- Can independently inspect AWS resources</p><p>This distinction becomes useful when troubleshooting Terraform failures. An engineer should be able to determine whether a problem originates in the Terraform configuration, AWS authentication, AWS networking, or the underlying resource.</p><p>Git</p><p>Git is used to version-control the Terraform project.</p><p>Verify the installation:</p><p>git — version</p><p>Version control is particularly important for Infrastructure as Code because Terraform configuration represents infrastructure decisions.</p><p>A Git repository allows us to track:</p><p>- Terraform configuration changes</p><p>- Variable changes</p><p>- Provisioning scripts</p><p>- Documentation</p><p>- Troubleshooting improvements</p><p>- Production-readiness changes</p><p>The project repository is hosted on GitHub:</p><p><a href="https://github.com/olajide-adedayo/terraform-parameterized-aws-infrastructure">https://github.com/olajide-adedayo/terraform-parameterized-aws-infrastructure</a></p><p>SSH Private Key</p><p>The project uses SSH to connect Terraform to the Ubuntu EC2 instance during provisioning.</p><p>The corresponding EC2 key pair must therefore already exist in AWS, and the local machine must have access to the matching private key.</p><p>For example:</p><p>olajide-key.pem</p><p>The private key must never be committed to GitHub.</p><p>The project therefore excludes private-key files through “.gitignore”:</p><p>*.pem</p><p>This is a basic but essential security control when working with infrastructure repositories.</p><p>Windows SSH Key Path</p><p>Because this project was implemented from Windows, the SSH private-key path required particular attention.</p><p>Terraform’s “file()” function reads the private key from the local filesystem:</p><p>private_key = file(var.private_key_path)</p><p>The path is supplied through a Terraform variable rather than being hard-coded into the resource configuration.</p><p>For example:</p><p>private_key_path = “C:/Users/YOUR_USERNAME/Downloads/olajide-key.pem”</p><p>Using the correct path format is important when running Terraform from Git Bash on Windows.</p><p>This became a real troubleshooting point during the implementation and is one reason why infrastructure troubleshooting should be treated as part of the engineering workflow rather than as an afterthought.</p><p>AWS Region and Availability Zone</p><p>The project uses:</p><p>- AWS Region: “us-east-1”</p><p>- Availability Zone: “us-east-1a”</p><p>The region and Availability Zone are parameterized:</p><p>aws_region = “us-east-1”</p><p>availability_zone = “us-east-1a”</p><p>Parameterization makes the configuration easier to adapt to another AWS environment without rewriting the resource definitions.</p><p>However, an Availability Zone must belong to the selected AWS Region. Changing one without considering the other can produce an invalid deployment configuration.</p><p>EC2 Instance Type</p><p>The project uses:</p><p>instance_type = “t3.micro”</p><p>The instance type is also parameterized.</p><p>This is useful for demonstrating how infrastructure can be resized without modifying the EC2 resource itself.</p><p>It also highlights an important AWS consideration: the selected AMI architecture must be compatible with the selected EC2 instance type.</p><p>During the actual implementation, an incompatible AMI architecture caused an EC2 provisioning failure. The AMI was subsequently corrected to one compatible with the selected instance type.</p><p>This is an important practical lesson:</p><p>«An AMI is not simply an operating-system image name. Its architecture and other characteristics must be compatible with the compute configuration being requested.»</p><p>Project Directory</p><p>The Terraform project is organized as a dedicated Git repository.</p><p>The working directory used during implementation was:</p><p>C:\Users\OLAJIDE\terraform-project\terraform-parameterized-aws-infrastructure</p><p>From Git Bash, the equivalent path is:</p><p>/c/Users/OLAJIDE/terraform-project/terraform-parameterized-aws-infrastructure</p><p>Move into the project directory before running Terraform:</p><p>cd /c/Users/OLAJIDE/terraform-project/terraform-parameterized-aws-infrastructure</p><p>Confirm the project files:</p><p>ls</p><p>The directory contains the Terraform configuration, variables, outputs, provisioning script, example variable file, and supporting project files.</p><p>Credentials and Authentication</p><p>Terraform requires valid AWS authentication before it can create resources.</p><p>Before beginning the deployment, verify that the AWS CLI can identify the active AWS account:</p><p>aws sts get-caller-identity</p><p>A successful response should identify the AWS account and the IAM principal being used.</p><p>This check is valuable because it separates an authentication problem from a Terraform configuration problem.</p><p>If “aws sts get-caller-identity” fails, it should be resolved before continuing with Terraform deployment.</p><p>A Practical Engineering Principle</p><p>Before troubleshooting Terraform resources, first establish that the local execution environment is healthy.</p><p>A useful validation sequence is:</p><p>Terraform installed</p><p>↓</p><p>AWS CLI installed</p><p>↓</p><p>AWS authentication working</p><p>↓</p><p>SSH private key available</p><p>↓</p><p>Project directory correct</p><p>↓</p><p>Terraform configuration present</p><p>↓</p><p>Terraform initialization</p><p>↓</p><p>Terraform validation</p><p>↓</p><p>Terraform plan</p><p>This approach reduces unnecessary troubleshooting because each dependency is verified before moving to the next layer.</p><p>What We Will Build Next</p><p>With the environment prepared, the next step is to examine the Terraform project structure and understand the responsibility of each configuration file.</p><p>We will then start building the infrastructure configuration itself, beginning with Terraform’s AWS provider and the project variables.</p><p>4. Project Structure &amp; Terraform Configuration</p><p>With the local environment prepared, the next step is to understand how the Terraform project is organized before creating the infrastructure.</p><p>A clean project structure makes Infrastructure as Code easier to understand, troubleshoot, review, and maintain.</p><p>For this project, the Terraform configuration is intentionally kept compact so that each file has a clear responsibility.</p><p>Project Structure</p><p>The project contains the following primary files:</p><p>terraform-parameterized-aws-infrastructure/<br>│<br>├── main.tf<br>├── variables.tf<br>├── outputs.tf<br>├── terraform.tfvars.example<br>├── web.sh<br>├── .gitignore<br>├── .terraform.lock.hcl<br>└── screenshots/</p><p>Each file serves a specific purpose.</p><p>“main.tf”</p><p>“main.tf” contains the primary infrastructure resources and Terraform provisioners.</p><p>The EC2 instance is defined here, together with the configuration required to connect to it over SSH and execute the Apache installation script.</p><p>The important design principle is that the resource consumes variables rather than embedding deployment-specific values directly into the resource.</p><p>For example:</p><p>resource “aws_instance” “app_server” {<br> ami = var.ami_ids[var.aws_region]<br> instance_type = var.instance_type<br> availability_zone = var.availability_zone<br> key_name = var.key_name</p><p>tags = {<br> Name = var.instance_name<br> }<br>}</p><p>The configuration therefore separates the resource definition from the values used to deploy it.</p><p>“variables.tf”</p><p>“variables.tf” defines the inputs that control the deployment.</p><p>The project parameterizes values such as:</p><p>- AWS Region<br>- Availability Zone<br>- AMI ID<br>- EC2 instance type<br>- Instance name<br>- SSH username<br>- SSH private-key path<br>- EC2 key-pair name</p><p>For example:</p><p>variable “instance_type” {<br> description = “EC2 instance type for the application server”<br> type = string<br> default = “t3.micro”<br>}</p><p>Instead of modifying “main.tf” whenever the instance type changes, the value can be supplied through the Terraform variable system.</p><p>This makes the configuration more reusable and easier to maintain.</p><p>“terraform.tfvars.example”</p><p>The example variable file demonstrates the values required for a deployment without exposing environment-specific secrets or private credentials.</p><p>For example:</p><p>aws_region = “us-east-1”<br>availability_zone = “us-east-1a”<br>instance_type = “t3.micro”<br>instance_name = “terraform-parameterized-app-server”<br>ssh_user = “ubuntu”<br>private_key_path = “C:/Users/YOUR_USERNAME/Downloads/olajide-key.pem”<br>key_name = “olajide-key”</p><p>The real “terraform.tfvars” file is excluded from Git because it can contain environment-specific configuration.</p><p>This follows an important Infrastructure as Code practice:</p><p>«Configuration that belongs to a particular environment should be separated from reusable infrastructure definitions.»</p><p>“outputs.tf”</p><p>“outputs.tf” exposes useful information after Terraform creates the infrastructure.</p><p>This project exposes:</p><p>output “instance_public_ip” {<br> description = “Public IP address of the Terraform Project 3 application server”<br> value = aws_instance.app_server.public_ip<br>}</p><p>output “instance_private_ip” {<br> description = “Private IP address of the Terraform Project 3 application server”<br> value = aws_instance.app_server.private_ip<br>}</p><p>These outputs become useful during validation because they provide the addresses required to connect to and test the deployed instance.</p><p>“web.sh”</p><p>The “web.sh” script contains the server-side configuration performed after the EC2 instance becomes accessible.</p><p>Its responsibilities include:</p><p>- Updating Ubuntu package information<br>- Installing Apache<br>- Enabling Apache<br>- Starting Apache<br>- Removing the default Apache page<br>- Creating the project’s custom HTML page</p><p>The Terraform “file” provisioner transfers this script to the EC2 instance, while “remote-exec” executes it.</p><p>This creates a simple configuration workflow:</p><p>Local Terraform Project<br> |<br> | web.sh<br> v<br> EC2 Instance<br> |<br> v<br> Ubuntu Linux<br> |<br> v<br> Apache HTTP Server</p><p>“.gitignore”</p><p>The “.gitignore” file prevents local and sensitive Terraform artifacts from being committed to the repository.</p><p>Important exclusions include:</p><p>.terraform/<br>*.tfstate<br>*.tfstate.*<br>*.pem<br>terraform.tfvars<br>private_ips.txt</p><p>This is particularly important for Terraform repositories because Terraform state can contain sensitive infrastructure information, while SSH private keys must never be committed to source control.</p><p>The Terraform dependency lock file, “.terraform.lock.hcl”, is intentionally tracked so that provider dependency selections can be consistently reproduced.</p><p>First Implementation Checkpoint</p><p>Before proceeding with Terraform initialization and planning, it is useful to verify that the expected project files are present.</p><p>This was captured during the hands-on implementation.</p><p>Insert Screenshot 01 here:</p><p>“01-project3-terraform-variable-workspace.png”</p><p>This screenshot introduces the actual working environment used for the project rather than presenting a theoretical file structure.</p><p>It also provides evidence that the Terraform project was organized and worked on locally before infrastructure provisioning began.</p><p>Why Project Structure Matters</p><p>A Terraform project does not become maintainable simply because the configuration works.</p><p>A professional IaC implementation should make it possible for another engineer to quickly determine:</p><p>- Where infrastructure resources are defined<br>- Where variables are declared<br>- Where deployment values are supplied<br>- Where outputs are defined<br>- How server configuration is performed<br>- Which files contain sensitive information<br>- Which generated Terraform artifacts should remain outside source control</p><p>This separation becomes increasingly important as infrastructure grows.</p><p>A small project may begin with only a few Terraform files, but the same principles can eventually evolve into reusable modules, environment-specific configurations, remote state management, CI/CD pipelines, policy enforcement, automated testing, and centralized secrets management.</p><p>From Configuration to Infrastructure</p><p>At this stage, we have established the relationship between the project files:</p><p>variables.tf<br> |<br> v<br>terraform.tfvars<br> |<br> v<br> main.tf<br> |<br> v<br>AWS Infrastructure<br> |<br> v<br> outputs.tf</p><p>The next step is to make Terraform aware of AWS by configuring the AWS provider and initializing the working directory.</p><p>That is where the Terraform execution workflow begins:</p><p>terraform init<br> ↓<br>terraform validate<br> ↓<br>terraform plan<br> ↓<br>terraform apply</p><p>We will start with “terraform init” and examine what Terraform actually prepares before any AWS infrastructure is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAd8cKzgtHLagyQxSKXYKA.png" /><figcaption>Figure 1: Terraform project workspace showing the parameterized infrastructure configuration and supporting project files.</figcaption></figure><p>Part 5 — Terraform Provider Configuration &amp; Initialization</p><p>Before Terraform can create or manage AWS resources, it needs to know which cloud platform it is managing and how to interact with that platform.</p><p>This is the role of the Terraform AWS provider.</p><p>The provider acts as the integration layer between Terraform configuration and the AWS API. In this project, Terraform uses the AWS provider to create and manage resources such as the EC2 instance and its associated networking and security configuration.</p><p>5.1 Configure the AWS Provider</p><p>The provider configuration belongs in “main.tf”:</p><p>provider “aws” {<br> region = var.aws_region<br>}</p><p>Instead of hard-coding the AWS Region, the configuration references the “aws_region” variable:</p><p>region = var.aws_region</p><p>This is an important Infrastructure as Code practice because the infrastructure definition is not unnecessarily tied to a single deployment region.</p><p>The corresponding variable is defined in “variables.tf”:</p><p>variable “aws_region” {<br> description = “AWS region where the infrastructure will be deployed”<br> type = string<br> default = “us-east-1”<br>}</p><p>The relationship is:</p><p>terraform.tfvars<br> │<br> ▼<br> aws_region<br> │<br> ▼<br> AWS Provider<br> │<br> ▼<br> AWS API<br> │<br> ▼<br> AWS Infrastructure</p><p>This means that changing the deployment region can be handled through variable configuration rather than modifying the provider block itself.</p><p>5.2 Why Provider Configuration Matters</p><p>Terraform is designed around a provider model.</p><p>The Terraform core engine handles the Infrastructure as Code workflow:</p><p>Configuration<br> ↓<br>Terraform<br> ↓<br>Provider<br> ↓<br>Cloud/API<br> ↓<br>Infrastructure</p><p>For this project:</p><p>Terraform<br> ↓<br>AWS Provider<br> ↓<br>AWS API<br> ↓<br>EC2<br>Security Groups<br>Networking</p><p>The AWS provider translates Terraform resource definitions into API operations that AWS understands.</p><p>For example, when Terraform encounters:</p><p>resource “aws_instance” “app_server” {<br> …<br>}</p><p>Terraform does not directly create an EC2 instance by itself.</p><p>The AWS provider interprets that resource configuration and communicates with AWS to create, update, inspect, or destroy the corresponding EC2 resource.</p><p>5.3 Initialize the Terraform Working Directory</p><p>Once the configuration is in place, the next step is to initialize the project:</p><p>terraform init</p><p>“terraform init” prepares the working directory for Terraform operations.</p><p>During initialization, Terraform:</p><p>- initializes the working directory<br>- downloads the required provider<br>- establishes the provider dependency<br>- creates the “.terraform/” working directory<br>- creates or updates “.terraform.lock.hcl”<br>- prepares the project for commands such as “terraform plan” and “terraform apply”</p><p>A successful initialization should end with a message similar to:</p><p>Terraform has been successfully initialized!</p><p>The exact output can vary depending on the Terraform and provider versions.</p><p>5.4 Understanding “.terraform.lock.hcl”</p><p>One important file is:</p><p>.terraform.lock.hcl</p><p>This file records the selected provider version and checksums.</p><p>For this project, the lock file is intentionally tracked in Git.</p><p>That is different from the “.terraform/” directory, which should not be committed.</p><p>The distinction is important:</p><p>.terraform/<br> → Local Terraform working data<br> → Do not commit</p><p>.terraform.lock.hcl<br> → Provider dependency lock information<br> → Commit to Git</p><p>Keeping the lock file in the repository improves dependency consistency because other developers or CI/CD systems cloning the repository can use the locked provider dependency information.</p><p>5.5 Verify the Configuration</p><p>After initialization, validate the Terraform configuration:</p><p>terraform validate</p><p>A successful result should indicate:</p><p>Success! The configuration is valid.</p><p>Validation checks the Terraform configuration for structural and syntactical problems.</p><p>It is important to understand what validation does not mean.</p><p>A successful:</p><p>terraform validate</p><p>does not prove that:</p><p>- AWS credentials are valid<br>- the selected AMI exists<br>- the EC2 instance can be created<br>- the SSH connection will work<br>- the security rules are correct<br>- Apache will successfully start<br>- the infrastructure will be reachable from the Internet</p><p>Those conditions require later stages of testing and validation.</p><p>This project therefore follows a progressive validation model:</p><p>terraform validate<br> ↓<br>terraform plan<br> ↓<br>terraform apply<br> ↓<br>AWS resource validation<br> ↓<br>SSH validation<br> ↓<br>Apache/service validation<br> ↓<br>HTTP/browser validation</p><p>This distinction becomes particularly important when troubleshooting real infrastructure deployments.</p><p>5.6 Verify AWS Authentication</p><p>Terraform also needs AWS credentials with sufficient permissions to perform the requested operations.</p><p>A useful pre-flight check is:</p><p>aws sts get-caller-identity</p><p>If authentication is correctly configured, AWS returns information about the identity making the request.</p><p>This is preferable to discovering an authentication problem only after running:</p><p>terraform apply</p><p>A senior-level infrastructure workflow separates authentication problems from Terraform configuration problems.</p><p>For example:</p><p>AWS credential problem<br> ≠<br>Terraform syntax problem<br> ≠<br>AWS resource configuration problem<br> ≠<br>Network connectivity problem<br> ≠<br>Application configuration problem</p><p>Keeping these failure domains separate makes troubleshooting significantly faster.</p><p>5.7 Initialization and Dependency Flow</p><p>At this stage, the project has moved from simply containing Terraform files to becoming an initialized Terraform working environment:</p><p>Terraform Configuration<br> │<br> ├── main.tf<br> ├── variables.tf<br> ├── outputs.tf<br> └── terraform.tfvars<br> │<br> ▼<br> terraform init<br> │<br> ▼<br> AWS Provider Loaded<br> │<br> ▼<br> terraform validate<br> │<br> ▼<br> Ready for terraform plan</p><p>The next stage is where the parameterized configuration becomes particularly important: supplying deployment-specific values and inspecting exactly what Terraform intends to create before any infrastructure is changed.</p><p>Part 6 — Parameterizing the AWS Infrastructure</p><p>Hard-coding infrastructure values directly into Terraform resources may work for a single test deployment, but it quickly becomes difficult to maintain when the same infrastructure needs to be deployed with different regions, instance types, names, or credentials.</p><p>A more maintainable approach is to parameterize the infrastructure.</p><p>In this project, Terraform variables are used to separate reusable infrastructure logic from deployment-specific configuration.</p><p>6.1 Why Parameterization Matters</p><p>Instead of embedding values directly into the infrastructure resources, this project defines variables for important deployment parameters such as:</p><p>- AWS Region<br>- Availability Zone<br>- AMI ID<br>- EC2 instance type<br>- EC2 instance name<br>- SSH username<br>- SSH private-key path<br>- EC2 key-pair name</p><p>The basic design is:</p><p>Deployment Values<br> │<br> ▼<br>Terraform Variables<br> │<br> ▼<br>Terraform Resources<br> │<br> ▼<br>AWS Infrastructure</p><p>This makes the Terraform configuration easier to reuse, review, test, and maintain.</p><p>It also makes the infrastructure configuration more suitable for future CI/CD automation.</p><p>— -</p><p>6.2 Define the Terraform Variables</p><p>The variables are defined in “variables.tf”.</p><p>For example:</p><p>variable “instance_type” {<br> description = “EC2 instance type for the application server”<br> type = string<br> default = “t3.micro”<br>}</p><p>The EC2 resource can then reference the variable:</p><p>instance_type = var.instance_type</p><p>This creates a separation between the infrastructure definition and the value supplied for a particular deployment.</p><p>The same principle is applied to the other configuration values.</p><p>variable “aws_region” {<br> description = “AWS region where the infrastructure will be deployed”<br> type = string<br> default = “us-east-1”<br>}</p><p>variable “availability_zone” {<br> description = “Availability Zone where the EC2 instance will be deployed”<br> type = string<br> default = “us-east-1a”<br>}</p><p>variable “instance_name” {<br> description = “Name tag assigned to the EC2 instance”<br> type = string<br> default = “terraform-parameterized-app-server”<br>}</p><p>variable “ssh_user” {<br> description = “SSH username used by Terraform provisioners to connect to the Ubuntu EC2 instance”<br> type = string<br> default = “ubuntu”<br>}</p><p>— -</p><p>6.3 Parameterizing the AMI</p><p>One particularly important design decision in this project was the use of an AMI map:</p><p>variable “ami_ids” {<br> description = “Ubuntu AMI IDs mapped by AWS region”<br> type = map(string)</p><p>default = {<br> us-east-1 = “ami-052355af2a014bd2c”<br> us-east-2 = “ami-0dc6aa44dbcdd872e”<br> }<br>}</p><p>The EC2 resource then selects the AMI based on the configured AWS Region:</p><p>ami = var.ami_ids[var.aws_region]</p><p>This produces the following relationship:</p><p>aws_region<br> │<br> ▼<br>var.ami_ids[var.aws_region]<br> │<br> ▼<br>Region-specific Ubuntu AMI<br> │<br> ▼<br>EC2 Instance</p><p>This approach is useful because AMI IDs are region-specific.</p><p>However, AMI architecture must also be considered.</p><p>During the actual implementation of this project, an incompatible Ubuntu AMI architecture initially caused an EC2 launch failure because the selected AMI architecture did not match the selected instance configuration.</p><p>The issue was resolved by selecting an AMI compatible with the “t3.micro” instance architecture.</p><p>This is an important real-world IaC lesson:</p><p>«Parameterization does not automatically guarantee compatibility. The values supplied to the parameters must still satisfy AWS resource constraints.»</p><p>— -</p><p>6.4 Separate Deployment Values from Terraform Logic</p><p>The project uses “terraform.tfvars” for deployment-specific values.</p><p>The repository includes a safe template:</p><p>terraform.tfvars.example</p><p>The example contains:</p><p>aws_region = “us-east-1”<br>availability_zone = “us-east-1a”<br>instance_type = “t3.micro”<br>instance_name = “terraform-parameterized-app-server”<br>ssh_user = “ubuntu”<br>private_key_path = “C:/Users/YOUR_USERNAME/Downloads/olajide-key.pem”<br>key_name = “olajide-key”</p><p>The real local “terraform.tfvars” contains the values used for the deployment.</p><p>This separation allows the repository to demonstrate the expected configuration without exposing machine-specific or sensitive information.</p><p>— -</p><p>6.5 Sensitive Deployment Values</p><p>The SSH private-key path is a deployment-specific value:</p><p>private_key_path = “C:/Users/OLAJIDE/Downloads/olajide-key.pem”</p><p>The actual private key itself is not stored in the repository.</p><p>The “.gitignore” configuration includes:</p><p>*.pem<br>terraform.tfvars</p><p>This prevents the private key and local deployment variables from accidentally becoming Git-tracked files.</p><p>The important security principle is:</p><p>Terraform Configuration<br> ↓<br>Reusable and version controlled</p><p>Private Key<br> ↓<br>Local / securely managed<br> ↓<br>Never committed to Git</p><p>For production environments, secrets and credentials should be managed using appropriate secret-management and CI/CD mechanisms rather than relying on local private-key files.</p><p>— -</p><p>6.6 Create the Deployment Variables File</p><p>For a local deployment, create:</p><p>terraform.tfvars</p><p>Example:</p><p>aws_region = “us-east-1”<br>availability_zone = “us-east-1a”<br>instance_type = “t3.micro”<br>instance_name = “terraform-parameterized-app-server”<br>ssh_user = “ubuntu”<br>private_key_path = “C:/Users/OLAJIDE/Downloads/olajide-key.pem”<br>key_name = “olajide-key”</p><p>Terraform automatically loads values from “terraform.tfvars” during planning and application.</p><p>The configuration can therefore remain reusable while the deployment values remain outside the main Terraform resource definitions.</p><p>— -</p><p>6.7 Generate the Terraform Plan</p><p>Once the variables have been supplied, generate a plan:</p><p>terraform plan</p><p>Terraform evaluates the configuration and determines what changes would be required to make the real AWS environment match the desired configuration.</p><p>The important point is that:</p><p>terraform plan</p><p>does not normally create the infrastructure.</p><p>Instead, it provides a preview of the proposed changes.</p><p>The workflow becomes:</p><p>Terraform Configuration<br> +<br>Variable Values<br> ↓<br>terraform plan<br> ↓<br>Proposed Infrastructure Changes<br> ↓<br>Review<br> ↓<br>terraform apply</p><p>This plan-before-apply workflow is an important professional Terraform practice because it provides an opportunity to detect incorrect values before making changes to AWS.</p><p>— -</p><p>6.8 Screenshot 02 — Variable Configuration and Plan</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XtUpH3BShDIYVsYnrjUwRQ.png" /><figcaption>Figure 2: Terraform variable values and execution plan showing the parameterized AWS infrastructure configuration before deployment.</figcaption></figure><p>— -</p><p>6.9 Why This Design Is More Maintainable</p><p>The resulting configuration separates three different concerns:</p><p>1. Infrastructure Logic<br> main.tf<br> ↓<br> Defines what Terraform creates</p><p>2. Variable Definitions<br> variables.tf<br> ↓<br> Defines what can be customized</p><p>3. Deployment Values<br> terraform.tfvars<br> ↓<br> Defines values for this deployment</p><p>This separation improves maintainability because changing a deployment value does not necessarily require changing the underlying resource definition.</p><p>For example, changing:</p><p>instance_type = “t3.micro”</p><p>to another compatible instance type can be handled through variable configuration rather than rewriting the EC2 resource.</p><p>Similarly, the region and availability zone can be changed through the appropriate variables, provided the associated AMI and other regional requirements are compatible.</p><p>— -</p><p>6.10 Validate the Plan Before Applying</p><p>Before proceeding to “terraform apply”, review the plan carefully.</p><p>Look for:</p><p>- unexpected resource creation<br>- unexpected resource replacement<br>- incorrect AMI selection<br>- incorrect instance type<br>- incorrect region<br>- incorrect availability zone<br>- incorrect key-pair configuration<br>- unexpected changes to existing resources</p><p>This is particularly important because Terraform will execute the desired configuration, not the configuration you intended to write.</p><p>A senior Infrastructure as Code workflow therefore follows:</p><p>Write<br> ↓<br>Validate<br> ↓<br>Plan<br> ↓<br>Review<br> ↓<br>Apply<br> ↓<br>Validate Real Infrastructure</p><p>The next stage will examine sensitive variable handling and the refinement of the Terraform plan before deployment, including the evidence captured during the actual implementation.</p><p>Part 7 — Refining Variables and Reviewing the Terraform Plan</p><p>A Terraform plan is more than a confirmation that the configuration is syntactically correct. It is an opportunity to inspect the proposed infrastructure before Terraform makes changes to AWS.</p><p>In a real DevOps workflow, this review becomes especially important when variables control infrastructure behavior.</p><p>7.1 Review the Variable Inputs</p><p>The project uses variables for deployment-specific settings such as:</p><p>aws_region<br>availability_zone<br>instance_type<br>instance_name<br>ssh_user<br>private_key_path<br>key_name</p><p>These values influence the resources Terraform will attempt to create.</p><p>For example:</p><p>instance_type = var.instance_type</p><p>means that the EC2 instance type is controlled by the variable rather than being permanently embedded in the resource definition.</p><p>This makes the configuration reusable, but it also means that incorrect variable values can produce incorrect infrastructure.</p><p>Therefore, parameterization must always be combined with validation and plan review.</p><p>7.2 Sensitive and Local Values</p><p>Some variables are not appropriate for publication.</p><p>The project uses:</p><p>private_key_path = “C:/Users/OLAJIDE/Downloads/olajide-key.pem”</p><p>This value identifies the local SSH private key used by the Terraform provisioners.</p><p>The private key itself is not part of the Terraform repository.</p><p>The “.gitignore” file excludes:</p><p>*.pem<br>terraform.tfvars</p><p>This prevents the local private key and deployment-specific variable file from being committed accidentally.</p><p>However, an important distinction should be made:</p><p>«Hiding a file from Git is not the same as securely managing a secret.»</p><p>For production environments, credentials and secrets should be managed through appropriate secret-management solutions, CI/CD secret stores, or other secure mechanisms.</p><p>7.3 Review the Terraform Plan</p><p>After supplying the required variables, run:</p><p>terraform plan</p><p>Terraform evaluates:</p><p>- the configuration files<br>- variable values<br>- provider configuration<br>- current Terraform state<br>- the existing AWS infrastructure</p><p>It then produces a proposed execution plan.</p><p>The plan should be reviewed before running:</p><p>terraform apply</p><p>A useful review asks:</p><p>1. Is the correct AWS Region selected?<br>2. Is the correct Availability Zone selected?<br>3. Is the AMI compatible with the selected EC2 instance?<br>4. Is the intended instance type being created?<br>5. Is the correct EC2 key pair configured?<br>6. Are the expected resources being created?<br>7. Is Terraform proposing any unexpected replacement?<br>8. Are there any values that should not be exposed?</p><p>7.4 Architecture Compatibility Matters</p><p>One of the actual deployment lessons from this project involved AMI and instance compatibility.</p><p>The initial configuration used an Ubuntu AMI with an architecture that was not compatible with the selected EC2 instance configuration.</p><p>The resulting AWS error demonstrated an important principle:</p><p>AMI Architecture<br> +<br>EC2 Instance Architecture<br> ↓<br>Must Be Compatible</p><p>The issue was resolved by selecting an Ubuntu AMI compatible with the “t3.micro” instance.</p><p>This is a good example of why a successful Terraform configuration does not automatically mean that the requested AWS infrastructure is valid.</p><p>Terraform can correctly interpret the configuration while AWS can still reject the requested resource because of an infrastructure-specific constraint.</p><p>7.5 Screenshot 03 — Sensitive Variable Configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXVVyyuCWHFR7DjvCNZEPg.png" /><figcaption>Figure 3: Sensitive deployment-specific variables reviewed during the Terraform planning process.</figcaption></figure><p>This screenshot provides evidence of the variable-handling stage where sensitive or deployment-specific configuration is being considered as part of the Terraform planning workflow.</p><p>7.6 Continue Refining the Plan</p><p>After correcting configuration issues, run the plan again:</p><p>terraform plan</p><p>The goal is not simply to obtain a plan that completes successfully.</p><p>The goal is to obtain a plan that represents the infrastructure you actually intend to deploy.</p><p>This distinction is important:</p><p>Successful Plan<br> ≠<br>Correct Infrastructure</p><p>Instead:</p><p>Successful Plan<br> +<br>Correct Variables<br> +<br>Compatible AWS Resources<br> +<br>Expected Changes<br> =<br>Deployment-Ready Plan</p><p>7.7 Final Plan Review</p><p>Before proceeding to “terraform apply”, the final plan should be reviewed for unexpected behavior.</p><p>At this stage, Terraform should provide a clear picture of the resources that will be created or modified.</p><p>The review process becomes:</p><p>Modify Configuration<br> ↓<br>terraform validate<br> ↓<br>terraform plan<br> ↓<br>Review Variables<br> ↓<br>Review Resource Changes<br> ↓<br>Check AWS Compatibility<br> ↓<br>Approve Deployment</p><p>This workflow reduces avoidable deployment failures and creates a stronger audit trail for Infrastructure as Code changes.</p><p>7.8 Screenshot 04 — Final Variable Plan</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoMeEdPUOlTltJfpKipmYg.png" /><figcaption>Figure 4: Final Terraform variable plan confirming the refined infrastructure configuration before deployment.</figcaption></figure><p>It represents the refined Terraform configuration immediately before moving toward infrastructure creation.</p><p>The progression is therefore:</p><p>Screenshot 02<br>Initial Variable / Plan Review<br> ↓<br>Screenshot 03<br>Sensitive / Deployment-Specific Configuration<br> ↓<br>Screenshot 04<br>Final Variable Plan<br> ↓<br>Terraform Apply</p><p>This progressive evidence is useful in a portfolio because it demonstrates not only the final result, but also how the infrastructure configuration was reviewed and refined before deployment.</p><p>7.9 Professional IaC Principle</p><p>A strong Terraform workflow does not treat “terraform plan” as a formality.</p><p>The plan is a decision point.</p><p>Before applying infrastructure changes, the engineer should be able to answer:</p><p>«”Do I understand exactly what Terraform is about to change, and does that change match the intended architecture?”»</p><p>That mindset becomes increasingly important as infrastructure grows from a single EC2 instance into production environments containing networking, databases, load balancers, autoscaling, IAM, observability, and multiple deployment environments.</p><p>The next section moves from variable management into Terraform provisioners, where the project uses “file”, “remote-exec”, and “local-exec” to configure the EC2 instance after provisioning.</p><p>Part 8 — Configuring the AWS EC2 Instance with Terraform</p><p>With the variables defined and the Terraform plan reviewed, the next step is to translate those parameters into an actual AWS compute resource.</p><p>For this project, the compute layer is an Amazon EC2 instance running Ubuntu.</p><p>The objective is not simply to launch an EC2 instance. The objective is to make the instance reproducible through Terraform while keeping deployment-specific values outside the resource definition.</p><p>8.1 Defining the EC2 Resource</p><p>The EC2 instance is defined in “main.tf” using the “aws_instance” resource:</p><p>resource “aws_instance” “app_server” {<br> ami = var.ami_ids[var.aws_region]<br> instance_type = var.instance_type<br> availability_zone = var.availability_zone<br> key_name = var.key_name</p><p>tags = {<br> Name = var.instance_name<br> }<br>}</p><p>Several important decisions are being made here.</p><p>The AMI is selected from the region-specific AMI map:</p><p>ami = var.ami_ids[var.aws_region]</p><p>The instance type is parameterized:</p><p>instance_type = var.instance_type</p><p>The Availability Zone is also controlled through a variable:</p><p>availability_zone = var.availability_zone</p><p>The EC2 key pair is supplied through:</p><p>key_name = var.key_name</p><p>Finally, the instance receives a meaningful Name tag:</p><p>tags = {<br> Name = var.instance_name<br>}</p><p>This makes the resource easier to identify in the AWS console and in operational environments.</p><p>8.2 Why Parameterize the EC2 Resource?</p><p>Hard-coding values directly into an EC2 resource can make the configuration difficult to reuse.</p><p>For example, this approach:</p><p>instance_type = “t3.micro”</p><p>works for a specific deployment, but it couples the infrastructure definition to one instance size.</p><p>The parameterized approach:</p><p>instance_type = var.instance_type</p><p>allows the same Terraform configuration to support different deployment requirements.</p><p>For example:</p><p>Development<br> ↓<br>t3.micro</p><p>Testing<br> ↓<br>t3.small</p><p>Production<br> ↓<br>Larger instance type</p><p>The actual value can change without rewriting the resource definition.</p><p>8.3 Selecting the AMI Correctly</p><p>The AMI is one of the most important EC2 parameters.</p><p>This project uses an AMI map:</p><p>variable “ami_ids” {<br> description = “Ubuntu AMI IDs mapped by AWS region”<br> type = map(string)</p><p>default = {<br> us-east-1 = “ami-052355af2a014bd2c”<br> us-east-2 = “ami-0dc6aa44dbcdd872e”<br> }<br>}</p><p>Terraform then selects the AMI according to the configured AWS Region.</p><p>This provides a simple form of regional parameterization.</p><p>However, an important operational lesson emerged during implementation: an AMI must be compatible with the architecture supported by the selected EC2 instance type.</p><p>The initial deployment attempt exposed this issue when the selected Ubuntu AMI architecture was incompatible with the chosen “t3.micro” configuration.</p><p>AWS rejected the instance request.</p><p>The solution was to select an AMI compatible with the EC2 instance architecture.</p><p>This is an important Infrastructure as Code lesson:</p><p>«Terraform can correctly process your configuration while AWS can still reject the resulting resource because of an AWS-specific compatibility constraint.»</p><p>8.4 Configuring the EC2 Key Pair</p><p>The instance also receives an EC2 key pair:</p><p>key_name = var.key_name</p><p>For this implementation, the configured key pair was:</p><p>olajide-key</p><p>The corresponding private key was stored locally and used by Terraform’s SSH provisioners.</p><p>The private key itself was not committed to GitHub.</p><p>The “.gitignore” configuration includes:</p><p>*.pem</p><p>This is an important repository hygiene practice because private SSH keys must never be committed to source control.</p><p>8.5 Adding Resource Metadata</p><p>The EC2 instance receives a Name tag:</p><p>tags = {<br> Name = var.instance_name<br>}</p><p>The configured value is:</p><p>terraform-parameterized-app-server</p><p>Tags are operationally useful because they make resources easier to:</p><p>- identify<br>- search<br>- monitor<br>- manage<br>- associate with projects<br>- control through automation<br>- analyze for cost allocation</p><p>In larger environments, a more comprehensive tagging strategy would normally include attributes such as environment, application, owner, cost center, and managed-by metadata.</p><p>8.6 EC2 Is Only One Layer of the Deployment</p><p>It is important to understand that creating the EC2 instance does not automatically make the application reachable.</p><p>The deployment has several layers:</p><p>Terraform<br> ↓<br>AWS EC2<br> ↓<br>Operating System<br> ↓<br>Network Connectivity<br> ↓<br>Security Group<br> ↓<br>SSH Access<br> ↓<br>Apache Installation<br> ↓<br>HTTP Service</p><p>A failure at any layer can prevent the final application from working.</p><p>For example:</p><p>- the EC2 instance can exist but SSH can fail;<br>- SSH can work but Apache can be stopped;<br>- Apache can be running but port 80 can be blocked;<br>- the security group can allow HTTP while the application itself is not listening;<br>- Terraform can complete resource creation while a provisioner fails during post-deployment configuration.</p><p>This layered model became particularly important during the troubleshooting phase of this project.</p><p>8.7 Preparing for Terraform Provisioners</p><p>The EC2 resource also contains Terraform provisioners.</p><p>The first provisioner transfers the web-server script to the instance:</p><p>provisioner “file” {<br> source = “web.sh”<br> destination = “/tmp/web.sh”<br>}</p><p>The second executes the script remotely:</p><p>provisioner “remote-exec” {<br> inline = [<br> “chmod +x /tmp/web.sh”,<br> “sudo /tmp/web.sh”<br> ]<br>}</p><p>These provisioners depend on successful SSH connectivity.</p><p>Therefore, Terraform must be able to establish an SSH connection to the newly created EC2 instance before these steps can succeed.</p><p>This introduces an important distinction:</p><p>EC2 Creation<br> ↓<br>SSH Connectivity<br> ↓<br>Provisioner Execution<br> ↓<br>Application Configuration</p><p>The EC2 resource can be successfully created while the provisioner stage still fails.</p><p>That distinction became one of the key troubleshooting lessons from the real deployment.</p><p>8.8 Production Consideration</p><p>Terraform provisioners are useful for demonstrating post-provisioning configuration and understanding infrastructure lifecycle behavior.</p><p>However, for production infrastructure, configuration management or image-based approaches are generally preferable where practical.</p><p>Examples include:</p><p>- cloud-init<br>- EC2 user data<br>- Packer-built machine images<br>- AWS Systems Manager<br>- configuration-management tools<br>- immutable infrastructure patterns</p><p>The purpose of this project is therefore not to claim that provisioners are the preferred production architecture.</p><p>Instead, the project demonstrates how Terraform can orchestrate infrastructure creation and post-provisioning actions while exposing the operational considerations involved.</p><p>8.9 EC2 Configuration Flow</p><p>The complete EC2 configuration can be viewed as:</p><p>Terraform Variables<br> ↓<br>AMI + Instance Type + AZ + Key Pair<br> ↓<br>aws_instance<br> ↓<br>EC2 Instance Created<br> ↓<br>SSH Connectivity<br> ↓<br>Terraform Provisioners<br> ↓<br>Apache Configuration</p><p>This separation between infrastructure creation and application configuration is central to understanding what happens during “terraform apply”.</p><p>The next section focuses specifically on the Terraform provisioners used by this project: “file”, “remote-exec”, and “local-exec”, including why each was used and the real connectivity problems encountered during deployment.</p><p>Part 9 — Terraform Provisioners: “file”, “remote-exec”, and “local-exec”</p><p>Creating an EC2 instance is only the first stage of this project.</p><p>After the instance is created, the project needs to:</p><p>1. Connect to the new EC2 instance.<br>2. Transfer the Apache configuration script.<br>3. Execute the script remotely.<br>4. Record the EC2 private IP locally.</p><p>Terraform provisioners were used to demonstrate these post-provisioning operations.</p><p>The project uses three provisioner types:</p><p>- “file”<br>- “remote-exec”<br>- “local-exec”</p><p>Each performs a different task.</p><p>— -</p><p>9.1 The Provisioner Workflow</p><p>The implementation follows this sequence:</p><p>EC2 Instance Created<br> ↓<br>SSH Connection Established<br> ↓<br>file Provisioner<br> ↓<br>web.sh Transferred<br> ↓<br>remote-exec Provisioner<br> ↓<br>Apache Installed and Configured<br> ↓<br>local-exec Provisioner<br> ↓<br>Private IP Recorded Locally</p><p>This demonstrates an important Infrastructure as Code concept:</p><p>«Infrastructure provisioning and server configuration can occur as part of a controlled Terraform workflow, but each stage introduces its own failure conditions.»</p><p>— -</p><p>9.2 The “file” Provisioner</p><p>The first provisioner transfers the Apache configuration script from the local Terraform project to the EC2 instance:</p><p>provisioner “file” {<br> source = “web.sh”<br> destination = “/tmp/web.sh”</p><p>connection {<br> type = “ssh”<br> user = var.ssh_user<br> private_key = file(var.private_key_path)<br> host = self.public_ip<br> }<br>}</p><p>The important parameters are:</p><p>source = “web.sh”</p><p>This identifies the local file.</p><p>The destination is:</p><p>destination = “/tmp/web.sh”</p><p>The file is therefore copied to the EC2 instance before it is executed.</p><p>Why use a separate script?</p><p>Instead of placing every Apache configuration command directly inside Terraform, the project keeps the server configuration in:</p><p>web.sh</p><p>This provides a cleaner separation between:</p><p>Infrastructure Definition<br> ↓<br>main.tf</p><p>Server Configuration<br> ↓<br>web.sh</p><p>The approach also makes the shell script easier to inspect and modify independently.</p><p>— -</p><p>9.3 The SSH Connection Block</p><p>The provisioner needs an SSH connection to the EC2 instance.</p><p>The connection configuration is:</p><p>connection {<br> type = “ssh”<br> user = var.ssh_user<br> private_key = file(var.private_key_path)<br> host = self.public_ip<br>}</p><p>Terraform obtains the required values from the project variables.</p><p>For Ubuntu, the SSH user is:</p><p>ubuntu</p><p>The private key is loaded from the configured local path:</p><p>file(var.private_key_path)</p><p>The host is dynamically obtained from:</p><p>self.public_ip</p><p>This is significant because the EC2 public IP is not permanently known before the instance is created.</p><p>Terraform obtains the resulting address from the resource itself.</p><p>— -</p><p>9.4 Why SSH Connectivity Became a Critical Dependency</p><p>The provisioners depend on successful network connectivity.</p><p>During the actual deployment, the project encountered SSH connectivity problems, including a timeout similar to:</p><p>dial tcp 44.214.143.23:22: i/o timeout</p><p>This demonstrated an important operational principle:</p><p>EC2 Exists<br> ≠<br>SSH Is Reachable</p><p>An instance can successfully exist in AWS while Terraform is unable to connect to it.</p><p>Possible failure points include:</p><p>- incorrect private key<br>- incorrect SSH username<br>- incorrect public IP<br>- missing key pair<br>- security group restrictions<br>- network connectivity problems<br>- DNS problems<br>- transient connectivity issues<br>- instance readiness</p><p>Therefore, troubleshooting must consider the complete connection path rather than assuming that successful EC2 creation means SSH must work.</p><p>— -</p><p>9.5 The “remote-exec” Provisioner</p><p>After transferring the script, Terraform uses “remote-exec”:</p><p>provisioner “remote-exec” {<br> inline = [<br> “chmod +x /tmp/web.sh”,<br> “sudo /tmp/web.sh”<br> ]</p><p>connection {<br> type = “ssh”<br> user = var.ssh_user<br> private_key = file(var.private_key_path)<br> host = self.public_ip<br> }<br>}</p><p>The first command makes the script executable:</p><p>chmod +x /tmp/web.sh</p><p>The second executes the script with elevated privileges:</p><p>sudo /tmp/web.sh</p><p>This allows the script to install and configure Apache.</p><p>— -</p><p>9.6 The “local-exec” Provisioner</p><p>The project also uses “local-exec”:</p><p>provisioner “local-exec” {<br> command = “echo ${self.private_ip} &gt; private_ips.txt”<br>}</p><p>Unlike “remote-exec”, this command runs on the machine executing Terraform rather than on the EC2 instance.</p><p>The purpose is to record the EC2 private IP in:</p><p>private_ips.txt</p><p>This provides a simple demonstration of the distinction between local and remote execution.</p><p>local-exec<br> ↓<br>Terraform execution machine</p><p>remote-exec<br> ↓<br>EC2 instance</p><p>— -</p><p>9.7 Provisioner Dependency Chain</p><p>The three provisioners perform different operations but form one deployment workflow:</p><p>aws_instance<br> │<br> ▼<br>EC2 Created<br> │<br> ▼<br>SSH Connection<br> │<br> ├───────────────┐<br> ▼ │<br>file │<br>web.sh copied │<br> │ │<br> ▼ │<br>remote-exec │<br>Apache configured │<br> │ │<br> ▼ │<br>local-exec ◄─────────┘<br>Private IP recorded</p><p>This dependency chain explains why a connectivity problem can prevent later provisioning steps from completing.</p><p>— -</p><p>9.8 Real Deployment Lesson: Provisioner Failure Does Not Mean the Instance Never Existed</p><p>One of the most important lessons from this project was distinguishing between resource creation failure and post-provisioning failure.</p><p>Terraform may successfully create an EC2 instance and then encounter a failure while attempting to connect through SSH.</p><p>For example:</p><p>AWS Resource Creation<br> ↓<br> SUCCESS<br> ↓<br>SSH Connection<br> ↓<br> FAILURE<br> ↓<br>Provisioner<br> ↓<br> FAILURE</p><p>This is different from AWS rejecting the EC2 resource itself.</p><p>Understanding this distinction is essential when reading Terraform output and inspecting Terraform state after a failed deployment.</p><p>— -</p><p>9.9 Resource Replacement and Provisioner Re-execution</p><p>Another important lifecycle consideration is resource replacement.</p><p>If Terraform determines that an EC2 instance must be replaced, the new instance receives a new identity and potentially a new public IP address.</p><p>Provisioners associated with the resource can therefore execute against the replacement instance.</p><p>During the project, resource replacement was required after an unsuccessful provisioning attempt.</p><p>The controlled replacement was performed using:</p><p>terraform apply -replace=aws_instance.app_server</p><p>Terraform then destroyed the affected instance and created a replacement according to the current configuration.</p><p>This demonstrates why provisioners must be treated carefully: their behavior is tied to the lifecycle of the resource to which they are attached.</p><p>— -</p><p>9.10 Screenshot 05 — Provisioner Configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VS0qW0CtrGL2IUfHceX88A.png" /><figcaption>Figure 5: Terraform plan showing the EC2 infrastructure with Terraform provisioners configured for post-provisioning automation.</figcaption></figure><p>It provides evidence of the Terraform plan containing the provisioner-enabled infrastructure configuration.</p><p>— -</p><p>9.11 Screenshot 06 — Provisioner Plan During Key-Pair Replacement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U29joCEEDcsv_RNLg5UT5A.png" /><figcaption>Figure 6: Terraform plan showing the EC2 key-pair configuration and controlled replacement during provisioner troubleshooting.</figcaption></figure><p>It demonstrates how the infrastructure plan changed as the EC2 access configuration was corrected.</p><p>— -</p><p>9.12 Screenshot 07 — Security Group Configuration During Provisioner Troubleshooting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YTWB9vy70RMFAlVnqKpqQ.png" /><figcaption>Figure 7: Terraform plan showing the security group configuration required for SSH and HTTP connectivity during provisioning.</figcaption></figure><p>The security group is a critical dependency because the Terraform provisioners require network access to the EC2 instance.</p><p>For SSH-based provisioning, TCP port 22 must be reachable from the Terraform execution environment.</p><p>For the Apache application, TCP port 80 must also be reachable by the intended clients.</p><p>— -</p><p>9.13 Provisioners: Useful for Learning, Limited for Production</p><p>Provisioners are valuable for understanding Terraform’s execution model and for demonstrating how infrastructure and post-provisioning actions interact.</p><p>However, they should not automatically be treated as the preferred production configuration-management mechanism.</p><p>For production workloads, alternatives may include:</p><p>- EC2 user data<br>- cloud-init<br>- Packer<br>- AWS Systems Manager<br>- configuration-management platforms<br>- immutable machine images<br>- application deployment pipelines</p><p>The choice depends on the architecture, operational requirements, security model, and lifecycle strategy.</p><p>The important lesson is not simply:</p><p>«”Terraform can run commands.”»</p><p>The more important lesson is:</p><p>«”Every post-provisioning mechanism introduces dependencies, failure modes, and lifecycle considerations that must be understood before using it in production.”»</p><p>— -</p><p>9.14 What This Implementation Demonstrates</p><p>This project uses provisioners to demonstrate several practical DevOps concepts:</p><p>- remote SSH connectivity<br>- automated file transfer<br>- remote command execution<br>- local command execution<br>- EC2 lifecycle dependencies<br>- troubleshooting failed connections<br>- resource replacement<br>- Terraform state behavior<br>- post-provisioning automation<br>- separation between infrastructure creation and server configuration</p><p>The next step is to examine the actual “web.sh” configuration script and show how Terraform used it to install, start, enable, and configure Apache on the EC2 instance.</p><p>Part 10 — Configuring Apache with “web.sh”</p><p>Once the EC2 instance has been provisioned and Terraform can establish an SSH connection to it, the next step is to configure the web server.</p><p>For this project, Apache HTTP Server is installed and configured through a Bash script named “web.sh”. Terraform transfers the script to the EC2 instance using the “file” provisioner and then executes it remotely using the “remote-exec” provisioner.</p><p>This creates a simple but complete infrastructure-to-application configuration workflow:</p><p>Terraform<br> ↓<br>EC2 Instance<br> ↓<br>SSH Connection<br> ↓<br>Transfer web.sh<br> ↓<br>Execute web.sh<br> ↓<br>Install Apache<br> ↓<br>Start Apache<br> ↓<br>Create Custom Web Page</p><p>10.1 The “web.sh” Script</p><p>The project uses the following script:</p><p>#!/bin/bash</p><p>sudo apt-get update -y<br>sudo apt-get install -y apache2</p><p>sudo systemctl enable apache2<br>sudo systemctl start apache2</p><p>sudo rm -f /var/www/html/index.html</p><p>sudo tee /var/www/html/index.html &gt; /dev/null &lt;&lt;’EOF’<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br> &lt;title&gt;Terraform Project 3&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br> &lt;h1&gt;Terraform Provisioners Demo&lt;/h1&gt;<br> &lt;p&gt;Apache was provisioned using Terraform file and remote-exec provisioners.&lt;/p&gt;<br> &lt;p&gt;Project: Terraform Parameterized AWS Infrastructure&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>EOF</p><p>The script deliberately keeps the configuration straightforward so that each operation can be understood, validated, and troubleshooting can be performed at every stage.</p><p>10.2 Updating the Ubuntu Package Index</p><p>The first command is:</p><p>sudo apt-get update -y</p><p>This refreshes the Ubuntu package index so the instance has current package metadata before Apache is installed.</p><p>The “-y” option automatically confirms the operation rather than waiting for interactive input.</p><p>This is particularly important for automated provisioning because Terraform cannot depend on a human responding to an installation prompt.</p><p>10.3 Installing Apache</p><p>The next command installs Apache:</p><p>sudo apt-get install -y apache2</p><p>Apache is the HTTP server that will handle requests arriving at the EC2 instance on TCP port 80.</p><p>The installation establishes the application-layer component of the project:</p><p>AWS EC2<br> ↓<br>Ubuntu Linux<br> ↓<br>Apache HTTP Server</p><p>However, installing the package does not by itself demonstrate that the web server is operating correctly. The service must also be enabled and started.</p><p>10.4 Enabling Apache at Boot</p><p>The script executes:</p><p>sudo systemctl enable apache2</p><p>This configures Apache to start automatically when the Ubuntu operating system boots.</p><p>It is important to distinguish “enable” from “start”:</p><p>- “systemctl enable” configures the service to start during boot.<br>- “systemctl start” starts the service immediately.</p><p>10.5 Starting Apache</p><p>The script then starts Apache:</p><p>sudo systemctl start apache2</p><p>This makes the web server available during the current deployment.</p><p>Later, the service can be independently validated with:</p><p>systemctl status apache2</p><p>A successful validation should show the service in an active state:</p><p>active (running)</p><p>This distinction is important in infrastructure troubleshooting. A successful Terraform deployment does not automatically prove that the application service is healthy.</p><p>10.6 Removing the Default Apache Page</p><p>A standard Apache installation on Ubuntu provides a default “index.html”.</p><p>This project removes that default page:</p><p>sudo rm -f /var/www/html/index.html</p><p>The “-f” option forces the removal operation without generating an error if the file is already absent.</p><p>Removing the default page allows the project to create its own application-specific validation page.</p><p>10.7 Creating the Custom Web Page</p><p>The script creates a new “/var/www/html/index.html” file:</p><p>sudo tee /var/www/html/index.html &gt; /dev/null &lt;&lt;’EOF’<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br> &lt;title&gt;Terraform Project 3&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br> &lt;h1&gt;Terraform Provisioners Demo&lt;/h1&gt;<br> &lt;p&gt;Apache was provisioned using Terraform file and remote-exec provisioners.&lt;/p&gt;<br> &lt;p&gt;Project: Terraform Parameterized AWS Infrastructure&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>EOF</p><p>The resulting page provides a visible validation target.</p><p>Instead of validating only that an EC2 instance exists, the deployment can be validated all the way through the application layer:</p><p>EC2 Instance<br> ↓<br>Network Connectivity<br> ↓<br>Security Group<br> ↓<br>SSH Connectivity<br> ↓<br>Terraform Provisioner<br> ↓<br>Apache Installation<br> ↓<br>Apache Service<br> ↓<br>HTTP Port 80<br> ↓<br>Custom Web Page</p><p>This is a stronger validation model because it tests the actual outcome of the infrastructure deployment rather than relying solely on Terraform’s resource status.</p><p>10.8 How Terraform Uses “web.sh”</p><p>The Bash script is not executed directly from the local workstation.</p><p>Terraform first transfers the script to the EC2 instance:</p><p>provisioner “file” {<br> source = “web.sh”<br> destination = “/tmp/web.sh”</p><p>connection {<br> type = “ssh”<br> user = var.ssh_user<br> private_key = file(var.private_key_path)<br> host = self.public_ip<br> }<br>}</p><p>Terraform then executes the script remotely:</p><p>provisioner “remote-exec” {<br> inline = [<br> “chmod +x /tmp/web.sh”,<br> “sudo /tmp/web.sh”<br> ]</p><p>connection {<br> type = “ssh”<br> user = var.ssh_user<br> private_key = file(var.private_key_path)<br> host = self.public_ip<br> }<br>}</p><p>The complete sequence is therefore:</p><p>Local Terraform Project<br> │<br> │ file provisioner<br> ▼<br>/tmp/web.sh on EC2<br> │<br> │ remote-exec<br> ▼<br>chmod +x /tmp/web.sh<br> │<br> ▼<br>sudo /tmp/web.sh<br> │<br> ├── apt-get update<br> ├── install Apache<br> ├── enable Apache<br> ├── start Apache<br> ├── remove default page<br> └── create custom page</p><p>This demonstrates the relationship between infrastructure provisioning and server configuration.</p><p>Terraform creates the infrastructure, establishes connectivity, transfers the configuration script, and executes the configuration remotely.</p><p>10.9 Why Separate “web.sh” from “main.tf”?</p><p>Keeping the operating-system configuration in a separate script provides a clear separation of responsibilities:</p><p>Terraform<br>→ Infrastructure Provisioning</p><p>web.sh<br>→ Operating System / Web Server Configuration</p><p>This makes the project easier to read, troubleshoot, modify, and extend.</p><p>It also provides a useful migration path. The same server configuration logic can later be moved into a more production-oriented mechanism without fundamentally changing the infrastructure design.</p><p>10.10 Production Considerations</p><p>Terraform provisioners are useful for demonstrating remote configuration and understanding infrastructure lifecycle behavior. However, they should be used carefully in production environments.</p><p>For production workloads, common alternatives include:</p><p>- EC2 user data and cloud-init<br>- Packer-built machine images<br>- AWS Systems Manager<br>- Configuration management tools<br>- Container images<br>- Immutable infrastructure patterns</p><p>These approaches can provide better repeatability, observability, failure handling, and separation between infrastructure provisioning and application configuration.</p><p>For this portfolio project, provisioners are intentionally retained because they demonstrate an important real-world Terraform capability and, more importantly, expose the operational challenges associated with establishing connectivity to a newly created EC2 instance.</p><p>10.11 Key DevOps Lesson</p><p>The important lesson from this configuration is that creating infrastructure is only one stage of a successful deployment.</p><p>A production-minded infrastructure engineer must consider the entire path:</p><p>Infrastructure<br> ↓<br>Connectivity<br> ↓<br>Configuration<br> ↓<br>Service Startup<br> ↓<br>Application Availability<br> ↓<br>Validation</p><p>Terraform can report that an EC2 resource was successfully created while the application may still be inaccessible because of SSH connectivity, security-group rules, service configuration, DNS, routing, or application-level problems.</p><p>That is why this project treats infrastructure validation as a separate engineering activity rather than assuming that “terraform apply” alone proves success.</p><p>With the Apache configuration defined, the next stage is to execute the complete Terraform deployment and examine the actual result of the infrastructure and provisioning workflow.</p><p>Part 11 — Executing the Terraform Deployment with “terraform apply”</p><p>After defining the infrastructure, parameterizing the deployment values, configuring the EC2 instance, and preparing the Apache installation script, the next step is to execute the Terraform deployment.</p><p>This is where the configuration moves from a declarative definition to actual AWS resources.</p><p>The deployment workflow is:</p><p>Terraform Configuration<br> ↓<br>terraform init<br> ↓<br>terraform validate<br> ↓<br>terraform plan<br> ↓<br>terraform apply<br> ↓<br>EC2 Provisioning<br> ↓<br>SSH Connectivity<br> ↓<br>web.sh Transfer<br> ↓<br>Apache Configuration<br> ↓<br>Terraform Outputs<br> ↓<br>Application Validation</p><p>11.1 Review Before Applying</p><p>Before executing the deployment, the Terraform configuration should already have passed the earlier validation stages:</p><p>terraform init<br>terraform validate<br>terraform plan</p><p>The purpose of this sequence is to separate different classes of problems.</p><p>“terraform init” prepares the working directory and provider dependencies.</p><p>“terraform validate” checks the Terraform configuration for structural and syntax-related errors.</p><p>“terraform plan” previews the infrastructure changes Terraform intends to make.</p><p>Only after reviewing the plan should the deployment be executed.</p><p>11.2 Applying the Infrastructure</p><p>The deployment is started with:</p><p>terraform apply</p><p>Terraform asks for confirmation before making the planned changes.</p><p>When the plan has been reviewed and the changes are intentional, the deployment can be approved.</p><p>Terraform then begins creating the resources defined in the configuration.</p><p>For this project, the deployment includes the EC2 instance and its associated security configuration, followed by the provisioner workflow responsible for server configuration.</p><p>11.3 What Happens During “terraform apply”</p><p>The important point is that “terraform apply” is not a single operation from an engineering perspective.</p><p>Several stages occur during the deployment:</p><p>1. Terraform evaluates configuration<br> ↓<br>2. AWS resources are created<br> ↓<br>3. EC2 instance becomes available<br> ↓<br>4. Terraform attempts SSH connectivity<br> ↓<br>5. web.sh is transferred<br> ↓<br>6. web.sh is executed remotely<br> ↓<br>7. Apache is installed<br> ↓<br>8. Apache is started<br> ↓<br>9. Custom web page is created<br> ↓<br>10. local-exec records the private IP</p><p>This distinction became particularly important during the actual implementation because the EC2 resource could exist while the provisioner connection was still failing.</p><p>11.4 Infrastructure Creation Does Not Equal Successful Provisioning</p><p>One of the most important lessons from this project was that an EC2 instance being successfully created does not necessarily mean that the complete Terraform deployment has succeeded.</p><p>Terraform must still establish the required SSH connection before the “file” and “remote-exec” provisioners can operate.</p><p>For example, during the implementation, an SSH connection attempt produced:</p><p>dial tcp 44.214.143.23:22: i/o timeout</p><p>The significance of this error is that the problem was no longer necessarily EC2 creation itself.</p><p>The infrastructure had progressed far enough for Terraform to attempt communication with the instance, but the provisioning connection could not be established.</p><p>This requires a different troubleshooting approach.</p><p>Instead of immediately modifying the EC2 resource definition, the investigation needs to consider:</p><ul><li>Security Group rules<br>- TCP port 22<br>- Network connectivity<br>- Public IP address<br>- DNS/network availability<br>- SSH key configuration<br>- SSH username<br>- Private-key path<br>- Instance readiness<br>- Local network connectivity</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkIZlk7PuReczVE0IOIAOA.png" /><figcaption>Figure: Terraform troubleshooting and validation workflow showing failure isolation, infrastructure diagnosis, state reconciliation, controlled resource replacement, and final operational validation.</figcaption></figure><p>This is an important infrastructure-engineering mindset:</p><p>«Troubleshoot the failing layer rather than changing unrelated infrastructure.»</p><p>11.5 Understanding the Provisioner Dependency</p><p>The deployment has a dependency chain:</p><p>EC2 Creation<br> ↓<br>Public IP<br> ↓<br>Network Reachability<br> ↓<br>SSH Port 22<br> ↓<br>SSH Authentication<br> ↓<br>File Provisioner<br> ↓<br>Remote-Exec<br> ↓<br>Apache Configuration</p><p>A failure early in this chain prevents the later stages from completing.</p><p>For example:</p><p>SSH unavailable<br> ↓<br>file provisioner cannot connect<br> ↓<br>web.sh cannot be transferred<br> ↓<br>remote-exec cannot execute<br> ↓<br>Apache configuration does not complete</p><p>This explains why provisioner troubleshooting requires more than simply examining the Terraform syntax.</p><p>11.6 Successful Application of the Infrastructure</p><p>After resolving the connectivity and provisioning issues encountered during implementation, the Terraform deployment completed successfully.</p><p>The final successful replacement operation reported:</p><p>Apply complete! Resources: 1 added, 0 changed, 1 destroyed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-tYQVT4LhTIQ3wIubfS1Q.png" /><figcaption>Figure 8: Successful Terraform apply confirming EC2 provisioning and completion of the Terraform provisioner workflow.</figcaption></figure><p>This result is particularly significant because the deployment had previously encountered provisioner connectivity failures.</p><p>The successful apply demonstrated that Terraform was eventually able to:</p><p>- create the replacement EC2 instance<br>- establish the required connection<br>- execute the provisioning workflow<br>- complete the infrastructure operation<br>- reconcile Terraform state with the resulting AWS infrastructure</p><p>This is more valuable as portfolio evidence than showing only an uncomplicated first deployment because it demonstrates actual troubleshooting and lifecycle management.</p><p>11.7 Why the Successful Apply Matters</p><p>A senior DevOps workflow does not treat a successful “terraform apply” message as the end of the process.</p><p>It is a transition point.</p><p>The next questions should be:</p><p>Was the EC2 instance created?<br> ↓<br>Can I connect to it?<br> ↓<br>Is Apache running?<br> ↓<br>Is port 80 reachable?<br> ↓<br>Does HTTP return the expected page?<br> ↓<br>Do Terraform outputs match the deployed infrastructure?<br> ↓<br>Does Terraform state accurately represent reality?</p><p>This is the difference between deployment execution and deployment validation.</p><p>11.8 Deployment Evidence</p><p>The successful Terraform execution was captured as part of the project’s implementation evidence.</p><p>The screenshot demonstrates the completed “terraform apply” operation after the provisioning workflow was successfully resolved.</p><p>This provides a verifiable milestone between infrastructure deployment and application-level validation.</p><p>The next validation step is to verify that the Apache web server is actually reachable through HTTP and that the custom page created by “web.sh” is being served successfully.</p><p>Part 12 — Validating the Deployed Apache Web Server</p><p>After “terraform apply” completes successfully, the next step is to validate the actual application rather than assuming that successful infrastructure provisioning means the workload is working correctly.</p><p>For this project, Apache HTTP Server is the intended workload. Therefore, validation must move beyond Terraform and confirm that the web server is reachable and serving the custom page created by “web.sh”.</p><p>The validation path is:</p><p>Terraform Apply<br> ↓<br>EC2 Instance<br> ↓<br>Security Group<br> ↓<br>Network Connectivity<br> ↓<br>Apache Service<br> ↓<br>HTTP Port 80<br> ↓<br>Custom Web Page</p><p>12.1 Why Application-Level Validation Matters</p><p>Terraform can confirm that AWS resources were created successfully, but infrastructure creation alone does not prove that the application is accessible.</p><p>For example, an EC2 instance can be:</p><p>- successfully created but unreachable through SSH;<br>- running but missing the required application;<br>- running Apache but blocking TCP port 80;<br>- accessible through SSH but unavailable over HTTP;<br>- serving Apache but displaying the wrong content.</p><p>Therefore, a professional DevOps validation process checks multiple layers of the deployment.</p><p>12.2 Testing HTTP Connectivity</p><p>Once the Terraform deployment and provisioners completed successfully, the EC2 instance’s public IP address was used to test HTTP connectivity.</p><p>The expected request was:</p><p>curl http://&lt;EC2_PUBLIC_IP&gt;</p><p>A successful response should contain the custom HTML generated by “web.sh”, including:</p><p>Terraform Provisioners Demo</p><p>and:</p><p>Project: Terraform Parameterized AWS Infrastructure</p><p>This confirms that the request reached the Apache web server and that the custom page created during provisioning was being served.</p><p>12.3 Browser-Based Verification</p><p>The deployment was also validated through a web browser by navigating to the EC2 instance’s public IP address.</p><p>The expected result was the custom Apache page created by the Terraform provisioning workflow.</p><p>This provides a useful human-readable validation point because the browser confirms the complete request path:</p><p>Browser<br> ↓<br>Internet<br> ↓<br>EC2 Public IP<br> ↓<br>Security Group<br> ↓<br>TCP Port 80<br> ↓<br>Apache<br> ↓<br>/var/www/html/index.html<br> ↓<br>Terraform Project 3 Page</p><p>12.4 Real Troubleshooting During HTTP Validation</p><p>During the actual implementation, HTTP connectivity did not immediately work as expected.</p><p>A direct request to the instance initially failed to connect to port 80.</p><p>At that point, the correct approach was not to immediately assume that Apache itself was the problem.</p><p>The investigation considered the entire connectivity path:</p><p>Client<br> ↓<br>Public IP<br> ↓<br>VPC Network Connectivity<br> ↓<br>Security Group<br> ↓<br>EC2 Instance<br> ↓<br>Apache<br> ↓<br>Port 80</p><p>The Security Group was subsequently verified to contain rules allowing the required traffic, including:</p><p>- SSH — TCP 22<br>- HTTP — TCP 80</p><p>This illustrates an important troubleshooting principle:</p><p>«A failed application connection should be investigated layer by layer rather than immediately changing the application configuration.»</p><p>12.5 Public IP Address Consideration</p><p>Another important operational lesson was that an EC2 public IPv4 address is not necessarily permanent.</p><p>During the implementation, stopping and starting the instance resulted in a different public IP address.</p><p>Therefore, when troubleshooting or validating an EC2 workload using its public IP, the current address should always be confirmed rather than relying on a previously recorded value.</p><p>Terraform can expose the current address through an output:</p><p>output “instance_public_ip” {<br> description = “Public IP address of the Terraform Project 3 application server”<br> value = aws_instance.app_server.public_ip<br>}</p><p>This becomes especially useful after resource replacement or other lifecycle operations.</p><p>12.6 Successful Web Verification</p><p>After the infrastructure, connectivity, and provisioning issues were resolved, the custom Apache page was successfully accessed through the EC2 public IP.</p><p>This confirmed that the deployment had progressed successfully through the major layers:</p><p>Terraform<br> ↓<br>AWS Infrastructure<br> ↓<br>EC2<br> ↓<br>Security Group<br> ↓<br>SSH Provisioning<br> ↓<br>Apache Installation<br> ↓<br>Apache Service<br> ↓<br>HTTP Port 80<br> ↓<br>Custom Web Page</p><p>This is the point where the infrastructure becomes demonstrably useful rather than merely existing as AWS resources.</p><p>12.7 Implementation Evidence</p><p>The successful browser verification was captured as part of the project’s implementation evidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTNHBlzVUCD0vdbb9khLRQ.png" /><figcaption>Figure 9: Successful browser verification of the custom Apache web page provisioned through Terraform.</figcaption></figure><p>This screenshot provides visual evidence that the Apache web server was successfully configured and that the custom page generated by the Terraform provisioning process was accessible.</p><p>Together with the successful Terraform deployment evidence from Part 11, this demonstrates both infrastructure-level and application-level success:</p><p>Terraform Apply Successful<br> +<br>Application Accessible<br> =<br>End-to-End Deployment Validation</p><p>12.8 DevOps Validation Model</p><p>A strong infrastructure deployment should be validated at multiple levels.</p><p>Infrastructure validation</p><p>Are the AWS resources present?</p><p>Connectivity validation</p><p>Can the required network connections be established?</p><p>Service validation</p><p>Is Apache running?</p><p>Application validation</p><p>Does HTTP return the expected application content?</p><p>The combination of these checks provides significantly stronger evidence than a successful “terraform apply” message alone.</p><p>The next step is to examine the Terraform outputs and use them to retrieve important information about the deployed EC2 instance, including its public and private IP addresses.</p><p>13. Terraform Outputs: Retrieving Deployment Information</p><p>Provisioning infrastructure is only part of the Terraform workflow. After Terraform creates a resource, engineers often need important information about that resource for validation, troubleshooting, operations, automation, and downstream processes.</p><p>This is where Terraform outputs become useful.</p><p>In this project, Terraform outputs expose the public and private IP addresses assigned to the EC2 instance.</p><p>13.1 Why Terraform Outputs Matter</p><p>Without outputs, an engineer may need to open the AWS Management Console and manually locate information such as the EC2 instance’s public IP address.</p><p>With Terraform outputs, important resource attributes can be exposed directly through the Terraform CLI.</p><p>The workflow becomes:</p><p>Terraform Configuration<br> ↓<br>Terraform Apply<br> ↓<br>AWS EC2 Instance<br> ↓<br>Terraform State<br> ↓<br>Terraform Outputs<br> ↓<br>Operational Information</p><p>This is particularly useful when infrastructure is created and managed through automation rather than manually through the AWS Console.</p><p>For this project, the outputs provide:</p><p>- EC2 public IP address<br>- EC2 private IP address</p><p>These values were used during the project for SSH connectivity, HTTP validation, troubleshooting, and verification.</p><p>— -</p><p>13.2 Defining the Terraform Outputs</p><p>The project defines the outputs in “outputs.tf”:</p><p>output “instance_public_ip” {<br> description = “Public IP address of the Terraform Project 3 application server”<br> value = aws_instance.app_server.public_ip<br>}</p><p>output “instance_private_ip” {<br> description = “Private IP address of the Terraform Project 3 application server”<br> value = aws_instance.app_server.private_ip<br>}</p><p>Each output contains three important elements:</p><p>Output name</p><p>instance_public_ip</p><p>This is the name Terraform uses when displaying the value.</p><p>Description</p><p>description = “Public IP address of the Terraform Project 3 application server”</p><p>The description provides context for engineers reviewing the configuration.</p><p>Value</p><p>value = aws_instance.app_server.public_ip</p><p>This tells Terraform which resource attribute should be exposed.</p><p>The private IP output follows the same pattern:</p><p>value = aws_instance.app_server.private_ip</p><p>This is preferable to manually recording infrastructure values because the value comes directly from the Terraform-managed resource.</p><p>— -</p><p>13.3 Reviewing Outputs During the Terraform Plan</p><p>Before applying infrastructure changes, Terraform can show the expected output changes as part of the execution plan.</p><p>This provides another opportunity to review the infrastructure before changes are made.</p><p>In this project, the configured outputs were visible during the planning process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJtKy51_DNw-ISRj2LfeOg.png" /><figcaption>Figure 10: Terraform plan showing the configured infrastructure outputs for the EC2 deployment.</figcaption></figure><p>The plan acts as a review checkpoint. It allows the engineer to confirm that Terraform understands the intended infrastructure changes and that the expected resource attributes are being exposed.</p><p>This reinforces an important infrastructure-as-code practice:</p><p>«Review the plan before allowing Terraform to make infrastructure changes.»</p><p>A plan is not merely a formality. It is an opportunity to identify unexpected resource creation, modification, replacement, or output changes before they reach the AWS environment.</p><p>— -</p><p>13.4 Retrieving the Actual Output Values</p><p>After the infrastructure was successfully deployed, Terraform returned the actual values associated with the EC2 instance.</p><p>The deployment produced:</p><p>instance_private_ip = “172.31.3.119”<br>instance_public_ip = “44.200.225.123”</p><p>These values represented the private and public addresses assigned to the deployed EC2 instance at that point in the infrastructure lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwmusAyWUu4rtt6h_YU6og.png" /><figcaption>Figure 11: Terraform output results displaying the deployed EC2 instance public and private IP addresses.</figcaption></figure><p>The same private IP was also written to the local file generated by the “local-exec” provisioner.</p><p>Running:</p><p>cat private_ips.txt</p><p>returned:</p><p>172.31.3.119</p><p>This provided an additional validation point: the value generated by the Terraform “local-exec” provisioner matched the private IP exposed through the Terraform output.</p><p>— -</p><p>13.5 Public IP vs Private IP</p><p>Understanding the difference between these two addresses is important when working with AWS infrastructure.</p><p>The public IP address provides internet-reachable connectivity to the EC2 instance when the surrounding AWS networking and security configuration permit it.</p><p>In this project, the public IP was used for:</p><p>SSH → EC2<br>HTTP → Apache<br>Browser → Apache Web Page</p><p>The private IP address is used for communication within the VPC and connected private networks, subject to the applicable routing and security controls.</p><p>Therefore:</p><p>Public IP<br> ↓<br>External connectivity</p><p>Private IP<br> ↓<br>Internal VPC connectivity</p><p>This distinction becomes particularly important in multi-tier architectures where application servers, databases, caches, and other services communicate over private networking.</p><p>— -</p><p>13.6 Outputs as an Operational Interface</p><p>Terraform outputs can be viewed as an interface between infrastructure code and the engineers or automation systems consuming the infrastructure.</p><p>For example:</p><p>terraform output</p><p>can be used to display all configured outputs.</p><p>Individual outputs can also be retrieved by name:</p><p>terraform output instance_public_ip</p><p>or:</p><p>terraform output instance_private_ip</p><p>This makes Terraform useful beyond infrastructure creation.</p><p>An engineer can provision infrastructure and immediately retrieve the information required for the next operational step.</p><p>For example:</p><p>terraform apply<br> ↓<br>EC2 created<br> ↓<br>terraform output instance_public_ip<br> ↓<br>SSH / HTTP validation</p><p>This is more reliable than manually copying infrastructure information from the AWS Console.</p><p>— -</p><p>13.7 An Important Lesson: Do Not Hardcode Ephemeral IP Addresses</p><p>During the troubleshooting process, the EC2 instance’s public IP changed after the instance lifecycle changed.</p><p>This is an important AWS operational consideration.</p><p>A public IPv4 address associated with an EC2 instance can change depending on how the instance is stopped, started, replaced, or otherwise managed.</p><p>Therefore, an engineer should avoid treating an automatically assigned public IP as a permanent identifier.</p><p>Instead of hardcoding:</p><p>44.200.225.123</p><p>into scripts, documentation, or operational procedures, retrieve the current value from Terraform:</p><p>terraform output instance_public_ip</p><p>This makes the workflow more resilient to infrastructure changes.</p><p>For production architectures that require a stable endpoint, alternatives may include:</p><p>- Elastic IP<br>- Route 53 DNS<br>- Application Load Balancer<br>- Network Load Balancer<br>- CloudFront<br>- service discovery<br>- private DNS</p><p>The appropriate solution depends on the architecture and traffic requirements.</p><p>— -</p><p>13.8 Outputs and Automation</p><p>Terraform outputs become even more valuable when infrastructure is integrated into larger automation workflows.</p><p>For example, a CI/CD pipeline could consume Terraform output values after deployment and use them for subsequent automated operations.</p><p>A simplified workflow could look like:</p><p>CI/CD Pipeline<br> ↓<br>Terraform Plan<br> ↓<br>Terraform Apply<br> ↓<br>Infrastructure Created<br> ↓<br>Terraform Outputs<br> ↓<br>Automated Validation<br> ↓<br>Application Deployment</p><p>In more advanced environments, however, outputs should be designed carefully.</p><p>Not every resource attribute should be exposed as an output, particularly if the value contains sensitive information.</p><p>For example, credentials, secrets, private keys, or other sensitive data should not be exposed unnecessarily through Terraform outputs.</p><p>— -</p><p>13.9 What This Project Demonstrated</p><p>The outputs in this project demonstrated several practical DevOps principles:</p><p>1. Infrastructure information can be exposed programmatically.</p><p>2. Terraform outputs can reduce manual AWS Console inspection.</p><p>3. Public and private resource attributes serve different operational purposes.</p><p>4. Outputs can support troubleshooting and validation.</p><p>5. Outputs can be consumed by automation and downstream processes.</p><p>6. Ephemeral infrastructure values should not be treated as permanent identifiers.</p><p>7. Production architectures should use stable service endpoints where appropriate.</p><p>The important lesson is that Terraform does not stop at resource creation.</p><p>A well-designed Terraform workflow should make the resulting infrastructure understandable, verifiable, and consumable by both engineers and automation.</p><p>The next stage is to examine the complete Terraform infrastructure lifecycle — including state management, reconciliation, controlled replacement, and final destruction of the infrastructure.</p><p>14. Infrastructure Lifecycle Validation: From Terraform State to Running Apache</p><p>Infrastructure as Code is not complete when “terraform apply” returns successfully.</p><p>A professional Terraform workflow requires validation at multiple layers to confirm that the infrastructure exists, the operating system is functioning, the required service is running, and the application is actually reachable.</p><p>In this project, validation was performed progressively from the Terraform state through to the Apache web page.</p><p>The validation path was:</p><p>Terraform State<br> ↓<br>EC2 Instance<br> ↓<br>Network Connectivity<br> ↓<br>SSH Connectivity<br> ↓<br>Apache Service<br> ↓<br>HTTP Port 80<br> ↓<br>Application Response<br> ↓<br>Browser Verification</p><p>This layered approach was particularly important because several problems encountered during the implementation demonstrated that successful infrastructure creation does not automatically mean successful application delivery.</p><p>— -</p><p>14.1 Terraform State Validation</p><p>Terraform maintains a state representation of the infrastructure it manages.</p><p>The state allows Terraform to understand the relationship between the configuration and the resources deployed in AWS.</p><p>The project state was inspected using:</p><p>terraform state list</p><p>The deployment contained the managed resources associated with the application infrastructure, including:</p><p>aws_instance.app_server<br>aws_security_group.app_server</p><p>This confirmed that Terraform was tracking the resources as part of the current infrastructure state.</p><p>However, state validation alone is not sufficient.</p><p>Terraform knowing that an EC2 instance exists does not prove that:</p><p>- SSH is working<br>- Apache is running<br>- port 80 is reachable<br>- the application is responding<br>- the browser can access the service</p><p>Therefore, validation had to continue beyond Terraform itself.</p><p>— -</p><p>14.2 EC2 and Operating System Validation</p><p>The next layer was the EC2 instance.</p><p>The instance needed to be reachable through SSH before the server configuration could be inspected.</p><p>The project used the Terraform-generated public IP and configured EC2 key pair to establish SSH connectivity.</p><p>The general connection pattern was:</p><p>ssh -i “C:/Users/OLAJIDE/Downloads/olajide-key.pem” ubuntu@&lt;EC2_PUBLIC_IP&gt;</p><p>Once connected, the operating system could be inspected directly.</p><p>This provided an important distinction between:</p><p>Infrastructure-level validation</p><p>and</p><p>Operating-system-level validation.</p><p>Terraform can confirm that an EC2 resource exists, but SSH provides evidence that the deployed operating system is actually reachable through the configured network path.</p><p>— -</p><p>14.3 Apache Service Validation</p><p>After establishing SSH connectivity, the Apache service was checked directly on the Ubuntu server.</p><p>The validation command was:</p><p>sudo systemctl status apache2</p><p>The expected result was that Apache was active and running.</p><p>This was an important checkpoint because the EC2 instance could be healthy while the web service itself was not running.</p><p>The validation chain therefore became:</p><p>EC2 exists<br> ↓<br>SSH works<br> ↓<br>Apache installed<br> ↓<br>Apache service running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeN4298iqzrMYnehfmr9Qw.png" /><figcaption>Figure 12: Apache service status confirming that the web server is active and running on the Terraform-provisioned EC2 instance.</figcaption></figure><p>The screenshot provides implementation evidence that the Apache service was running successfully on the provisioned EC2 instance.</p><p>— -</p><p>14.4 Why Service-Level Validation Matters</p><p>A common infrastructure mistake is to stop validation at the resource layer.</p><p>For example:</p><p>terraform apply<br>Apply complete!</p><p>does not necessarily mean:</p><p>Application available</p><p>The EC2 instance could exist while:</p><p>- Apache installation failed<br>- Apache failed to start<br>- the wrong port was configured<br>- the Security Group blocked HTTP<br>- the public IP changed<br>- the application configuration was incorrect<br>- the network path was unavailable</p><p>This project demonstrated that distinction through the actual troubleshooting process.</p><p>The SSH provisioner initially experienced connectivity problems even though the EC2 resource had already been created.</p><p>Later, HTTP connectivity also required separate validation.</p><p>These incidents reinforced a core DevOps principle:</p><p>«Infrastructure provisioning success and application availability are separate validation concerns.»</p><p>— -</p><p>14.5 HTTP Connectivity Validation</p><p>After confirming that Apache was running, the next validation layer was HTTP.</p><p>The server needed to accept connections on TCP port 80.</p><p>A command-line validation could be performed with:</p><p>curl http://&lt;EC2_PUBLIC_IP&gt;</p><p>A successful response should contain the custom page content created by “web.sh”, including:</p><p>Terraform Provisioners Demo</p><p>and:</p><p>Project: Terraform Parameterized AWS Infrastructure</p><p>This confirmed that the request was reaching the Apache web server and that the expected application content was being served.</p><p>The complete path was now:</p><p>Client<br> ↓<br>Public IP<br> ↓<br>AWS Network<br> ↓<br>Security Group<br> ↓<br>EC2<br> ↓<br>TCP Port 80<br> ↓<br>Apache<br> ↓<br>HTML Response</p><p>— -</p><p>14.6 Final Browser Verification</p><p>The final validation step was accessing the application through a web browser using the EC2 public IP address.</p><p>The browser successfully displayed the custom Apache page generated during the Terraform provisioning workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhMZ37KPGbQgZBM3rs-8mg.png" /><figcaption>Figure 13: Final browser verification confirming successful HTTP access to the Apache web application provisioned by Terraform.</figcaption></figure><p>This represents the highest-level validation performed in the project because it verifies the complete path from an external client to the application response.</p><p>The validation can therefore be summarized as:</p><p>Terraform<br> ↓<br>AWS EC2<br> ↓<br>Ubuntu<br> ↓<br>Apache<br> ↓<br>Security Group<br> ↓<br>HTTP/80<br> ↓<br>Browser<br> ↓<br>Application Page</p><p>This is significantly stronger evidence than simply showing a successful “terraform apply”.</p><p>— -</p><p>14.7 Validation as an Engineering Practice</p><p>The validation process used in this project follows a principle that is applicable to larger DevOps environments:</p><p>«Validate each layer independently before declaring the deployment successful.»</p><p>A practical validation model is:</p><p>Layer| Validation<br>Terraform| “terraform state list”<br>AWS| EC2 resource exists<br>Network| Public connectivity<br>SSH| SSH connection<br>OS| Ubuntu server accessible<br>Service| “systemctl status apache2”<br>Port| TCP/HTTP 80<br>Application| “curl http://&lt;EC2_PUBLIC_IP&gt;”<br>Browser| Custom Apache page</p><p>This layered model makes troubleshooting much more systematic.</p><p>If the browser cannot reach the application, the engineer can work backwards through the layers rather than immediately assuming that Terraform is the problem.</p><p>— -</p><p>14.8 From Provisioning to Operational Confidence</p><p>The project therefore moved through several levels of confidence:</p><p>Configuration Valid<br> ↓<br>Terraform Plan Reviewed<br> ↓<br>Infrastructure Provisioned<br> ↓<br>Terraform State Reconciled<br> ↓<br>SSH Connectivity Confirmed<br> ↓<br>Apache Service Confirmed<br> ↓<br>HTTP Connectivity Confirmed<br> ↓<br>Browser Verification Confirmed</p><p>Only after these validation stages could the deployment reasonably be considered successful.</p><p>This approach is particularly important in production DevOps environments, where infrastructure changes may affect multiple dependent services.</p><p>— -</p><p>14.9 What the Validation Process Demonstrated</p><p>This project demonstrated that infrastructure validation should be treated as a deliberate engineering activity rather than an afterthought.</p><p>The implementation provided practical experience with:</p><p>- Terraform state inspection<br>- EC2 validation<br>- SSH connectivity<br>- Linux service validation<br>- Apache verification<br>- Security Group troubleshooting<br>- HTTP connectivity testing<br>- browser-based application validation<br>- infrastructure-to-application verification</p><p>More importantly, it demonstrated how to move from:</p><p>“I created the infrastructure.”</p><p>to:</p><p>“I verified that the infrastructure, server, service, network path, and application are all functioning as expected.”</p><p>That distinction is fundamental to reliable DevOps operations.</p><p>With the infrastructure now validated, the next stage is to examine the complete Terraform lifecycle — including controlled changes, resource replacement, state reconciliation, and ultimately destroying the infrastructure cleanly when it is no longer required.</p><p>15. Terraform Infrastructure Lifecycle: Reconciliation, Controlled Replacement and Destruction</p><p>One of the most important lessons from this project is that Terraform is not simply a tool for creating AWS resources.</p><p>Terraform is an infrastructure lifecycle management tool.</p><p>A real infrastructure workflow must account for what happens after deployment:</p><p>- What happens when a resource changes?<br>- What happens when provisioning fails?<br>- How does Terraform recognize an unhealthy or inconsistent resource?<br>- How can an engineer deliberately replace a resource?<br>- How is infrastructure safely removed when it is no longer required?</p><p>This project exercised these lifecycle concepts through actual EC2 provisioning, provisioner failures, resource replacement, state reconciliation, validation, and final destruction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAps006dNNZNzatzLG0pBg.png" /><figcaption>Figure: Terraform infrastructure lifecycle showing the progression from infrastructure definition and provisioning through configuration, validation, troubleshooting, state reconciliation, controlled replacement, revalidation, and destruction.</figcaption></figure><p>The complete lifecycle can be represented as:</p><p>Define<br> ↓<br>Parameterize<br> ↓<br>Plan<br> ↓<br>Provision<br> ↓<br>Configure<br> ↓<br>Validate<br> ↓<br>Troubleshoot<br> ↓<br>Reconcile<br> ↓<br>Replace<br> ↓<br>Validate Again<br> ↓<br>Destroy</p><p>— -</p><p>15.1 Terraform State as the Source of Lifecycle Awareness</p><p>Terraform uses its state to track resources that it manages.</p><p>The state allows Terraform to compare:</p><p>Desired Configuration<br> ↓<br>Terraform State<br> ↓<br>Real Infrastructure</p><p>When these three perspectives differ, Terraform can determine what action is required.</p><p>This is one of the fundamental principles of Infrastructure as Code.</p><p>Instead of manually asking:</p><p>«”What resources currently exist in AWS?”»</p><p>Terraform can evaluate the infrastructure against the declared configuration and state.</p><p>During this project, the managed resources were inspected with:</p><p>terraform state list</p><p>The state included resources such as:</p><p>aws_instance.app_server<br>aws_security_group.app_server</p><p>This provided visibility into the infrastructure Terraform was responsible for managing.</p><p>— -</p><p>15.2 Provisioner Failure and Resource Health</p><p>The project provided a practical example of why resource creation and resource health are not always the same thing.</p><p>The EC2 instance could be created successfully, but the Terraform “file” provisioner subsequently experienced an SSH connectivity failure:</p><p>dial tcp 44.214.143.23:22: i/o timeout</p><p>This demonstrated an important lifecycle distinction:</p><p>EC2 Resource Created<br> ↓<br>Provisioner Connection Attempt<br> ↓<br>SSH Connectivity Failure</p><p>The infrastructure therefore existed, but the complete Terraform workflow had not successfully completed.</p><p>This is an important operational lesson when using provisioners.</p><p>A successful AWS API operation does not necessarily mean that every post-provisioning operation will succeed.</p><p>The engineer must consider:</p><p>- network reachability<br>- Security Group rules<br>- public IP address<br>- SSH port 22<br>- SSH username<br>- private-key path<br>- EC2 readiness<br>- DNS and local network conditions</p><p>— -</p><p>15.3 Resource Replacement</p><p>During troubleshooting, the EC2 resource required controlled replacement.</p><p>Terraform provides a deliberate mechanism for this:</p><p>terraform apply -replace=aws_instance.app_server</p><p>This tells Terraform that the specified resource should be replaced rather than simply updated in place.</p><p>The lifecycle becomes:</p><p>Existing EC2<br> ↓<br>Mark for Replacement<br> ↓<br>Terraform Plan<br> ↓<br>Destroy Existing Resource<br> ↓<br>Create Replacement Resource<br> ↓<br>Run Provisioners<br> ↓<br>Validate</p><p>This is fundamentally different from manually deleting the instance through the AWS Console.</p><p>The replacement remains part of Terraform’s lifecycle management process.</p><p>— -</p><p>15.4 Why Controlled Replacement Is Important</p><p>Controlled replacement is useful when a resource has become unsuitable for the current deployment state or when a clean recreation is preferable to attempting incremental repair.</p><p>Examples in real environments can include:</p><p>- immutable infrastructure patterns<br>- failed provisioning<br>- incompatible configuration<br>- corrupted or inconsistent resources<br>- changes requiring replacement<br>- recovery from infrastructure drift<br>- controlled recreation during testing</p><p>The important principle is that replacement should be intentional and observable.</p><p>An engineer should review the Terraform plan before allowing a replacement to proceed.</p><p>— -</p><p>15.5 State Reconciliation After Replacement</p><p>After the replacement process completed successfully, Terraform reported:</p><p>Apply complete! Resources: 1 added, 0 changed, 1 destroyed.</p><p>This result demonstrated the lifecycle reconciliation process.</p><p>Terraform had:</p><p>1. identified the resource requiring replacement<br>2. removed the old resource<br>3. created the replacement<br>4. executed the configured provisioning workflow<br>5. updated the infrastructure state</p><p>The resulting state once again represented the infrastructure Terraform was managing.</p><p>This is one of the major advantages of Infrastructure as Code over manual infrastructure management.</p><p>The desired infrastructure can be represented declaratively, while Terraform handles the required lifecycle operations to converge the environment toward that declaration.</p><p>— -</p><p>15.6 Re-Validation After Replacement</p><p>Resource replacement should never be considered complete simply because Terraform reports success.</p><p>The replacement resource must be validated again.</p><p>In this project, validation included:</p><p>Replacement EC2<br> ↓<br>SSH Connectivity<br> ↓<br>Apache Service<br> ↓<br>HTTP Connectivity<br> ↓<br>Browser Verification</p><p>The replacement EC2 instance successfully supported the required provisioning workflow.</p><p>Apache was installed and running, and the custom web page was subsequently verified through HTTP.</p><p>This demonstrated an important operational principle:</p><p>«Every significant infrastructure change should be followed by validation.»</p><p>A replacement is not successful merely because the resource exists. It is successful when the resulting infrastructure satisfies the intended technical requirements.</p><p>— -</p><p>15.7 Understanding “terraform apply” as a Lifecycle Operation</p><p>It is tempting to think of:</p><p>terraform apply</p><p>as simply a command that creates infrastructure.</p><p>In reality, “terraform apply” is a lifecycle operation.</p><p>Depending on the configuration and current state, it can:</p><p>- create resources<br>- modify resources<br>- replace resources<br>- destroy resources<br>- update Terraform state<br>- execute provisioners<br>- produce outputs</p><p>Therefore, the same command can have very different consequences depending on the current infrastructure state and the execution plan.</p><p>This is why the professional workflow is:</p><p>terraform plan</p><p>followed by:</p><p>terraform apply</p><p>rather than treating “apply” as an isolated action.</p><p>— -</p><p>15.8 The Importance of “terraform plan”</p><p>The plan provides a preview of the actions Terraform intends to perform.</p><p>A disciplined workflow is:</p><p>Configuration Change<br> ↓<br>terraform validate<br> ↓<br>terraform plan<br> ↓<br>Review<br> ↓<br>terraform apply<br> ↓<br>Validate Infrastructure</p><p>The plan should be reviewed for unexpected:</p><p>- resource creation<br>- resource destruction<br>- resource replacement<br>- configuration changes<br>- security changes<br>- networking changes<br>- output changes</p><p>For production infrastructure, this review becomes even more important because a seemingly small configuration change can result in a resource replacement or service interruption.</p><p>— -</p><p>15.9 Infrastructure Destruction</p><p>Once the project had been fully validated and the infrastructure was no longer required, the final lifecycle operation was destruction.</p><p>The command was:</p><p>terraform destroy</p><p>Terraform displayed the resources scheduled for deletion and required confirmation before proceeding.</p><p>The operation completed successfully:</p><p>Destroy complete! Resources: 2 destroyed.</p><p>This confirmed that Terraform successfully removed the resources managed by the project.</p><p>The final lifecycle therefore became:</p><p>Provision<br> ↓<br>Configure<br> ↓<br>Validate<br> ↓<br>Troubleshoot<br> ↓<br>Replace<br> ↓<br>Validate Again<br> ↓<br>Destroy</p><p>— -</p><p>15.10 Why Terraform Destroy Matters</p><p>Infrastructure cleanup is an important part of responsible cloud engineering.</p><p>Leaving temporary resources running can result in:</p><p>- unnecessary AWS charges<br>- security exposure<br>- resource sprawl<br>- forgotten infrastructure<br>- operational confusion</p><p>For development and learning environments, destroying infrastructure when it is no longer required is an effective cost-control practice.</p><p>However, “terraform destroy” must always be treated as a destructive operation.</p><p>In production environments, destruction should be protected by appropriate:</p><p>- approval workflows<br>- change management<br>- environment controls<br>- access controls<br>- backup and recovery procedures<br>- resource protection mechanisms</p><p>The command should never be executed casually against critical infrastructure.</p><p>— -</p><p>15.11 Complete Lifecycle Demonstrated by This Project</p><p>This project went beyond basic EC2 creation and demonstrated a complete Infrastructure-as-Code lifecycle:</p><p>1. Define Infrastructure<br> ↓<br>2. Parameterize Configuration<br> ↓<br>3. Initialize Terraform<br> ↓<br>4. Validate Configuration<br> ↓<br>5. Review Terraform Plan<br> ↓<br>6. Provision EC2<br> ↓<br>7. Configure Apache<br> ↓<br>8. Validate Connectivity<br> ↓<br>9. Troubleshoot Provisioner Failure<br> ↓<br>10. Replace EC2 Resource<br> ↓<br>11. Reconcile Terraform State<br> ↓<br>12. Validate Replacement<br> ↓<br>13. Verify Application<br> ↓<br>14. Destroy Infrastructure</p><p>This is a much more realistic representation of Infrastructure as Code than simply demonstrating:</p><p>terraform apply</p><p>and stopping there.</p><p>— -</p><p>15.12 Professional DevOps Lesson</p><p>The strongest lesson from this project is that Infrastructure as Code is fundamentally about controlled infrastructure lifecycle management.</p><p>Terraform provides the mechanisms to define infrastructure declaratively, compare desired and current states, plan changes, apply changes, replace resources, expose operational information, and cleanly destroy managed resources.</p><p>The engineer’s responsibility is to apply these mechanisms safely.</p><p>That means:</p><p>Plan Before Change<br> ↓<br>Apply Deliberately<br> ↓<br>Validate After Change<br> ↓<br>Troubleshoot Systematically<br> ↓<br>Reconcile State<br> ↓<br>Replace When Required<br> ↓<br>Destroy When No Longer Needed</p><p>This lifecycle mindset is transferable to much larger AWS environments involving multiple EC2 instances, VPCs, load balancers, databases, containers, IAM resources, autoscaling, and CI/CD pipelines.</p><p>The next section will focus on the security and cost considerations revealed by this implementation, including SSH exposure, sensitive Terraform variables, public IP usage, Security Group design, provisioner considerations, and practical ways to reduce unnecessary AWS network and compute costs.</p><p>16. Security and Cost Optimization Considerations</p><p>Provisioning infrastructure successfully is only one part of professional cloud engineering.</p><p>A production-minded DevOps engineer must also consider:</p><p>- Security<br>- Network exposure<br>- Credential protection<br>- Access control<br>- Compute costs<br>- Network costs<br>- Resource lifecycle<br>- Operational overhead</p><p>This project was intentionally designed as a hands-on Terraform learning and portfolio implementation. Therefore, some configurations were suitable for demonstrating Terraform concepts but would require additional controls before being used in a production environment.</p><p>This distinction is important:</p><p>«A working implementation is not automatically a production-ready implementation.»</p><p>The following considerations were identified during the project.</p><p>— -</p><p>16.1 Security Group Design</p><p>The EC2 instance required inbound connectivity for two primary purposes:</p><p>TCP 22 → SSH<br>TCP 80 → HTTP</p><p>SSH was required for Terraform’s “file” and “remote-exec” provisioners.</p><p>HTTP was required to make the Apache web server accessible for application validation.</p><p>Conceptually:</p><p>Internet<br> │<br> ├── TCP 22 ──→ EC2<br> │<br> └── TCP 80 ──→ EC2</p><p>This configuration was sufficient for the project demonstration.</p><p>However, exposing SSH broadly to the internet is not a preferred production design.</p><p>A stronger production configuration would restrict SSH access to trusted administrative networks, VPN ranges, bastion hosts, or approved management systems.</p><p>For example:</p><p>Production-oriented approach:</p><p>Trusted Management Network<br> ↓<br> TCP 22<br> ↓<br> EC2</p><p>Rather than:</p><p>Internet<br> ↓<br>TCP 22<br> ↓<br>EC2</p><p>The principle is straightforward:</p><p>«Only expose the network paths that are actually required.»</p><p>— -</p><p>16.2 Least-Privilege Network Access</p><p>Security Groups should follow the principle of least privilege.</p><p>For an application server, the required rules should be evaluated based on the application’s actual architecture.</p><p>For example:</p><p>SSH<br>22<br>↓<br>Administrative access only</p><p>HTTP/HTTPS<br>80/443<br>↓<br>Application traffic</p><p>If the application does not require direct public HTTP access, port 80 should not necessarily be exposed publicly.</p><p>In a production architecture, the EC2 instance could instead sit behind an Application Load Balancer:</p><p>Internet<br> ↓<br>Application Load Balancer<br> ↓<br>Private EC2 Instance</p><p>This provides a stronger security boundary and enables additional capabilities such as:</p><p>- health checks<br>- TLS termination<br>- listener rules<br>- target groups<br>- controlled ingress<br>- horizontal scaling</p><p>— -</p><p>16.3 SSH Keys and Sensitive Files</p><p>The project used an EC2 private key to establish SSH connectivity.</p><p>The private key was stored locally and referenced through the Terraform variable:</p><p>private_key_path = “C:/Users/YOUR_USERNAME/Downloads/olajide-key.pem”</p><p>The private key itself was not intended to be committed to Git.</p><p>The project’s “.gitignore” therefore included:</p><p>*.pem<br>terraform.tfvars</p><p>This is an important repository security practice.</p><p>However, “.gitignore” should not be confused with a complete secret-management solution.</p><p>It prevents accidental Git tracking, but it does not:</p><p>- encrypt the secret<br>- rotate the secret<br>- revoke a compromised secret<br>- prevent local exposure<br>- provide centralized secret management</p><p>For production environments, stronger approaches may include:</p><p>- AWS Systems Manager Session Manager<br>- IAM-based access<br>- AWS Secrets Manager where appropriate<br>- AWS Systems Manager Parameter Store<br>- short-lived credentials<br>- centralized identity and access management</p><p>— -</p><p>16.4 Terraform Variables Are Not Automatically Secrets</p><p>The project demonstrated parameterization through Terraform variables.</p><p>For example:</p><p>variable “private_key_path” {<br> description = “Local path to the SSH private key used by Terraform provisioners”<br> type = string<br>}</p><p>Parameterization improves flexibility, but a variable should not automatically be considered secure simply because it is defined in “variables.tf”.</p><p>Terraform configuration, variable files, state, command output, and CI/CD logs must all be considered when handling sensitive information.</p><p>For actual secrets, engineers should use appropriate secret-management mechanisms rather than placing credentials directly into Terraform configuration.</p><p>— -</p><p>16.5 Public IP Address Considerations</p><p>The EC2 instance used a public IP address during this project because direct SSH and browser-based HTTP validation were required.</p><p>This simplified the learning workflow.</p><p>However, public IP addresses should not automatically be used for internal application components in production.</p><p>A more secure architecture may use:</p><p>Internet<br> ↓<br>Load Balancer<br> ↓<br>Private Subnet<br> ↓<br>EC2</p><p>The EC2 instances can remain private while the load balancer provides the public application endpoint.</p><p>This reduces unnecessary direct exposure of individual compute resources.</p><p>— -</p><p>16.6 EC2 Instance Cost Awareness</p><p>The project used:</p><p>EC2 Instance Type: t3.micro</p><p>This was appropriate for a lightweight learning workload and helped keep compute requirements small.</p><p>However, instance selection should always be based on workload requirements rather than simply choosing the smallest or cheapest instance.</p><p>Important considerations include:</p><p>- CPU utilization<br>- memory requirements<br>- network performance<br>- workload pattern<br>- burst requirements<br>- application latency<br>- expected traffic<br>- availability requirements</p><p>For development environments, smaller instance types can be appropriate.</p><p>For production workloads, right-sizing should be based on measured utilization and performance requirements.</p><p>— -</p><p>16.7 The Importance of Destroying Temporary Infrastructure</p><p>One of the most effective cost-control practices demonstrated by this project was lifecycle cleanup.</p><p>After the infrastructure was no longer required, the deployment was removed using:</p><p>terraform destroy</p><p>The operation completed successfully:</p><p>Destroy complete! Resources: 2 destroyed.</p><p>This prevented the temporary EC2 and Security Group resources from remaining active unnecessarily.</p><p>For learning environments, testing environments, and temporary infrastructure, this can significantly reduce avoidable cloud spending.</p><p>The principle is:</p><p>«If a resource is no longer required, do not leave it running without a reason.»</p><p>— -</p><p>16.8 Network Cost Awareness</p><p>Cloud cost optimization is not limited to compute instances.</p><p>Network architecture can also influence AWS costs.</p><p>For example, applications frequently accessing AWS services such as Amazon S3 may benefit from private connectivity mechanisms rather than unnecessarily routing traffic through external paths or network address translation infrastructure.</p><p>A common AWS optimization is an S3 Gateway VPC Endpoint.</p><p>Conceptually:</p><p>EC2<br> │<br> │ S3 request<br> ↓<br>S3 Gateway VPC Endpoint<br> │<br> ↓<br>Amazon S3</p><p>This can allow traffic from resources in a VPC to reach S3 through the AWS private networking path without requiring a NAT Gateway for that S3 traffic.</p><p>This is particularly relevant because NAT Gateway charges can include hourly processing and data-processing costs.</p><p>The exact cost benefit depends on the architecture, traffic volume, and services involved.</p><p>Therefore, cost optimization should be based on actual traffic patterns rather than assuming that every endpoint automatically produces savings.</p><p>— -</p><p>16.9 Avoiding Unnecessary NAT Gateway Costs</p><p>NAT Gateways are useful when private subnet resources need outbound internet access.</p><p>However, they can become a significant cost component in architectures with substantial traffic.</p><p>If a private workload only needs access to AWS services that support VPC endpoints, an endpoint can sometimes reduce unnecessary NAT processing.</p><p>For example:</p><p>Without S3 Gateway Endpoint</p><p>Private EC2<br> ↓<br>NAT Gateway<br> ↓<br>S3</p><p>Compared with:</p><p>With S3 Gateway Endpoint</p><p>Private EC2<br> ↓<br>S3 Gateway VPC Endpoint<br> ↓<br>S3</p><p>The second design can avoid sending S3 traffic through the NAT Gateway.</p><p>This is an example of a broader DevOps principle:</p><p>«Cost optimization should be considered at the architecture level, not only at the resource-size level.»</p><p>— -</p><p>16.10 Provisioner Security and Operational Considerations</p><p>This project used:</p><p>- “file”<br>- “remote-exec”<br>- “local-exec”</p><p>These provisioners were valuable for demonstrating Terraform’s ability to perform post-provisioning actions.</p><p>However, provisioners introduce operational dependencies.</p><p>For example:</p><p>EC2 Creation<br> ↓<br>Network Ready<br> ↓<br>SSH Available<br> ↓<br>Private Key Available<br> ↓<br>Terraform Connects<br> ↓<br>Script Transfer<br> ↓<br>Script Execution</p><p>If any stage fails, the provisioning workflow can fail.</p><p>This was demonstrated by the actual SSH timeout encountered during the project.</p><p>For production infrastructure, alternatives may include:</p><p>- EC2 user data<br>- cloud-init<br>- Packer-built machine images<br>- AWS Systems Manager<br>- configuration management<br>- container images<br>- immutable infrastructure<br>- CI/CD deployment mechanisms</p><p>Provisioners are therefore best treated as a capability that should be used deliberately rather than as the default configuration-management mechanism.</p><p>— -</p><p>16.11 Security and Cost Are Connected</p><p>Security and cost should not be treated as completely separate concerns.</p><p>For example, an unnecessarily exposed public server can increase security risk.</p><p>An unnecessarily large EC2 instance can increase cost.</p><p>An architecture that sends avoidable traffic through a NAT Gateway can increase network costs.</p><p>A forgotten development environment can create both:</p><p>- unnecessary expenditure<br>- unnecessary security exposure</p><p>Therefore, professional cloud engineering considers:</p><p>Security<br> +<br>Reliability<br> +<br>Performance<br> +<br>Operational Complexity<br> +<br>Cost</p><p>rather than optimizing only one dimension.</p><p>— -</p><p>16.12 Project-Level Security and Cost Assessment</p><p>For this project, the main considerations can be summarized as follows:</p><p>Area| Project Approach| Production Consideration<br>EC2| “t3.micro”| Right-size based on workload<br>SSH| Required for provisioners| Restrict administrative access<br>HTTP| Public validation| Prefer controlled ingress<br>Private key| Local “.pem”| Use stronger access mechanisms<br>Variables| Parameterized| Protect sensitive values<br>Public IP| Used for testing| Prefer stable/controlled endpoints<br>Provisioners| “file”, “remote-exec”, “local-exec”| Prefer cloud-init/SSM/immutable patterns where appropriate<br>Cleanup| “terraform destroy”| Use controlled lifecycle management<br>S3 connectivity| Not part of this deployment| Consider VPC endpoints where appropriate<br>NAT| Not required by this project| Avoid unnecessary NAT processing</p><p>The purpose of this table is not to imply that the project was insecure or incorrectly designed.</p><p>Instead, it demonstrates the difference between a working educational implementation and a production-hardened architecture.</p><p>— -</p><p>16.13 Senior DevOps Perspective</p><p>A senior DevOps engineer does not evaluate infrastructure using only one question:</p><p>«”Does it work?”»</p><p>The stronger questions are:</p><p>Does it work?<br> ↓<br>Is it secure?<br> ↓<br>Is it reliable?<br> ↓<br>Is it observable?<br> ↓<br>Is it maintainable?<br> ↓<br>Is it scalable?<br> ↓<br>Is it cost-effective?<br> ↓<br>Can it be safely changed?<br> ↓<br>Can it be safely removed?</p><p>That mindset transforms Infrastructure as Code from a simple provisioning mechanism into an engineering discipline.</p><p>The next section will examine production improvements and how this Terraform implementation could evolve from a learning project into a more production-oriented AWS architecture, including improved networking, configuration management, IAM, remote state, CI/CD, observability, and more resilient application deployment.</p><p>17. Production Improvements: Evolving the Terraform Project Toward Production</p><p>The Terraform implementation in this project successfully demonstrates parameterized infrastructure provisioning, EC2 configuration, provisioners, Apache deployment, validation, troubleshooting, state reconciliation, controlled replacement, and infrastructure destruction.</p><p>However, a production environment requires additional engineering controls.</p><p>The objective is not to claim that this project is production-ready as implemented. Instead, the project provides a practical foundation that can be evolved into a more resilient, secure, scalable, and operationally mature AWS architecture.</p><p>A useful DevOps principle is:</p><p>«Build the simplest working system first, then evolve it deliberately toward production requirements.»</p><p>The following improvements would be appropriate for that evolution.</p><p>17.1 Move Terraform State to a Remote Backend</p><p>This project uses Terraform state during local development. For a team environment, state should normally be stored remotely.</p><p>A production-oriented implementation could use an Amazon S3 backend with appropriate access controls, encryption, versioning, and state locking.</p><p>Modern Terraform versions also support S3-native state locking through the “use_lockfile” backend setting.</p><p>For example:</p><p>terraform {<br> backend “s3” {<br> bucket = “company-terraform-state”<br> key = “applications/web-server/terraform.tfstate”<br> region = “us-east-1”<br> encrypt = true<br> use_lockfile = true<br> }<br>}</p><p>The bucket itself should be protected through appropriate IAM permissions, encryption, versioning, and restricted access.</p><p>The important production principle is:</p><p>«Terraform state is infrastructure data and should be treated as sensitive operational information.»</p><p>A remote backend also makes collaboration safer because multiple engineers and automation systems can work against the same authoritative state.</p><p>— -</p><p>17.2 Improve the Network Architecture</p><p>The current project intentionally keeps the architecture simple so that the Terraform lifecycle can be demonstrated clearly.</p><p>A production application would normally use a more deliberate VPC architecture.</p><p>A common design would be:</p><p>Internet<br> |<br> v<br> Route 53 / DNS<br> |<br> v<br> Application Load<br> Balancer<br> |<br> + — — — — — — — + — — — — — — — +<br> | |<br> v v<br> Private Subnet Private Subnet<br> | |<br> v v<br> EC2 / ASG EC2 / ASG<br> | |<br> + — — — — — — -+ — — — — — — — -+<br> |<br> AWS Services<br> |<br> VPC Endpoints / NAT</p><p>This design separates public-facing components from application workloads.</p><p>Instead of exposing an EC2 instance directly to the internet, the application servers can remain in private subnets while the Application Load Balancer provides the public entry point.</p><p>This improves security and provides a foundation for high availability.</p><p>— -</p><p>17.3 Replace SSH-Based Provisioners with More Production-Oriented Configuration</p><p>The project intentionally demonstrates Terraform’s:</p><p>- “file” provisioner<br>- “remote-exec” provisioner<br>- “local-exec” provisioner</p><p>These were valuable for demonstrating the relationship between infrastructure provisioning and post-provisioning configuration.</p><p>However, provisioners introduce additional operational dependencies.</p><p>For example:</p><p>Terraform<br> |<br> v<br>EC2 created<br> |<br> v<br>Public IP available<br> |<br> v<br>Network connectivity<br> |<br> v<br>SSH available<br> |<br> v<br>Authentication succeeds<br> |<br> v<br>Provisioner executes</p><p>A failure anywhere in this chain can cause the provisioning workflow to fail.</p><p>This project demonstrated that limitation through the real SSH timeout encountered during deployment.</p><p>For production, alternatives include:</p><p>- EC2 user data<br>- cloud-init<br>- AWS Systems Manager<br>- Packer-built machine images<br>- configuration management<br>- container images<br>- immutable infrastructure</p><p>For example, AWS Systems Manager can reduce the need to expose SSH access to application servers.</p><p>The production evolution is therefore:</p><p>Learning / Demonstration</p><p>Terraform<br> |<br> v<br>EC2<br> |<br> v<br>SSH<br> |<br> v<br>remote-exec</p><p>toward:</p><p>Production-Oriented</p><p>Terraform<br> |<br> v<br>EC2 / ASG<br> |<br> v<br>SSM / User Data / Immutable Image<br> |<br> v<br>Application</p><p>— -</p><p>17.4 Apply IAM Least Privilege</p><p>The next production improvement would be stronger identity and access management.</p><p>Instead of relying on long-lived credentials or manually managed access wherever possible, AWS IAM roles should be used for workloads that need to communicate with AWS services.</p><p>For example:</p><p>EC2 Instance<br> |<br> v<br>IAM Instance Role<br> |<br> + — → S3<br> |<br> + — → CloudWatch<br> |<br> + — → Systems Manager</p><p>The role should contain only the permissions required by the workload.</p><p>This follows the principle of least privilege:</p><p>«Grant only the permissions required to perform the intended operation.»</p><p>Terraform automation should also use an appropriately scoped identity rather than broad administrator permissions wherever practical.</p><p>— -</p><p>17.5 Introduce Proper Secrets Management</p><p>The project deliberately excludes “terraform.tfvars” and “.pem” files from Git through “.gitignore”.</p><p>For example:</p><p>*.pem<br>terraform.tfvars</p><p>This prevents accidental Git commits, but “.gitignore” should not be confused with a secrets-management system.</p><p>For production workloads, sensitive information should be managed through appropriate services and mechanisms such as:</p><p>- AWS Secrets Manager<br>- AWS Systems Manager Parameter Store<br>- IAM roles<br>- CI/CD secret stores<br>- environment-specific secure configuration</p><p>The objective is to prevent credentials and secrets from being embedded directly into source code or unnecessarily distributed across developer machines.</p><p>— -</p><p>17.6 Use a Stable Application Endpoint</p><p>During this project, the EC2 public IP was used for testing.</p><p>That worked for demonstrating the infrastructure, but public IP addresses are not an ideal application endpoint because an instance’s public IP can change when the instance is stopped and started.</p><p>A production architecture should normally provide a stable endpoint through components such as:</p><p>- Application Load Balancer<br>- Route 53<br>- Elastic IP where appropriate<br>- CloudFront for suitable workloads<br>- private DNS/service discovery for internal applications</p><p>A production request path could therefore become:</p><p>User<br> |<br> v<br>Route 53<br> |<br> v<br>Application Load Balancer<br> |<br> v<br>Target Group<br> |<br> v<br>EC2 Auto Scaling Group</p><p>This separates the application’s public identity from individual EC2 instances.</p><p>— -</p><p>17.7 Enable HTTPS/TLS</p><p>The demonstration application uses HTTP because the objective was to validate basic network and application connectivity.</p><p>A production deployment should normally protect application traffic with HTTPS.</p><p>A common AWS implementation would use:</p><p>Client<br> |<br> | HTTPS :443<br> v<br>Application Load Balancer<br> |<br> | HTTP/HTTPS<br> v<br>Application Servers</p><p>AWS Certificate Manager can be used to manage TLS certificates for supported AWS services.</p><p>This provides encrypted communication between the client and the public application endpoint.</p><p>— -</p><p>17.8 Introduce Auto Scaling and High Availability</p><p>The project intentionally provisions a single EC2 instance.</p><p>That is appropriate for demonstrating Terraform resource creation and lifecycle management, but a single instance represents a single point of failure.</p><p>A production architecture could use:</p><p>- multiple Availability Zones<br>- Auto Scaling Groups<br>- Application Load Balancer<br>- health checks<br>- multiple EC2 instances<br>- automated replacement of unhealthy instances</p><p>The architecture could evolve from:</p><p>Internet<br> |<br> v<br>Single EC2<br> |<br>Application</p><p>to:</p><p>Internet<br> |<br> v<br> Application LB<br> / \<br> / \<br> v v<br> EC2 AZ-A EC2 AZ-B<br> \ /<br> \ /<br> Auto Scaling</p><p>This improves availability and allows capacity to respond to changing demand.</p><p>— -</p><p>17.9 Add Observability</p><p>Production infrastructure must be observable.</p><p>Creating an EC2 instance successfully does not tell an operations team whether the application remains healthy after deployment.</p><p>A production implementation could integrate:</p><p>- Amazon CloudWatch metrics<br>- CloudWatch Logs<br>- alarms<br>- application health checks<br>- centralized logging<br>- dashboards<br>- alerting<br>- AWS CloudTrail for auditing</p><p>A useful operational model is:</p><p>Infrastructure<br> |<br> v<br>Metrics + Logs<br> |<br> v<br>CloudWatch<br> |<br> v<br>Alarms<br> |<br> v<br>Notification / Incident Response</p><p>This changes the operational model from simply asking:</p><p>«”Did Terraform deploy successfully?”»</p><p>to asking:</p><p>«”Is the infrastructure and application healthy after deployment?”»</p><p>— -</p><p>17.10 Introduce CI/CD for Terraform</p><p>The current project was executed interactively from a local development environment.</p><p>A mature DevOps workflow would move Terraform execution into a controlled CI/CD pipeline.</p><p>A typical workflow could be:</p><p>Developer<br> |<br> v<br>Git Commit / Pull Request<br> |<br> v<br>CI Validation<br> |<br> + — → terraform fmt<br> |<br> + — → terraform validate<br> |<br> + — → Security / Policy Checks<br> |<br> + — → terraform plan<br> |<br> v<br>Review / Approval<br> |<br> v<br>terraform apply<br> |<br> v<br>AWS Infrastructure</p><p>This provides better consistency, auditability, and separation of duties.</p><p>The exact CI/CD platform could vary, including GitHub Actions, GitLab CI, Jenkins, or another enterprise platform.</p><p>— -</p><p>17.11 Separate Environments</p><p>A production implementation should distinguish environments such as:</p><p>Development<br> |<br> v<br>Staging<br> |<br> v<br>Production</p><p>Each environment should have controlled configuration and state.</p><p>Terraform can support environment separation through appropriate repository structures, variable files, modules, separate state, or workspaces where they are genuinely appropriate.</p><p>The important principle is not simply creating multiple directories or workspaces.</p><p>The real objective is:</p><p>«Prevent changes intended for one environment from unintentionally affecting another environment.»</p><p>— -</p><p>17.12 Introduce Terraform Modules</p><p>As infrastructure grows, repeating the same Terraform resources across multiple environments becomes difficult to maintain.</p><p>Reusable modules can encapsulate infrastructure patterns.</p><p>For example:</p><p>Terraform Root Module<br> |<br> + — → Network Module<br> |<br> + — → Security Group Module<br> |<br> + — → EC2 Module<br> |<br> + — → Load Balancer Module<br> |<br> + — → Monitoring Module</p><p>Modules can provide:</p><p>- reusability<br>- consistency<br>- standardization<br>- easier maintenance<br>- clearer architecture<br>- controlled interfaces between infrastructure components</p><p>The current project intentionally remains small enough to understand directly. Modularization becomes increasingly valuable as the infrastructure grows.</p><p>— -</p><p>17.13 Add Infrastructure Security Scanning</p><p>Before infrastructure reaches production, Terraform configurations can be scanned for common security and configuration issues.</p><p>Examples of tools that can be incorporated include:</p><p>- Checkov<br>- Trivy<br>- tfsec-compatible security scanning approaches<br>- Terraform validation<br>- policy-as-code frameworks</p><p>These tools can identify problems such as overly permissive network rules, insecure configurations, and policy violations.</p><p>For example:</p><p>Terraform Code<br> |<br> + — → terraform fmt<br> |<br> + — → terraform validate<br> |<br> + — → Security Scan<br> |<br> + — → Policy Check<br> |<br> v<br>terraform plan</p><p>These checks are recommended production improvements for this project; they were not part of the implementation documented in the preceding sections.</p><p>— -</p><p>17.14 Strengthen Cost Management</p><p>Cost optimization should also become part of the infrastructure lifecycle.</p><p>The project already demonstrated an important cost-control practice by destroying the temporary infrastructure after validation:</p><p>terraform destroy</p><p>For production environments, additional controls could include:</p><p>- right-sizing EC2 instances<br>- Auto Scaling<br>- Savings Plans where appropriate<br>- Reserved capacity strategies where appropriate<br>- S3 lifecycle policies<br>- CloudWatch cost monitoring<br>- AWS Budgets<br>- tagging for cost allocation<br>- avoiding unnecessary NAT Gateway traffic<br>- using VPC endpoints where they provide a suitable and economical connectivity pattern</p><p>For example, when workloads access Amazon S3 from within a VPC, an S3 Gateway VPC Endpoint can provide private connectivity without requiring the traffic to traverse a NAT Gateway.</p><p>This is an example of how network architecture and cost optimization can be considered together rather than treated as separate concerns.</p><p>— -</p><p>17.15 Standardize Resource Tagging</p><p>Production infrastructure should use consistent tagging.</p><p>For example:</p><p>tags = {<br> Name = var.instance_name<br> Environment = var.environment<br> Project = “terraform-parameterized-aws-infrastructure”<br> Owner = “DevOps”<br> ManagedBy = “Terraform”<br>}</p><p>Standardized tags can support:</p><p>- cost allocation<br>- ownership<br>- resource discovery<br>- automation<br>- compliance<br>- operational troubleshooting</p><p>Tagging conventions should be defined as organizational standards rather than applied inconsistently by individual engineers.</p><p>— -</p><p>17.16 The Production Evolution of This Project</p><p>The project can therefore evolve through several maturity stages.</p><p>Stage 1 — Learning and Validation</p><p>Terraform<br> |<br> v<br>EC2<br> |<br> v<br>SSH Provisioners<br> |<br> v<br>Apache</p><p>Stage 2 — Improved Infrastructure</p><p>Terraform<br> |<br> v<br>VPC<br> |<br> + — → Security Groups<br> |<br> + — → Private Subnets<br> |<br> + — → EC2<br> |<br> + — → SSM</p><p>Stage 3 — Production Architecture</p><p>Internet<br> |<br> v<br> Route 53<br> |<br> v<br> Application Load<br> Balancer<br> |<br> + — — — — — -+ — — — — — -+<br> | |<br> v v<br> Private Subnet Private Subnet<br> | |<br> v v<br> EC2/ASG EC2/ASG<br> | |<br> + — — — — — -+ — — — — — -+<br> |<br> + — — — — — -+ — — — — — -+<br> | |<br> v v<br> CloudWatch AWS Services<br> Monitoring VPC Endpoints/SSM</p><p>Stage 4 — DevOps Automation</p><p>Developer<br> |<br> v<br>GitHub<br> |<br> v<br>CI/CD Pipeline<br> |<br> + — → Format<br> + — → Validate<br> + — → Security Scan<br> + — → Plan<br> |<br> v<br>Approval<br> |<br> v<br>Terraform Apply<br> |<br> v<br>AWS Infrastructure<br> |<br> v<br>Monitoring / Alerting</p><p>This progression demonstrates an important DevOps engineering principle:</p><p>«Production readiness is an evolution of architecture, automation, security, observability, reliability, and operational controls — not simply adding more Terraform code.»</p><p>17.17 What Was Implemented vs. What Is Recommended</p><p>It is important to distinguish the actual implementation from the production improvements discussed in this section.</p><p>Implemented in this project:</p><p>- Terraform-managed EC2 infrastructure<br>- Parameterized Terraform variables<br>- AWS provider configuration<br>- EC2 key pair integration<br>- Terraform provisioners<br>- Apache installation<br>- Security Group configuration<br>- Terraform outputs<br>- Infrastructure validation<br>- Troubleshooting<br>- Resource replacement<br>- Terraform state reconciliation<br>- Infrastructure destruction<br>- Cost-aware temporary infrastructure usage</p><p>Recommended for a production evolution:</p><p>- Remote Terraform state<br>- Stronger state protection<br>- Private application subnets<br>- Application Load Balancer<br>- Auto Scaling<br>- HTTPS/TLS<br>- IAM roles and least privilege<br>- AWS Systems Manager<br>- Secrets Manager / Parameter Store<br>- CloudWatch observability<br>- CI/CD automation<br>- Security and policy scanning<br>- Reusable Terraform modules<br>- Environment separation<br>- Standardized tagging<br>- High-availability architecture</p><p>This distinction is important for professional documentation because a strong portfolio should demonstrate what was actually built while also showing that the engineer understands how the solution should evolve in a real production environment.</p><p>The project therefore moves from a working Terraform demonstration toward a broader DevOps engineering mindset:</p><p>Infrastructure as Code → Automation → Security → Reliability → Observability → Scalability → Cost Optimization → Operational Maturity</p><p>That is the path from simply provisioning infrastructure to engineering infrastructure that can be operated confidently in production.</p><p>18. Key Lessons and Senior DevOps Engineering Takeaways</p><p>Completing this project was not simply an exercise in writing Terraform configuration.</p><p>The more important objective was to understand what happens when infrastructure moves from code to a real AWS environment, and how an engineer responds when the deployment does not behave exactly as expected.</p><p>The project demonstrated the complete lifecycle:</p><p>Define<br> ↓<br>Parameterize<br> ↓<br>Plan<br> ↓<br>Provision<br> ↓<br>Configure<br> ↓<br>Validate<br> ↓<br>Troubleshoot<br> ↓<br>Reconcile<br> ↓<br>Replace<br> ↓<br>Validate Again<br> ↓<br>Destroy</p><p>Several lessons from this implementation are particularly important for anyone working with Terraform, AWS, and DevOps automation.</p><p>18.1 Terraform Is More Than an Infrastructure Creation Tool</p><p>A common beginner perception is:</p><p>«Terraform creates AWS resources.»</p><p>That is true, but incomplete.</p><p>Terraform also provides a mechanism for describing the desired state of infrastructure and comparing that desired state with Terraform’s recorded state.</p><p>This makes Terraform useful for:</p><p>- provisioning<br>- change management<br>- infrastructure reconciliation<br>- controlled replacement<br>- lifecycle management<br>- repeatability<br>- automation<br>- collaboration</p><p>The project demonstrated this when an EC2 resource required replacement and Terraform was used to deliberately reconcile the infrastructure.</p><p>— -</p><p>18.2 “terraform plan” Is an Engineering Decision Point</p><p>A Terraform plan should not be treated as a command that is executed only because Terraform requires it before deployment.</p><p>It is a review mechanism.</p><p>Before applying a plan, an engineer should ask:</p><p>- Is the correct AWS Region selected?<br>- Is the correct Availability Zone selected?<br>- Is the AMI compatible with the selected instance architecture?<br>- Is the intended EC2 instance type being used?<br>- Is the correct key pair configured?<br>- Are the expected resources being created?<br>- Are any resources unexpectedly being replaced?<br>- Are security rules appropriate?<br>- Are sensitive values exposed?<br>- Is the planned change actually what the application requires?</p><p>This project demonstrated why that review matters when the initial AMI configuration was incompatible with the selected EC2 instance architecture.</p><p>The lesson is simple:</p><p>«A successful Terraform plan does not automatically mean a correct infrastructure design.»</p><p>The plan must be interpreted.</p><p>— -</p><p>18.3 Infrastructure Creation and Infrastructure Readiness Are Different</p><p>One of the most important lessons from this project was the difference between:</p><p>EC2 creation</p><p>and</p><p>EC2 readiness for automation.</p><p>Terraform can successfully create an EC2 instance while a subsequent provisioner fails because:</p><p>- SSH is unavailable<br>- network connectivity is interrupted<br>- the security group does not permit the connection<br>- the instance is not ready<br>- the wrong username is used<br>- the private key is incorrect<br>- the public IP is inaccessible<br>- DNS or network connectivity fails</p><p>The actual deployment demonstrated this distinction through the SSH timeout:</p><p>dial tcp 44.214.143.23:22: i/o timeout</p><p>The correct response was not to assume that the EC2 resource was necessarily broken.</p><p>Instead, the failure had to be isolated to the appropriate layer.</p><p>— -</p><p>18.4 Troubleshooting Should Be Layered</p><p>A strong DevOps engineer does not troubleshoot randomly.</p><p>The problem should be isolated systematically.</p><p>For an application deployed on EC2, the troubleshooting path can be:</p><p>Client<br> ↓<br>DNS / Endpoint<br> ↓<br>Internet / Routing<br> ↓<br>VPC<br> ↓<br>Security Group<br> ↓<br>EC2 Instance<br> ↓<br>Operating System<br> ↓<br>Service<br> ↓<br>Listening Port<br> ↓<br>Application</p><p>For SSH:</p><p>Client<br> ↓<br>Public IP<br> ↓<br>Network<br> ↓<br>Security Group TCP/22<br> ↓<br>EC2<br> ↓<br>SSH Service<br> ↓<br>Username<br> ↓<br>Private Key</p><p>For HTTP:</p><p>Browser / curl<br> ↓<br>Public IP<br> ↓<br>Security Group TCP/80<br> ↓<br>EC2<br> ↓<br>Apache<br> ↓<br>Port 80<br> ↓<br>Web Content</p><p>This layered approach reduces troubleshooting time because it converts a vague failure into a sequence of testable hypotheses.</p><p>— -</p><p>18.5 Security Groups Are Part of the Application’s Connectivity Design</p><p>A Security Group is not simply another AWS resource that needs to exist.</p><p>It directly determines whether required network flows can occur.</p><p>In this project, two important traffic paths were:</p><p>Administrator → EC2 : TCP/22<br>Client → EC2 : TCP/80</p><p>Therefore, both infrastructure and application validation depended on the correct Security Group rules.</p><p>This reinforces an important DevOps principle:</p><p>«Application availability depends on both the application and the network path required to reach it.»</p><p>— -</p><p>18.6 Public IP Addresses Should Not Be Treated as Permanent Application Identities</p><p>During the project, the EC2 public IP changed after the instance lifecycle changed.</p><p>That provided an important practical lesson.</p><p>An EC2 public IP used for temporary validation is not necessarily a stable application endpoint.</p><p>For production, application access should generally be abstracted behind appropriate services such as:</p><p>- Application Load Balancer<br>- Route 53<br>- Elastic IP where appropriate<br>- CloudFront<br>- private DNS/service discovery</p><p>The objective is to prevent application consumers from depending directly on the lifecycle of an individual EC2 instance.</p><p>— -</p><p>18.7 Provisioners Are Useful, but They Have Operational Trade-Offs</p><p>Terraform provisioners were deliberately used in this project because they provided an excellent way to demonstrate:</p><p>- post-provisioning automation<br>- SSH connectivity<br>- file transfer<br>- remote command execution<br>- local automation<br>- dependency between infrastructure and configuration</p><p>However, the project also demonstrated why provisioners require caution.</p><p>The deployment depended on:</p><p>EC2<br> ↓<br>Network<br> ↓<br>SSH<br> ↓<br>Authentication<br> ↓<br>Provisioner<br> ↓<br>Application Configuration</p><p>Any failure in that chain can interrupt the deployment.</p><p>For production environments, alternatives such as user data, cloud-init, AWS Systems Manager, Packer, configuration management, containers, or immutable infrastructure may provide a more resilient approach depending on the workload.</p><p>The lesson is not:</p><p>«”Never use provisioners.”»</p><p>The better lesson is:</p><p>«Understand their limitations and select the configuration mechanism appropriate for the operational requirements.»</p><p>— -</p><p>18.8 State Is Operationally Important</p><p>Terraform state should not be treated as an unimportant local file.</p><p>It provides Terraform with information about resources it manages and enables Terraform to determine how infrastructure should be reconciled.</p><p>During this project, state was used to inspect managed resources:</p><p>terraform state list</p><p>The result included:</p><p>aws_instance.app_server<br>aws_security_group.app_server</p><p>State therefore became part of the troubleshooting and lifecycle-management process.</p><p>In a team or production environment, remote state, access control, encryption, locking, versioning, and recovery mechanisms become important operational requirements.</p><p>— -</p><p>18.9 Replacement Should Be Intentional</p><p>Infrastructure replacement can be destructive.</p><p>Therefore, an engineer should understand why Terraform wants to replace a resource before allowing the operation to proceed.</p><p>This project used:</p><p>terraform apply -replace=aws_instance.app_server</p><p>This provided a controlled mechanism for replacing the EC2 instance when required.</p><p>The important lesson is:</p><p>«Resource replacement is an infrastructure operation that should be understood, reviewed, and intentionally executed.»</p><p>This is particularly important for resources that contain application data or support production workloads.</p><p>— -</p><p>18.10 Validation Must Continue Beyond “terraform apply”</p><p>A successful command such as:</p><p>Apply complete! Resources: 1 added, 0 changed, 1 destroyed.</p><p>is an important milestone, but it is not the final validation.</p><p>The infrastructure still needs to be tested.</p><p>In this project, validation included:</p><p>Terraform Apply<br> ↓<br>Terraform Outputs<br> ↓<br>SSH Connectivity<br> ↓<br>Apache Service Status<br> ↓<br>HTTP Connectivity<br> ↓<br>curl<br> ↓<br>Browser</p><p>This represents a progression from infrastructure-level validation to application-level validation.</p><p>The final question should not simply be:</p><p>«”Did Terraform finish?”»</p><p>It should be:</p><p>«”Does the deployed system perform the function it was designed to perform?”»</p><p>— -</p><p>18.11 Outputs Are an Operational Interface</p><p>Terraform outputs provide useful information to engineers and automation systems after deployment.</p><p>For this project, outputs exposed:</p><p>instance_public_ip<br>instance_private_ip</p><p>This is preferable to manually searching through the AWS console whenever deployment information is required.</p><p>Outputs can also become integration points for larger infrastructure designs.</p><p>For example:</p><p>Terraform Module<br> ↓<br>Outputs<br> ↓<br>Load Balancer / DNS / Monitoring / Automation</p><p>This makes outputs part of the infrastructure interface rather than merely convenient terminal information.</p><p>— -</p><p>18.12 Cost Optimization Starts During Architecture Design</p><p>Cost optimization should not be an activity performed only after receiving an AWS bill.</p><p>The project provided several practical examples:</p><p>- selecting an appropriate EC2 instance size<br>- avoiding unnecessary infrastructure<br>- destroying temporary resources<br>- considering S3 Gateway VPC Endpoints<br>- avoiding unnecessary NAT Gateway processing<br>- using architecture appropriate to workload requirements</p><p>The broader lesson is:</p><p>«Cost is an architectural constraint, not simply an accounting concern.»</p><p>A technically functional architecture can still be poorly engineered if it introduces unnecessary operational or network costs.</p><p>— -</p><p>18.13 Security and Cost Must Be Considered Together</p><p>Security and cost decisions often interact.</p><p>For example, network architecture affects:</p><p>- security boundaries<br>- traffic paths<br>- operational complexity<br>- data transfer<br>- NAT Gateway usage<br>- VPC endpoint requirements</p><p>Similarly, public accessibility affects both:</p><p>- attack surface<br>- architecture<br>- operational requirements</p><p>A senior DevOps approach therefore evaluates:</p><p>Security<br> +<br>Reliability<br> +<br>Performance<br> +<br>Operational Complexity<br> +<br>Cost</p><p>rather than optimizing one dimension in isolation.</p><p>— -</p><p>18.14 Documentation Is Part of Engineering</p><p>A production-quality implementation is not complete simply because the code works.</p><p>Other engineers need to understand:</p><p>- what was built<br>- why it was built<br>- how it works<br>- how it is deployed<br>- how it is validated<br>- what failed<br>- how failures were resolved<br>- what limitations exist<br>- how the architecture could evolve</p><p>That is why this project documents both successful implementation and real troubleshooting.</p><p>Documenting only the successful final state would hide valuable engineering knowledge.</p><p>The troubleshooting journey is part of the technical story.</p><p>— -</p><p>18.15 A Strong Portfolio Should Demonstrate Engineering Judgment</p><p>A portfolio project should not attempt to appear artificially perfect.</p><p>Real infrastructure work includes:</p><p>- incorrect assumptions<br>- configuration mistakes<br>- connectivity failures<br>- resource replacement<br>- state reconciliation<br>- debugging<br>- validation<br>- design trade-offs</p><p>The professional value comes from demonstrating how those problems were handled.</p><p>This project therefore demonstrates more than:</p><p>terraform apply</p><p>It demonstrates:</p><p>Understand<br> ↓<br>Design<br> ↓<br>Implement<br> ↓<br>Observe<br> ↓<br>Diagnose<br> ↓<br>Correct<br> ↓<br>Validate<br> ↓<br>Document<br> ↓<br>Improve</p><p>That workflow is much closer to real DevOps engineering.</p><p>— -</p><p>18.16 The Most Important Takeaway</p><p>The central lesson from this project is that Infrastructure as Code is an engineering discipline, not simply a configuration language.</p><p>Terraform provides the mechanism.</p><p>AWS provides the infrastructure platform.</p><p>But the engineer provides:</p><p>- architectural judgment<br>- security awareness<br>- troubleshooting ability<br>- lifecycle thinking<br>- cost awareness<br>- automation strategy<br>- validation discipline<br>- operational understanding</p><p>The progression demonstrated throughout this project can therefore be summarized as:</p><p>Terraform Code<br> ↓<br>Infrastructure<br> ↓<br>Configuration<br> ↓<br>Connectivity<br> ↓<br>Application<br> ↓<br>Validation<br> ↓<br>Troubleshooting<br> ↓<br>Reconciliation<br> ↓<br>Lifecycle Management<br> ↓<br>Production Evolution</p><p>That is the real DevOps lesson behind this project.</p><p>The objective is not merely to make infrastructure exist.</p><p>The objective is to make infrastructure repeatable, understandable, testable, secure, maintainable, and operationally useful.</p><p>19. Conclusion</p><p>Terraform becomes significantly more valuable when it is treated as an engineering discipline rather than simply a tool for creating AWS resources.</p><p>In this project, we built and managed a parameterized AWS infrastructure deployment using Terraform, provisioned an Ubuntu EC2 instance, configured Apache, established network access, validated the deployed application, investigated real deployment failures, reconciled Terraform state, performed controlled resource replacement, and ultimately destroyed the infrastructure cleanly.</p><p>The project followed the complete infrastructure lifecycle:</p><p>Define<br> ↓<br>Parameterize<br> ↓<br>Plan<br> ↓<br>Provision<br> ↓<br>Configure<br> ↓<br>Validate<br> ↓<br>Troubleshoot<br> ↓<br>Reconcile<br> ↓<br>Replace<br> ↓<br>Validate Again<br> ↓<br>Destroy</p><p>More importantly, the implementation demonstrated that successful DevOps engineering is not measured only by whether “terraform apply” completes successfully.</p><p>A production-minded engineer must also understand:</p><p>- how infrastructure components communicate<br>- how Terraform state represents managed resources<br>- how variables make infrastructure reusable<br>- how security groups control network access<br>- how provisioners depend on connectivity and readiness<br>- how to troubleshoot failures systematically<br>- how to validate infrastructure at multiple layers<br>- how resource replacement affects the environment<br>- how public IP addresses behave across an EC2 lifecycle<br>- how security and cost considerations influence architecture<br>- how a working prototype can evolve toward production architecture</p><p>The real deployment experience reinforced one of the most important principles in DevOps:</p><p>«Infrastructure is not finished when it is created. Infrastructure is finished when it has been configured, validated, understood, and can be managed throughout its lifecycle.»</p><p>This project also demonstrates the value of documenting real engineering challenges rather than presenting an artificial “perfect deployment.”</p><p>The AMI architecture mismatch, SSH connectivity timeout, private-key path issue, key-pair configuration, public IP changes, HTTP connectivity troubleshooting, resource replacement, and final validation all provided practical lessons that are difficult to gain from Terraform syntax alone.</p><p>The implementation can now serve as a foundation for further evolution into a more production-oriented architecture using:</p><p>- remote Terraform state<br>- reusable modules<br>- private subnets<br>- IAM roles<br>- AWS Systems Manager<br>- Application Load Balancing<br>- Auto Scaling<br>- HTTPS/TLS<br>- CloudWatch observability<br>- CI/CD automation<br>- security scanning<br>- stronger secrets management<br>- multi-environment deployment<br>- improved cost controls</p><p>The most important outcome is therefore not simply the EC2 instance that was created.</p><p>It is the engineering workflow developed around it:</p><p>Infrastructure as Code<br> ↓<br>Automation<br> ↓<br>Validation<br> ↓<br>Troubleshooting<br> ↓<br>Security<br> ↓<br>Cost Awareness<br> ↓<br>Lifecycle Management<br> ↓<br>Production Evolution</p><p>That is the foundation of effective AWS Cloud and DevOps engineering.</p><p>The complete Terraform implementation, configuration files, deployment structure, and supporting documentation are available in the GitHub repository:</p><p>GitHub:<br><a href="https://github.com/olajide-adedayo/terraform-parameterized-aws-infrastructure">https://github.com/olajide-adedayo/terraform-parameterized-aws-infrastructure</a></p><p>Final Takeaway</p><p>If you are learning Terraform, do not stop at:</p><p>terraform init<br>terraform plan<br>terraform apply</p><p>Go further.</p><p>Ask:</p><p>Why did Terraform create this resource?</p><p>How does the resource communicate with other components?</p><p>What happens when connectivity fails?</p><p>How do I prove that the application actually works?</p><p>What happens when the resource must be replaced?</p><p>How does Terraform reconcile its state?</p><p>How will this architecture behave in production?</p><p>How can I make it more secure, reliable, observable, scalable, and cost-effective?</p><p>Those questions move Terraform usage from basic infrastructure provisioning toward professional Infrastructure as Code and DevOps engineering.</p><p>And that is the real value of this project.</p><p>About the Author</p><p>Olajide Adedayo is an AWS Cloud and DevOps Engineer focused on cloud infrastructure, Infrastructure as Code (IaC), CI/CD, automation, containerization, and reliable AWS deployments.</p><p>He builds and documents hands-on cloud engineering solutions with an emphasis on automation, security, troubleshooting, scalability, cost awareness, and operational excellence.</p><p>His portfolio projects demonstrate practical implementation across AWS and DevOps technologies, including Terraform, Amazon EC2, Docker, Jenkins, Amazon ECR, networking, cloud infrastructure, and deployment automation.</p><p>Olajide is particularly interested in turning infrastructure requirements into repeatable, maintainable, and production-oriented engineering solutions, while documenting the reasoning, troubleshooting process, and operational lessons behind each implementation.</p><p>Connect with Olajide</p><p>LinkedIn:<br><a href="https://www.linkedin.com/in/olajideadedayo">https://www.linkedin.com/in/olajideadedayo</a></p><p>GitHub:<br><a href="https://github.com/olajide-adedayo">https://github.com/olajide-adedayo</a></p><p>Medium:<br><a href="https://medium.com/@olajideadedayo230">https://medium.com/@olajideadedayo230</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc5570edcedd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# Terraform Infrastructure as Code on AWS: Managing the Complete EC2 Lifecycle]]></title>
            <link>https://medium.com/@olajideadedayo230/terraform-infrastructure-as-code-on-aws-managing-the-complete-ec2-lifecycle-53ddf50d92a1?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ddf50d92a1</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 09:45:13 GMT</pubDate>
            <atom:updated>2026-08-23T09:46:50.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8-m2OlKV-H5lgtevwVHGw.jpeg" /></figure><p># Terraform Infrastructure as Code on AWS: Managing the Complete EC2 Lifecycle</p><p>From Infrastructure Provisioning to Drift Detection, State Reconciliation, Verification, and Controlled Cleanup</p><p>Managing cloud infrastructure effectively goes beyond creating resources and moving on. In a real-world Infrastructure as Code (IaC) workflow, engineers must be able to define infrastructure declaratively, preview changes, apply controlled modifications, detect configuration drift, reconcile infrastructure state, verify the actual cloud environment, and safely clean up resources when they are no longer required.</p><p>In this hands-on project, I implemented **Terraform-based Infrastructure as Code on Amazon Web Services (AWS)** to manage an Amazon EC2 environment and demonstrate its complete infrastructure lifecycle.</p><p>The project focuses on practical Terraform and AWS engineering concepts including:</p><p>- Terraform provider configuration<br>- Dynamic AWS AMI discovery<br>- Amazon EC2 provisioning<br>- AWS Security Group configuration<br>- Infrastructure planning and validation<br>- Controlled infrastructure changes<br>- Terraform resource replacement analysis<br>- Infrastructure drift detection<br>- Desired-state reconciliation<br>- Terraform state inspection<br>- EC2 operational state management<br>- AWS CLI and AWS Management Console verification<br>- Controlled infrastructure destruction<br>- Cloud cost awareness</p><p>Rather than treating Terraform as only a provisioning tool, this implementation explores how Infrastructure as Code can provide a **controlled, repeatable, and auditable approach to cloud infrastructure lifecycle management**.</p><p>Throughout this tutorial, I will walk through the engineering workflow, explain the reasoning behind the implementation, and provide evidence from the actual hands-on environment.</p><p>&gt; **Project focus:** Terraform Infrastructure as Code • AWS EC2 • Infrastructure Lifecycle Management • Drift Detection • State Reconciliation • Cloud Operations</p><p>— -</p><p>## Project Context and Business Objective</p><p>### Project Context</p><p>Cloud environments are highly dynamic. Infrastructure can be created, modified, replaced, stopped, started, or removed as application and operational requirements change.</p><p>Managing these changes manually through the AWS Management Console can become difficult to reproduce, audit, and maintain consistently.</p><p>**Infrastructure as Code (IaC)** addresses this challenge by allowing infrastructure to be defined as version-controlled configuration rather than relying entirely on manual cloud operations.</p><p>Terraform provides a declarative approach in which engineers describe the **desired state** of infrastructure and allow Terraform to determine the actions required to bring the actual environment into alignment with that configuration.</p><p>For this project, I used Terraform to manage an AWS EC2 environment and intentionally explored several stages of the infrastructure lifecycle rather than stopping after the initial deployment.</p><p>The implementation included:</p><p>- Defining AWS infrastructure as Terraform configuration<br>- Validating and formatting Terraform code<br>- Planning infrastructure changes before execution<br>- Provisioning AWS resources<br>- Verifying deployed resources independently<br>- Introducing controlled infrastructure changes<br>- Examining Terraform resource replacement behavior<br>- Demonstrating infrastructure drift<br>- Reconciling drift with the desired configuration<br>- Managing EC2 operational state through Terraform<br>- Inspecting Terraform-managed resources<br>- Performing final no-change validation<br>- Safely destroying temporary infrastructure</p><p>## Business Objective</p><p>The primary objective was to demonstrate how an Infrastructure as Code workflow can provide **consistency, visibility, control, and repeatability** when managing cloud infrastructure.</p><p>From an engineering and operational perspective, the project addresses several practical objectives:</p><p>### 1. Standardize Infrastructure Management</p><p>Define AWS infrastructure through version-controlled Terraform configuration instead of relying exclusively on manual provisioning.</p><p>### 2. Improve Change Visibility</p><p>Use `terraform plan` to preview infrastructure changes before they are applied, making potentially destructive or replacement operations visible in advance.</p><p>### 3. Detect Infrastructure Drift</p><p>Identify situations where the actual AWS environment differs from the infrastructure configuration managed through Terraform.</p><p>### 4. Reconcile Desired and Actual State</p><p>Use Terraform to restore infrastructure to the declared desired state after configuration differences are detected.</p><p>### 5. Manage Infrastructure Lifecycle</p><p>Demonstrate that cloud infrastructure should have a complete lifecycle covering:</p><p>**Define → Validate → Plan → Provision → Verify → Modify → Reconcile → Validate → Destroy**</p><p>### 6. Improve Operational Confidence</p><p>Combine Terraform output with independent verification through the **AWS CLI** and **AWS Management Console** rather than relying on a single source of information.</p><p>#### 7. Promote Cloud Cost Awareness</p><p>Treat infrastructure cleanup as part of the lifecycle by destroying temporary resources after the hands-on implementation was completed.</p><p>### Engineering Perspective</p><p>The key objective was therefore not simply to create an EC2 instance.</p><p>It was to demonstrate how Terraform can be used as an **infrastructure lifecycle management tool** that provides a controlled relationship between:</p><p>**Desired Configuration → Terraform State → Actual AWS Infrastructure**</p><p>This distinction is important when moving from basic cloud provisioning toward professional Infrastructure as Code and DevOps engineering practices.</p><p>— -</p><p>## Architecture and Technology Stack</p><p>Understanding the architecture before implementing the infrastructure makes it easier to see how Terraform interacts with AWS and how the different components fit together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkENJzHxP0p7DBc2j-PTrA.jpeg" /></figure><p>### Architecture Overview</p><p>The implementation uses **Terraform as the Infrastructure as Code control layer** between the local development environment and AWS.</p><p>The overall workflow can be represented as:</p><p>Local Development Environment<br> │<br> ▼<br> ┌─────────────────┐<br> │ Terraform │<br> │ Configuration │<br> └────────┬────────┘<br> │<br> ▼<br> ┌─────────────────┐<br> │ AWS Provider │<br> │ HashiCorp │<br> └────────┬────────┘<br> │<br> ┌────────┴────────┐<br> │ │<br> ▼ ▼<br> ┌──────────────┐ ┌─────────────────┐<br> │ AWS AMI Data │ │ AWS Security │<br> │ Source │ │ Group │<br> └──────┬───────┘ └────────┬────────┘<br> │ │<br> └─────────┬─────────┘<br> │<br> ▼<br> ┌───────────────┐<br> │ Amazon EC2 │<br> │ t3.micro │<br> └───────┬───────┘<br> │<br> ┌───────┴────────┐<br> │ │<br> ▼ ▼<br> ┌─────────────┐ ┌─────────────┐<br> │ AWS Console │ │ AWS CLI │<br> │ Verification│ │ Verification│<br> └─────────────┘ └─────────────┘</p><p>Terraform defines the desired infrastructure state, while AWS provides the actual cloud resources.</p><p>The AWS CLI and AWS Management Console provide independent mechanisms for verifying that the resulting AWS environment corresponds with the Terraform-managed configuration.</p><p>### Core Technology Stack</p><p>#### Terraform</p><p>**Terraform** is the primary Infrastructure as Code tool used in this project.</p><p>It provides the declarative configuration model used to define, plan, provision, modify, reconcile, and destroy the AWS infrastructure.</p><p>#### Amazon Web Services</p><p>**AWS** provides the cloud infrastructure platform on which the implementation is deployed.</p><p>The project uses the `us-east-1` AWS region.</p><p>#### Amazon EC2</p><p>**Amazon EC2** provides the compute infrastructure managed by Terraform.</p><p>The implementation uses a `t3.micro` instance for the hands-on lifecycle demonstration.</p><p>#### AWS Security Group</p><p>An AWS Security Group provides network-level access control for the EC2 instance.</p><p>The project demonstrates controlled access through:</p><p>- TCP port 22 for SSH<br>- TCP port 8080 for application access</p><p>SSH access is restricted to the configured source address using a `/32` CIDR range.</p><p>#### AWS AMI Data Source</p><p>Terraform uses an AWS AMI data source to dynamically discover the Ubuntu image used for the EC2 instance.</p><p>This avoids unnecessarily hardcoding an AMI identifier into the infrastructure configuration.</p><p>#### Terraform State</p><p>Terraform state maintains Terraform’s knowledge of the resources it manages and their relationship to the declared configuration.</p><p>State inspection becomes particularly important when working with infrastructure changes, drift detection, and reconciliation.</p><p>#### AWS CLI</p><p>The **AWS CLI** provides an independent method for verifying the actual AWS infrastructure.</p><p>Throughout the project, it was used to confirm resource configuration and operational state after Terraform operations.</p><p>#### AWS Management Console</p><p>The AWS Management Console provides a visual verification layer for inspecting the deployed infrastructure and confirming the resulting AWS resource state.</p><p>### Architecture Principle</p><p>The core engineering principle behind the implementation is:</p><p>**Declare the desired state → Plan the change → Apply the approved change → Verify the actual state → Reconcile differences when necessary.**</p><p>This creates a controlled feedback loop between Terraform configuration and the real AWS environment.</p><p>— -</p><p>## Preparing the Terraform Project</p><p>Before provisioning the AWS infrastructure, I prepared a dedicated Terraform working directory and configured the project to use Git for version control.</p><p>The project was developed locally using **Windows, Git Bash, Visual Studio Code, Terraform, and the AWS CLI**.</p><p>### Project Directory</p><p>The Terraform implementation was organized under a dedicated project directory:</p><p>terraform-ec2-lifecycle-management/</p><p>The project was intentionally kept focused on the EC2 lifecycle management objective rather than combining unrelated infrastructure components.</p><p>### Terraform Configuration</p><p>The implementation was separated into logical Terraform configuration files:</p><p>provider.tf<br> instance.tf<br> security_group.tf</p><p>This separation keeps the configuration readable and makes the responsibility of each component easier to understand.</p><p>### AWS Provider</p><p>The AWS provider was configured to target the `us-east-1` region:</p><p>provider “aws” {<br> region = “us-east-1”<br> }</p><p>The provider allows Terraform to communicate with the AWS APIs and manage the infrastructure defined in the configuration.</p><p>### Version Control</p><p>Git was initialized for the project so that infrastructure configuration and documentation changes could be tracked over time.</p><p>The repository was subsequently published to GitHub as part of the portfolio implementation.</p><p>The project also uses a `.gitignore` file to prevent generated Terraform state and local Terraform working files from being committed to source control.</p><p>### Terraform Provider Dependency</p><p>Terraform provider dependencies were initialized locally, and the provider lock file was retained in the repository.</p><p>The `.terraform.lock.hcl` file helps maintain consistent provider dependency selections when the project is initialized again.</p><p>### Initial Configuration Validation</p><p>Before proceeding with infrastructure provisioning, the Terraform configuration was formatted and validated.</p><p>The formatting workflow used:</p><p>terraform fmt</p><p>The validation workflow used:</p><p>terraform validate</p><p>These checks provided an early opportunity to identify configuration issues before Terraform interacted with the AWS environment.</p><p>### Implementation Evidence</p><p>The initial validation stage is supported by the following captured evidence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWq3NelVVJp3OVC8FF3NXQ.png" /><figcaption>Figure 1. Terraform configuration formatting and validation during the initial project preparation stage.*</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRXRPLQM_NWREaARs2sPCA.png" /><figcaption>*Figure 2. Final formatting validation confirming that the Terraform configuration was consistently formatted before infrastructure planning.*</figcaption></figure><p>### Engineering Practice</p><p>Formatting and validation before provisioning are simple but important Infrastructure as Code practices.</p><p>The objective is to identify configuration problems as early as possible, before they become infrastructure deployment problems.</p><p>The workflow therefore begins with:</p><p>Configure<br> ↓<br> Format<br> ↓<br> Validate<br> ↓<br> Plan<br> ↓<br> Apply</p><p>This creates a disciplined foundation for the remaining Terraform lifecycle demonstrated in the project.</p><p>— -</p><p>## Defining the AWS Infrastructure</p><p>With the Terraform project prepared and the configuration validated, the next step was to define the AWS resources that Terraform would manage.</p><p>The infrastructure was intentionally kept simple enough to understand clearly while still demonstrating several important Terraform capabilities.</p><p>The core resources were:</p><p>- An Ubuntu-based Amazon EC2 instance<br>- A dedicated AWS Security Group<br>- A dynamically discovered Ubuntu AMI<br>- Terraform-managed EC2 operational state</p><p>### Dynamic Ubuntu AMI Discovery</p><p>Rather than hardcoding an AMI ID directly into the EC2 resource, the configuration uses an AWS AMI data source to identify the appropriate Ubuntu image.</p><p>This approach is useful because AMI identifiers are region-specific and can change over time.</p><p>The data source allows Terraform to resolve the appropriate image before provisioning the EC2 instance.</p><p>### EC2 Instance Configuration</p><p>The EC2 instance was defined as Terraform-managed infrastructure using a `t3.micro` instance type.</p><p>The configuration associates the instance with:</p><p>- The dynamically discovered Ubuntu AMI<br>- The Terraform-managed SSH key pair<br>- The dedicated security group<br>- Appropriate project identification through resource tagging</p><p>This creates a reproducible definition of the compute infrastructure rather than relying on manual EC2 creation.</p><p>### Security Group Configuration</p><p>A dedicated AWS Security Group was created for the EC2 instance.</p><p>The security configuration demonstrates controlled inbound access through:</p><p>- **TCP port 22** for SSH administration<br>- **TCP port 8080** for application access</p><p>SSH access was restricted to the configured source address using a `/32` CIDR range.</p><p>This is preferable to unnecessarily exposing administrative access broadly to the internet.</p><p>### Terraform Resource Relationships</p><p>The infrastructure components are connected through Terraform dependencies.</p><p>The relationship can be summarized as:</p><p>AWS AMI Data Source<br> │<br> ▼<br> EC2 Instance<br> │<br> ├──────────────┐<br> │ │<br> ▼ ▼<br> Security Group SSH Key Pair<br> │<br> ▼<br> AWS Network Access</p><p>Terraform evaluates these relationships when creating the execution plan and determines the appropriate order in which resources should be managed.</p><p>### Planning Before Provisioning</p><p>After defining the infrastructure, the next step was to generate a Terraform execution plan.</p><p>The purpose of `terraform plan` is to preview what Terraform intends to change before modifying the AWS environment.</p><p>The initial plan identified the resources that Terraform intended to create:</p><p>Plan: 2 to add, 0 to change, 0 to destroy</p><p>This provided an opportunity to review the proposed infrastructure before proceeding with `terraform apply`.</p><p>### Implementation Evidence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ydp1iI_zw40xedaNarGAQ.png" /><figcaption>*Figure 3. Terraform execution plan showing the initial infrastructure resources scheduled for creation.*</figcaption></figure><p>The plan provided a controlled checkpoint between configuration and infrastructure provisioning.</p><p>Rather than immediately creating resources, the workflow was:</p><p>Terraform Configuration<br> ↓<br> terraform plan<br> ↓<br> Review Changes<br> ↓<br> terraform apply</p><p>This planning-first approach is an important Terraform practice because it makes infrastructure changes visible before they are executed.</p><p>— -</p><p>## Provisioning the EC2 Infrastructure</p><p>After reviewing the Terraform execution plan and confirming that the proposed changes were expected, the infrastructure was provisioned using Terraform.</p><p>### Applying the Configuration</p><p>The infrastructure was deployed with:</p><p>terraform apply</p><p>Terraform requested confirmation before proceeding with the planned changes.</p><p>After approval, Terraform created the defined AWS resources and reported a successful deployment.</p><p>The initial provisioning established the core infrastructure required for the lifecycle management demonstration.</p><p>### Deployment Result</p><p>The successful apply operation confirmed that Terraform was able to:</p><p>- Communicate with the AWS provider<br>- Resolve the required Ubuntu AMI<br>- Create the EC2 instance<br>- Create the required Security Group<br>- Establish the required resource relationships<br>- Record the resulting infrastructure in Terraform state</p><p>### Implementation Evidence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIm0eQYTlf_SGOJk37gmdw.png" /><figcaption>*Figure 4. Successful Terraform apply operation confirming that the initial AWS infrastructure was provisioned.*</figcaption></figure><p>The successful deployment represents the transition from **desired configuration** to **actual AWS infrastructure**.</p><p>The workflow at this stage was:</p><p>Terraform Configuration<br> ↓<br> terraform plan<br> ↓<br> Review Changes<br> ↓<br> terraform apply<br> ↓<br> AWS Infrastructure Created</p><p>However, a successful Terraform apply should not be treated as the final verification step.</p><p>The next stage was to independently confirm that the resources Terraform created actually existed in AWS and were in the expected operational state.</p><p>### Why Independent Verification Matters</p><p>Terraform provides authoritative information about the infrastructure it manages, but cloud engineers should also understand how to verify the actual environment independently.</p><p>For this project, verification was performed through both:</p><p>- AWS CLI<br>- AWS Management Console</p><p>This provides an additional layer of confidence that the infrastructure reported by Terraform corresponds to the resources actually present in AWS.</p><p>— -</p><p>## Verifying the Deployed AWS Infrastructure</p><p>After Terraform successfully provisioned the infrastructure, I independently verified the resulting AWS resources using both the **AWS CLI** and the **AWS Management Console**.</p><p>This additional verification step is important because Infrastructure as Code should be validated against the actual cloud environment, not only against Terraform’s execution output.</p><p>### Verification Using the AWS CLI</p><p>The AWS CLI was used to inspect the EC2 environment and confirm that the Terraform-managed instance had been created successfully.</p><p>The verification provided visibility into the actual AWS resource, including its instance identifier and operational state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWgtc3T3FoKSPK6W6Ly5PQ.png" /><figcaption>*Figure 5. AWS CLI verification of the EC2 infrastructure provisioned through Terraform.*</figcaption></figure><p>The CLI verification established an independent view of the AWS environment and confirmed that the EC2 instance created through Terraform was present in AWS.</p><p>### Verification Through the AWS Management Console</p><p>The AWS Management Console was then used as a second independent verification mechanism.</p><p>The EC2 console provided a visual representation of the deployed instance and its associated infrastructure configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-2h1O8ngN3A_yUjeDGdtg.png" /><figcaption>*Figure 6. AWS Management Console showing the EC2 infrastructure provisioned by Terraform.*</figcaption></figure><p>The console verification complemented the AWS CLI verification by providing a visual confirmation of the resource state.</p><p>### Why Use Multiple Verification Methods?</p><p>Using multiple verification mechanisms is a valuable operational practice.</p><p>The verification workflow was:</p><p>Terraform Apply<br> ↓<br> AWS Infrastructure<br> ↓<br> AWS CLI Verification<br> ↓<br> AWS Console Verification</p><p>This approach helps establish confidence that:</p><p>- The expected EC2 resource exists.<br>- The resource is visible through AWS APIs.<br>- The resource is visible through the AWS Management Console.<br>- The operational state reported by AWS corresponds with the Terraform deployment.<br>- The Terraform-managed infrastructure can be independently inspected.</p><p>### Infrastructure Verification Principle</p><p>A successful deployment is only one part of an Infrastructure as Code workflow.</p><p>A more complete engineering process is:</p><p>**Deploy → Verify → Observe → Validate**</p><p>Independent verification becomes even more important when infrastructure changes are introduced, because it provides a baseline against which subsequent Terraform plans can be compared.</p><p>With the initial infrastructure successfully provisioned and verified, the next stage was to introduce a **controlled infrastructure change** and observe how Terraform identified and managed the difference.<br> — -</p><p>## Introducing a Controlled Infrastructure Change</p><p>With the initial EC2 infrastructure provisioned and independently verified, the next stage was to modify the infrastructure through Terraform.</p><p>The purpose of this stage was to demonstrate how Terraform detects and manages a controlled change to an existing AWS resource.</p><p>### Changing the Infrastructure Configuration</p><p>Rather than making the change manually through the AWS Management Console, the desired configuration was modified in Terraform.</p><p>This is an important Infrastructure as Code principle:</p><p>&gt; Infrastructure managed by Terraform should, wherever practical, be changed through the Terraform configuration rather than through manual cloud-console operations.</p><p>After modifying the configuration, I ran:</p><p>terraform plan</p><p>Terraform compared the current state of the infrastructure with the updated desired configuration and generated a plan describing the required change.</p><p>### Reviewing the Proposed Change</p><p>The plan identified that Terraform could modify the existing infrastructure without creating an additional EC2 instance.</p><p>The execution plan therefore provided a controlled checkpoint before the change was applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ho0Mm9y155V7JjIyA3x-NA.png" /><figcaption>**Figure 7.** Terraform execution plan showing the proposed controlled infrastructure change before it was applied.</figcaption></figure><p>The plan demonstrated how Terraform makes infrastructure changes visible before execution.</p><p>Instead of making an immediate modification, the workflow remained:</p><p>Modify Configuration<br> ↓<br> terraform plan<br> ↓<br> Review Difference<br> ↓<br> terraform apply</p><p>### Applying the Controlled Change</p><p>After reviewing the proposed modification, the change was applied through Terraform.</p><p>terraform apply</p><p>Terraform executed the approved change against the AWS environment and updated its managed infrastructure accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPRpPx9K5-z-fIXmFgEOJg.png" /><figcaption>**Figure 8.** Successful Terraform apply operation implementing the approved infrastructure change.</figcaption></figure><p>The successful apply demonstrated that Terraform could manage an existing AWS resource through a controlled configuration change rather than requiring the infrastructure to be recreated unnecessarily.</p><p>### Independent Verification</p><p>After the Terraform change was applied, the AWS environment was independently inspected using the AWS CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UO-af7gfXDE5lzA13N7dJQ.png" /><figcaption>**Figure 9.** AWS CLI verification confirming the resulting security group configuration after the Terraform change.</figcaption></figure><p>This verification provided an independent confirmation that the intended security group change was reflected in the actual AWS environment.</p><p>### Engineering Significance</p><p>This stage demonstrates one of the core advantages of Infrastructure as Code:</p><p>**Configuration change → Planned difference → Controlled apply → Independent verification**</p><p>The workflow provides visibility before changes are executed and creates a repeatable method for modifying cloud infrastructure.</p><p>It also establishes an important distinction between **manual cloud administration** and **configuration-driven infrastructure management**.</p><p>The next stage explores what happens when a Terraform configuration change cannot be performed in place and Terraform determines that a resource must instead be replaced.</p><p>— -</p><p>## Understanding Terraform Resource Replacement</p><p>Not every infrastructure change can be performed in place.</p><p>One of the important behaviors demonstrated in this project was Terraform’s ability to identify when a configuration change requires an existing resource to be **replaced** rather than modified.</p><p>### What Is Resource Replacement?</p><p>When Terraform determines that a resource cannot safely be modified in place to satisfy the desired configuration, it can propose a replacement operation.</p><p>The general lifecycle becomes:</p><p>Existing Resource<br> ↓<br> Configuration Change<br> ↓<br> terraform plan<br> ↓<br> Replacement Required<br> ↓<br> Destroy Existing Resource<br> ↓<br> Create Replacement Resource</p><p>This behavior is important because resource replacement can have operational consequences, including temporary service interruption and changes to resource identifiers.</p><p>### Reviewing the Replacement Plan</p><p>To understand this behavior, the Terraform configuration was changed in a way that caused Terraform to determine that the existing resource could not simply be updated in place.</p><p>The resulting execution plan identified the replacement operation before any infrastructure change was performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Odr18mlQOQ2VNA3cVs4IpA.png" /><figcaption>**Figure 10.** Terraform execution plan identifying an EC2 resource replacement required to achieve the updated desired configuration.</figcaption></figure><p>The plan provided visibility into the proposed replacement and allowed the change to be reviewed before execution.</p><p>### Why the Plan Matters</p><p>This is one of the reasons `terraform plan` is such an important part of a professional Infrastructure as Code workflow.</p><p>Without reviewing the plan, an engineer could overlook the fact that an apparently simple configuration change might result in resource destruction and recreation.</p><p>A planning-first workflow therefore provides an important safety checkpoint:</p><p>Configuration Change<br> ↓<br> terraform plan<br> ↓<br> Identify Replacement<br> ↓<br> Assess Impact<br> ↓<br> Approve Change<br> ↓<br> terraform apply</p><p>### Production Considerations</p><p>Resource replacement should be treated carefully in production environments.</p><p>Before approving a replacement, engineers should consider:</p><p>- Whether the resource is stateful<br>- Whether downtime is acceptable<br>- Whether dependent resources will be affected<br>- Whether resource identifiers will change<br>- Whether data needs to be preserved<br>- Whether a migration or alternative deployment strategy is required</p><p>Depending on the workload, production architectures may use techniques such as blue/green deployments, immutable infrastructure patterns, load balancing, backups, or carefully designed migration strategies to reduce service disruption.</p><p>### Engineering Lesson</p><p>The key lesson from this stage is that Terraform’s declarative model does not mean every change is automatically non-disruptive.</p><p>Terraform tells the engineer **what it needs to do to achieve the desired state**.</p><p>The engineer must then understand the proposed actions and evaluate their operational impact before applying them.</p><p>This makes `terraform plan` more than a routine command — it becomes an important part of infrastructure change review and operational risk management.</p><p>— -</p><p>## Detecting Infrastructure Drift</p><p>One of the most important capabilities demonstrated in this project was **infrastructure drift detection**.</p><p>Infrastructure drift occurs when the actual state of a cloud resource changes independently of the Terraform configuration that is intended to manage it.</p><p>### What Is Infrastructure Drift?</p><p>Terraform operates around the concept of a desired state.</p><p>For example, Terraform configuration may describe how an EC2 resource or its associated infrastructure should be configured.</p><p>If someone subsequently changes that infrastructure directly through AWS — outside the Terraform workflow — the actual AWS environment can become different from the configuration Terraform expects.</p><p>This difference is known as **configuration drift**.</p><p>The relationship can be represented as:</p><p>Terraform Configuration<br> Desired State<br> │<br> │<br> ▼<br> Terraform State<br> │<br> │<br> ▼<br> Actual AWS State</p><p>When the actual AWS state changes independently:</p><p>Desired State ≠ Actual State</p><p>Terraform can identify that difference during planning.</p><p>### Demonstrating Drift</p><p>For this project, an infrastructure difference was deliberately introduced so that Terraform could detect the discrepancy between the declared configuration and the actual AWS environment.</p><p>The subsequent planning operation revealed that the real infrastructure no longer completely matched the Terraform-managed configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lx-rMidWbC1IWpa-i5iT9g.png" /><figcaption>**Figure 11.** Terraform execution plan detecting a difference between the declared infrastructure configuration and the actual AWS environment.</figcaption></figure><p>The plan demonstrated Terraform’s ability to detect a difference between the expected configuration and the infrastructure currently observed in AWS.</p><p>### Why Drift Matters</p><p>Infrastructure drift can become a significant operational problem in environments where cloud resources are managed by multiple engineers, automation systems, or manual console operations.</p><p>Uncontrolled drift can lead to:</p><p>- Configuration inconsistencies<br>- Unexpected infrastructure behavior<br>- Difficulty reproducing environments<br>- Security configuration differences<br>- Deployment surprises<br>- Increased troubleshooting complexity</p><p>For this reason, professional Infrastructure as Code workflows should minimize unmanaged manual changes and regularly identify configuration differences.</p><p>### Detecting Drift Before Making Changes</p><p>Terraform’s planning workflow provides an important mechanism for identifying drift before additional infrastructure changes are introduced.</p><p>The process can be summarized as:</p><p>Terraform Configuration<br> ↓<br> terraform plan<br> ↓<br> Compare States<br> ↓<br> Drift Detected<br> ↓<br> Review Difference<br> ↓<br> Reconciliation</p><p>This allows engineers to understand what has changed before deciding how the infrastructure should be brought back into alignment.</p><p>### Engineering Lesson</p><p>The key lesson is that Infrastructure as Code is not simply about provisioning resources.</p><p>A mature IaC workflow must also account for what happens **after deployment**.</p><p>Cloud infrastructure changes over time, and Terraform provides mechanisms for identifying when the actual environment no longer matches the desired configuration.</p><p>The next stage focuses on **reconciling the detected drift** and restoring the AWS environment to the desired Terraform-managed state.</p><p>— -</p><p>## Reconciling Infrastructure Drift</p><p>Detecting infrastructure drift is only the first step.</p><p>Once Terraform identifies a difference between the desired configuration and the actual AWS environment, the next objective is to determine the appropriate action and restore the infrastructure to the intended state.</p><p>### From Detection to Reconciliation</p><p>The drift detected in the previous stage was intentionally introduced to demonstrate Terraform’s reconciliation capability.</p><p>The workflow was:</p><p>Desired Configuration<br> ↓<br> Drift Detected<br> ↓<br> Review the Plan<br> ↓<br> Apply Reconciliation<br> ↓<br> Verify AWS State<br> ↓<br> Configuration Aligned</p><p>Rather than manually correcting the infrastructure through the AWS Management Console, Terraform was used to restore the resource to the configuration defined in code.</p><p>### Applying the Reconciliation</p><p>After reviewing the drift detection plan, the required Terraform operation was applied.</p><p>Terraform compared the desired configuration with the actual AWS environment and performed the necessary action to bring the infrastructure back into alignment.</p><p>The resulting AWS state was then independently verified using the AWS CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBr1mmnbQxQb-wLGfEOM1Q.png" /><figcaption>**Figure 12.** AWS CLI verification confirming the infrastructure state after Terraform reconciled the detected configuration drift.</figcaption></figure><p>The AWS CLI verification provided an independent confirmation that the infrastructure had been restored to the intended configuration.</p><p>### Why Reconciliation Matters</p><p>Drift detection without reconciliation would leave the infrastructure in an inconsistent state.</p><p>The value of Infrastructure as Code comes from maintaining a reliable relationship between:</p><p>**Configuration → State → Infrastructure**</p><p>When those three elements become inconsistent, Terraform can help identify the difference and determine the actions required to restore alignment.</p><p>### Preventing Long-Term Drift</p><p>Although Terraform can detect and reconcile drift, preventing unnecessary drift is preferable to repeatedly correcting it.</p><p>Professional teams can reduce drift by:</p><p>- Making infrastructure changes through version-controlled Terraform configuration<br>- Restricting unnecessary manual changes through the AWS Console<br>- Reviewing Terraform plans before applying changes<br>- Using CI/CD pipelines for infrastructure deployment<br>- Implementing appropriate IAM permissions<br>- Performing regular infrastructure validation<br>- Maintaining clear ownership of infrastructure resources</p><p>### Engineering Lesson</p><p>This stage demonstrates an important Infrastructure as Code principle:</p><p>&gt; **Infrastructure should be managed through a known and controlled source of truth.**</p><p>Terraform provides the mechanism for declaring that desired state, detecting differences, and reconciling the actual environment when necessary.</p><p>The project therefore moved beyond simple provisioning into a more realistic infrastructure lifecycle:</p><p>Provision<br> ↓<br> Change<br> ↓<br> Drift<br> ↓<br> Detect<br> ↓<br> Reconcile<br> ↓<br> Verify</p><p>This lifecycle is fundamental to maintaining consistent cloud infrastructure over time.</p><p>— -</p><p>## Managing EC2 Operational State with Terraform</p><p>Terraform can manage more than the initial creation of cloud resources. It can also represent certain operational requirements as part of the desired infrastructure configuration.</p><p>In this stage, the EC2 instance’s operational state was managed through Terraform.</p><p>### Defining the Desired EC2 State</p><p>The configuration was used to express the desired operational state of the EC2 instance.</p><p>The lifecycle was intentionally changed so that Terraform could detect the difference between the current AWS state and the state declared in the configuration.</p><p>This provided another practical demonstration of desired-state management.</p><p>### Planning the State Change</p><p>After the configuration was updated, Terraform was used to generate a new execution plan.</p><p>The plan identified the required change to the EC2 resource before any action was performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fBBg_hspwshFS-UJkSNTw.png" /><figcaption>**Figure 13.** Terraform execution plan identifying the required EC2 operational state change.</figcaption></figure><p>The plan demonstrated that Terraform had identified a difference between the desired EC2 operational state and the current infrastructure state.</p><p>### Inspecting Terraform-Managed Resources</p><p>Terraform state information was then inspected to understand which resources were currently under Terraform management.</p><p>The state inspection provided visibility into the resources Terraform was tracking and their associated infrastructure information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoAAB9mWv4Hl2RFhrbR13g.png" /><figcaption>**Figure 14.** Terraform state inspection showing the resources currently tracked within the infrastructure lifecycle.</figcaption></figure><p>Understanding Terraform state is important because Terraform uses this information to determine how the configuration relates to the infrastructure it manages.</p><p>### Applying the EC2 State Change</p><p>After reviewing the proposed change, the Terraform configuration was applied.</p><p>Terraform then performed the required EC2 state transition to bring the actual AWS environment into alignment with the declared configuration.</p><p>A subsequent Terraform plan was used to confirm that the desired and actual states were aligned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6cj6DRaPrF0N3T9oSDSUQ.png" /><figcaption>**Figure 15.** Terraform planning output showing the EC2 state reconciliation process after the configuration change.</figcaption></figure><p>The resulting plan demonstrated the reconciliation process and provided visibility into whether further changes were required.</p><p>### Independent AWS Verification</p><p>Terraform output was not treated as the only verification mechanism.</p><p>The EC2 instance was independently checked using the AWS CLI to confirm its actual operational state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VE1UKQSO79LKuU3naEnG8Q.png" /><figcaption>**Figure 16.** AWS CLI verification confirming the EC2 operational state after Terraform reconciliation.</figcaption></figure><p>This provided an independent confirmation that the EC2 operational state reported by AWS matched the desired state managed through Terraform.</p><p>### Final No-Change Validation</p><p>After the EC2 state had been reconciled, Terraform was executed again to confirm whether any additional infrastructure changes were required.</p><p>The final validation returned:</p><p>No changes. Your infrastructure matches the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PaXj8QPld8rqRwh8Dn8qQ.png" /><figcaption>**Figure 17.** Final Terraform plan confirming that no further infrastructure changes were required.</figcaption></figure><p>This is an important Terraform milestone because it indicates that Terraform no longer identified a difference requiring modification.</p><p>### Engineering Significance</p><p>This stage demonstrated the complete desired-state reconciliation workflow:</p><p>Desired Configuration<br> ↓<br> terraform plan<br> ↓<br> Difference Detected<br> ↓<br> terraform apply<br> ↓<br> AWS State Changed<br> ↓<br> Independent Verification<br> ↓<br> terraform plan<br> ↓<br> No Changes</p><p>The final **no-changes** result provides strong evidence that the Terraform configuration and the actual AWS infrastructure were aligned at that point in the lifecycle.</p><p>— -</p><p>## What This Project Demonstrates</p><p>The implementation demonstrates that Terraform can be used as more than a provisioning tool.</p><p>Throughout the project, Terraform was used to manage and observe the infrastructure across multiple stages of its lifecycle.</p><p>### 1. Declarative Infrastructure Management</p><p>The AWS infrastructure was represented as Terraform configuration rather than being created exclusively through manual AWS Console operations.</p><p>This provides a repeatable definition of the desired infrastructure state.</p><p>### 2. Controlled Infrastructure Changes</p><p>Changes were introduced through Terraform configuration and reviewed using `terraform plan` before being applied.</p><p>This creates visibility into infrastructure modifications before they affect the AWS environment.</p><p>### 3. Resource Replacement Awareness</p><p>The project demonstrated that some configuration changes may require Terraform to replace an existing resource.</p><p>Understanding replacement behavior is important because resource destruction and recreation can have operational consequences.</p><p>### 4. Infrastructure Drift Detection</p><p>The project intentionally demonstrated a difference between the declared configuration and the actual AWS environment.</p><p>Terraform detected this difference during planning, providing visibility into infrastructure drift.</p><p>### 5. State Reconciliation</p><p>After drift was identified, Terraform was used to reconcile the AWS environment with the desired configuration.</p><p>This demonstrates the practical value of desired-state management.</p><p>### 6. Operational State Management</p><p>Terraform was also used to manage the operational state of the EC2 instance.</p><p>This reinforced the idea that infrastructure lifecycle management can include operational requirements rather than focusing exclusively on initial resource creation.</p><p>### 7. Independent Infrastructure Verification</p><p>The project used multiple verification mechanisms:</p><p>- Terraform planning and state information<br>- AWS CLI<br>- AWS Management Console</p><p>Using independent verification methods improves confidence that the infrastructure reported by Terraform corresponds with the actual cloud environment.</p><p>### 8. Controlled Infrastructure Cleanup</p><p>After the implementation and verification activities were completed, the temporary infrastructure was deliberately destroyed.</p><p>This demonstrated that infrastructure lifecycle management includes not only provisioning and modification, but also responsible cleanup.</p><p>### The Complete Lifecycle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRTif0tdSgFFbv7OxCsbwg.jpeg" /></figure><p>The project can therefore be summarized as:</p><p>Define<br> ↓<br> Format<br> ↓<br> Validate<br> ↓<br> Plan<br> ↓<br> Provision<br> ↓<br> Verify<br> ↓<br> Modify<br> ↓<br> Detect Drift<br> ↓<br> Reconcile<br> ↓<br> Manage Operational State<br> ↓<br> Verify Again<br> ↓<br> Confirm No Changes<br> ↓<br> Destroy</p><p>The practical lesson is that effective Infrastructure as Code is not simply about creating infrastructure.</p><p>It is about maintaining a controlled relationship between **desired configuration, infrastructure state, and the actual cloud environment throughout the infrastructure lifecycle**.</p><p>— -</p><p>## Key Engineering Lessons</p><p>This hands-on implementation reinforced several principles that are important when working with Terraform and cloud infrastructure in professional environments.</p><p>### 1. Infrastructure as Code Is a Lifecycle Discipline</p><p>Terraform should not be viewed simply as a tool for creating cloud resources.</p><p>A mature Infrastructure as Code workflow considers the complete lifecycle:</p><p>**Provision → Change → Verify → Detect Drift → Reconcile → Maintain → Destroy**</p><p>This broader perspective helps engineers manage infrastructure consistently beyond the initial deployment.</p><p>### 2. Always Review the Terraform Plan</p><p>`terraform plan` provides an important safety mechanism.</p><p>Before applying infrastructure changes, engineers should understand:</p><p>- What Terraform intends to create<br>- What Terraform intends to modify<br>- What Terraform intends to destroy<br>- Whether a resource will be replaced<br>- Whether the proposed change is consistent with the intended outcome</p><p>A plan should therefore be treated as an infrastructure change-review checkpoint rather than simply another Terraform command.</p><p>### 3. Desired State and Actual State Can Diverge</p><p>Cloud infrastructure can change independently of Infrastructure as Code.</p><p>Manual AWS Console changes, automation, configuration changes, or other operational activities can introduce differences between the declared Terraform configuration and the actual AWS environment.</p><p>Understanding this distinction is essential for effective drift detection and reconciliation.</p><p>### 4. Terraform State Matters</p><p>Terraform state is a fundamental component of Terraform’s infrastructure management model.</p><p>It allows Terraform to maintain information about the resources it manages and use that information when determining what actions are required to reach the desired state.</p><p>For this reason, state should be:</p><p>- Protected<br>- Managed carefully<br>- Excluded from inappropriate source control<br>- Considered when troubleshooting infrastructure differences</p><p>### 5. Independent Verification Builds Confidence</p><p>A successful Terraform operation should not always be the final verification step.</p><p>In this project, AWS CLI and the AWS Management Console were used to independently inspect the infrastructure.</p><p>This created a useful verification pattern:</p><p>**Terraform → AWS → Independent Verification**</p><p>This approach is particularly valuable when troubleshooting unexpected infrastructure behavior.</p><p>### 6. Resource Replacement Requires Careful Review</p><p>Terraform may determine that a resource must be replaced rather than modified in place.</p><p>This can have operational consequences.</p><p>Before approving a replacement, an engineer should understand:</p><p>- What resource will be destroyed<br>- What resource will be created<br>- Whether service interruption is expected<br>- Whether dependent resources are affected<br>- Whether important state or data must be preserved</p><p>### 7. Drift Should Be Reconciled, Not Ignored</p><p>Detecting drift is useful, but leaving infrastructure in a permanently inconsistent state creates operational risk.</p><p>Once drift is identified, engineers should determine whether the configuration or the actual infrastructure represents the intended state and then take the appropriate controlled action.</p><p>### 8. Cleanup Is Part of Cloud Engineering</p><p>Infrastructure lifecycle management does not end when deployment succeeds.</p><p>Temporary environments should have a clear cleanup strategy.</p><p>In this project, the AWS resources were deliberately terminated after the hands-on implementation was completed.</p><p>This demonstrates both operational discipline and cloud cost awareness.</p><p>### 9. Small Projects Can Demonstrate Production-Oriented Thinking</p><p>Although this implementation used a relatively small EC2 environment, the engineering principles demonstrated are applicable to larger infrastructure environments.</p><p>The same concepts extend into production systems involving:</p><p>- Reusable Terraform modules<br>- Remote state<br>- Multiple environments<br>- CI/CD pipelines<br>- Infrastructure security scanning<br>- Policy enforcement<br>- Monitoring and observability<br>- Cost governance</p><p>The scale of the infrastructure may change, but the underlying Infrastructure as Code principles remain relevant.</p><p>### Final Engineering Takeaway</p><p>The most important lesson from this project is that Terraform provides value not merely by automating resource creation, but by introducing a **structured and declarative approach to infrastructure change management**.</p><p>The engineering mindset can be summarized as:</p><p>**Define clearly → Plan carefully → Apply deliberately → Verify independently → Reconcile differences → Clean up responsibly**</p><p>This approach provides a strong foundation for building reliable and maintainable cloud infrastructure.</p><p>— -</p><p>## Troubleshooting and Challenges</p><p>Hands-on cloud infrastructure work rarely proceeds without unexpected conditions. One of the valuable aspects of this implementation was the opportunity to distinguish between Terraform configuration problems and issues originating from the surrounding environment.</p><p>### AWS Connectivity and DNS Resolution</p><p>During the infrastructure cleanup stage, Terraform encountered an AWS provider connectivity error while attempting to communicate with the AWS STS endpoint.</p><p>The error indicated a DNS resolution problem:</p><p>Error: Retrieving AWS account details<br> validating provider credentials<br> operation error STS: GetCallerIdentity<br> dial tcp: lookup sts.us-east-1.amazonaws.com:<br> no such host</p><p>The important point was that the error did not immediately indicate an invalid Terraform configuration.</p><p>### Troubleshooting Approach</p><p>The issue was investigated by separating the possible causes into different categories:</p><p>- Terraform configuration<br>- AWS credentials<br>- AWS provider communication<br>- Local network connectivity<br>- DNS resolution</p><p>AWS CLI connectivity was subsequently checked to determine whether the local environment could communicate with AWS successfully.</p><p>Once connectivity was restored, Terraform was able to communicate with AWS normally.</p><p>### Successful Cleanup</p><p>After the connectivity issue was resolved, Terraform was able to generate the expected destruction plan:</p><p>Plan:<br> 0 to add<br> 0 to change<br> 3 to destroy</p><p>The temporary project infrastructure was then successfully destroyed.</p><p>### What This Demonstrates</p><p>The experience reinforced an important troubleshooting principle:</p><p>&gt; **Do not assume every Terraform error is a Terraform configuration problem.**</p><p>Terraform depends on several external components, including:</p><p>**Local Environment → Network → DNS → AWS APIs → Authentication → Terraform Provider**</p><p>A failure anywhere along that chain can affect Terraform operations.</p><p>### Terraform State Investigation</p><p>Terraform state was also inspected during the implementation to understand which resources were under Terraform management.</p><p>The `terraform state list` command provided visibility into the resources recorded by Terraform.</p><p>This is particularly useful when investigating:</p><p>- Unexpected resource changes<br>- Missing resources<br>- Drift<br>- Resource replacement<br>- Infrastructure cleanup</p><p>### Structured Troubleshooting Workflow</p><p>The project reinforced a systematic troubleshooting approach:</p><p>Read the Error<br> ↓<br> Identify the Failing Layer<br> ↓<br> Verify the Environment<br> ↓<br> Inspect Terraform State<br> ↓<br> Review terraform plan<br> ↓<br> Correct the Root Cause<br> ↓<br> Re-run the Operation<br> ↓<br> Independently Verify</p><p>This approach is more reliable than repeatedly changing Terraform configuration without first identifying the actual source of the problem.</p><p>### Engineering Lesson</p><p>Troubleshooting Infrastructure as Code requires understanding both the Terraform control plane and the cloud environment being managed.</p><p>A strong cloud engineer should therefore be comfortable investigating not only Terraform syntax and state, but also:</p><p>- AWS APIs<br>- Authentication<br>- DNS<br>- Network connectivity<br>- Resource state<br>- Cloud provider behavior<br>- Local development environments</p><p>The ability to isolate the failing layer is often more valuable than simply knowing the command that produced the error.</p><p>— -</p><p>## Security, Cost Management and Responsible Cleanup</p><p>Infrastructure engineering does not end when resources are successfully deployed.</p><p>A professional cloud workflow must also consider **security, operational control, cost management, and the eventual removal of temporary infrastructure**.</p><p>### Security Considerations</p><p>The EC2 environment used a dedicated AWS Security Group rather than relying on unrestricted network access.</p><p>The configuration demonstrated controlled inbound access for the services required by the project:</p><p>- **TCP 22** for SSH administration<br>- **TCP 8080** for application access</p><p>SSH access was restricted to the configured source address using a `/32` CIDR range.</p><p>This follows the principle of limiting administrative access rather than exposing SSH broadly to the internet.</p><p>### Infrastructure Change Control</p><p>Security is also connected to how infrastructure changes are introduced.</p><p>Terraform’s planning workflow was used to review proposed infrastructure changes before they were applied.</p><p>This provided visibility into:</p><p>- Resource modifications<br>- Resource replacement<br>- Resource creation<br>- Resource destruction</p><p>Reviewing these changes before execution reduces the risk of unintentionally introducing infrastructure or security changes.</p><p>### Terraform State Protection</p><p>Terraform state can contain important information about managed infrastructure and should be handled carefully.</p><p>For this project, Terraform state files were excluded from Git version control using `.gitignore`.</p><p>The repository excludes:</p><p>*.tfstate<br> *.tfstate.*<br> terraform.tfstate<br> terraform.tfstate.backup</p><p>This prevents local Terraform state from being accidentally committed to the public project repository.</p><p>Sensitive Terraform variable files were also excluded from source control.</p><p>For production environments, remote state management, encryption, access control, state locking, and appropriate secrets-management practices would be required.</p><p>### Cloud Cost Awareness</p><p>The project was created as a temporary hands-on learning and portfolio environment.</p><p>Leaving temporary AWS compute resources running after completing the implementation would create unnecessary costs.</p><p>For that reason, infrastructure cleanup was treated as part of the project lifecycle rather than as an optional final step.</p><p>### Responsible Infrastructure Cleanup</p><p>After the Terraform lifecycle demonstrations were completed, the temporary AWS resources were terminated.</p><p>The cleanup process ensured that the infrastructure created for the hands-on implementation did not remain active unnecessarily.</p><p>This demonstrates an important cloud engineering principle:</p><p>&gt; **Resources should have a defined lifecycle from creation through eventual decommissioning.**</p><p>### Production Considerations</p><p>A production implementation could extend these practices with:</p><p>- Least-privilege IAM policies<br>- Remote and encrypted Terraform state<br>- Secrets management<br>- Infrastructure security scanning<br>- Policy as Code<br>- Resource tagging standards<br>- AWS Budgets and cost alerts<br>- CloudWatch monitoring<br>- CloudTrail auditing<br>- Automated lifecycle policies</p><p>These capabilities were not implemented as part of this project, but they represent logical extensions for a production-grade Infrastructure as Code environment.</p><p>### Engineering Takeaway</p><p>Security, cost, and cleanup should not be treated as separate concerns that are addressed only after infrastructure has been deployed.</p><p>They should be considered throughout the lifecycle:</p><p>**Design → Provision → Change → Verify → Monitor → Reconcile → Decommission**</p><p>This mindset helps ensure that cloud infrastructure remains controlled, secure, observable, and cost-conscious.</p><p>— -</p><p>## Project Outcomes</p><p>The project successfully demonstrated a complete Terraform-managed AWS EC2 infrastructure lifecycle, from initial configuration and provisioning through controlled changes, drift detection, reconciliation, operational state management, independent verification, and final cleanup.</p><p>### Technical Outcomes</p><p>The implementation demonstrated practical ability to:</p><p>- Define AWS infrastructure using **Terraform Infrastructure as Code**<br>- Configure and use the **HashiCorp AWS provider**<br>- Dynamically discover an Ubuntu AMI<br>- Provision and manage an **Amazon EC2** instance<br>- Configure a dedicated **AWS Security Group**<br>- Preview infrastructure changes using `terraform plan`<br>- Apply controlled infrastructure modifications<br>- Identify potential resource replacement<br>- Detect infrastructure drift<br>- Reconcile differences between desired and actual infrastructure state<br>- Inspect Terraform-managed resources through Terraform state<br>- Manage EC2 operational state through Terraform<br>- Independently verify infrastructure using the **AWS CLI**<br>- Independently verify infrastructure using the **AWS Management Console**<br>- Confirm final infrastructure alignment using a no-change Terraform plan<br>- Safely destroy temporary AWS infrastructure after completing the implementation</p><p>### Infrastructure Lifecycle Demonstrated</p><p>The complete workflow can be summarized as:</p><p>**Define → Format → Validate → Plan → Provision → Verify → Modify → Detect Drift → Reconcile → Manage State → Verify → Confirm → Destroy**</p><p>This demonstrates that Infrastructure as Code can be used as an ongoing infrastructure management discipline rather than simply as a mechanism for initial resource creation.</p><p>### Evidence-Based Implementation</p><p>The tutorial is supported by **17 implementation screenshots**, documenting the major stages of the hands-on workflow.</p><p>The evidence covers:</p><p>- Terraform formatting and validation<br>- Infrastructure planning<br>- Successful provisioning<br>- AWS CLI verification<br>- AWS Console verification<br>- Controlled infrastructure changes<br>- Resource replacement planning<br>- Drift detection<br>- Drift reconciliation<br>- Terraform state management<br>- EC2 operational state management<br>- Final no-change validation</p><p>This evidence demonstrates that the project was implemented as a practical AWS and Terraform exercise rather than being limited to theoretical configuration examples.</p><p>### Professional Skills Demonstrated</p><p>From a Cloud and DevOps engineering perspective, the project demonstrates practical exposure to:</p><p>**Infrastructure as Code** <br>Designing and managing cloud infrastructure through declarative configuration.</p><p>**Cloud Infrastructure Management** <br>Provisioning and controlling AWS compute and networking resources.</p><p>**Infrastructure Change Management** <br>Reviewing and applying controlled infrastructure changes through Terraform.</p><p>**Drift Detection and Reconciliation** <br>Identifying differences between desired configuration and actual cloud infrastructure and restoring alignment.</p><p>**Infrastructure State Management** <br>Understanding how Terraform state supports resource tracking and lifecycle operations.</p><p>**Cloud Troubleshooting** <br>Investigating Terraform, AWS provider, connectivity, DNS, and infrastructure-state issues systematically.</p><p>**Cloud Cost Awareness** <br>Treating infrastructure cleanup as an essential part of the resource lifecycle.</p><p>### Overall Outcome</p><p>The project strengthened practical understanding of how Terraform can provide a controlled relationship between:</p><p>**Desired Configuration → Terraform State → Actual AWS Infrastructure**</p><p>More importantly, it demonstrated the engineering discipline required to manage infrastructure throughout its lifecycle rather than focusing solely on deployment.</p><p>— -</p><p>## Future Improvements</p><p>The current implementation focused on demonstrating Terraform-based EC2 lifecycle management in a controlled AWS environment.</p><p>A production-grade implementation could be extended with additional capabilities for scalability, collaboration, security, automation, observability, and governance.</p><p>### Remote Terraform State</p><p>A production environment should use a remote Terraform backend rather than relying on local state.</p><p>A possible AWS-based architecture would use:</p><p>- Amazon S3 for centralized Terraform state storage<br>- State locking appropriate to the Terraform/backend architecture<br>- Encryption at rest<br>- IAM-based access control</p><p>Remote state would make collaboration safer and provide a centralized source of Terraform state for a team.</p><p>### Reusable Terraform Modules</p><p>The configuration could be reorganized into reusable Terraform modules for components such as:</p><p>- EC2<br>- Security Groups<br>- Networking<br>- IAM<br>- Application infrastructure</p><p>Modules would improve consistency, maintainability, and reuse across multiple projects and environments.</p><p>### Multi-Environment Architecture</p><p>The project could be expanded to support separate:</p><p>- Development<br>- Staging<br>- Production</p><p>environments.</p><p>Environment-specific configuration and state management would allow infrastructure changes to be promoted through controlled environments.</p><p>### CI/CD Integration</p><p>Terraform could be integrated into a CI/CD platform such as:</p><p>- GitHub Actions<br>- GitLab CI/CD<br>- Jenkins<br>- AWS CodePipeline</p><p>A mature workflow could automatically perform:</p><p>terraform fmt<br> ↓<br> terraform validate<br> ↓<br> Security Checks<br> ↓<br> terraform plan<br> ↓<br> Code Review<br> ↓<br> terraform apply</p><p>This would introduce automated infrastructure validation and controlled deployment.</p><p>### Infrastructure Security Scanning</p><p>Infrastructure as Code security scanning could be introduced using tools such as:</p><p>- Checkov<br>- Trivy<br>- tfsec</p><p>These tools can identify potentially insecure Terraform configurations before infrastructure changes are deployed.</p><p>### Policy as Code</p><p>Policy enforcement could be introduced through technologies such as:</p><p>- Open Policy Agent<br>- HashiCorp Sentinel</p><p>This would allow organizations to enforce infrastructure policies before changes reach sensitive environments.</p><p>### Production-Grade Networking</p><p>The current project could evolve into a more complete AWS network architecture incorporating:</p><p>- Custom VPC<br>- Public and private subnets<br>- Route tables<br>- Internet Gateway<br>- NAT Gateway<br>- Network ACLs</p><p>This would provide stronger network segmentation and support more complex workloads.</p><p>### Monitoring and Observability</p><p>AWS monitoring capabilities could be integrated through services such as:</p><p>- Amazon CloudWatch<br>- CloudWatch Logs<br>- CloudWatch Alarms<br>- AWS CloudTrail</p><p>These services would provide greater visibility into infrastructure health, activity, and operational changes.</p><p>### Automated Cost Governance</p><p>Additional cost-management capabilities could include:</p><p>- Standardized resource tagging<br>- AWS Budgets<br>- Cost alerts<br>- Cost Explorer<br>- Automated shutdown schedules for non-production resources<br>- Resource lifecycle policies</p><p>These controls would help prevent unnecessary cloud expenditure.</p><p>### Advanced Deployment Strategies</p><p>For production workloads where resource replacement could cause service interruption, the architecture could be extended with deployment strategies such as:</p><p>- Blue/green deployments<br>- Immutable infrastructure<br>- Load balancing<br>- Auto Scaling<br>- Backup and recovery mechanisms</p><p>These approaches can reduce operational risk when infrastructure changes require resource replacement.</p><p>### Production Evolution</p><p>The project could therefore evolve from a focused Terraform EC2 lifecycle demonstration into a broader Infrastructure as Code platform:</p><p>Terraform Configuration<br> ↓<br> Reusable Modules<br> ↓<br> Remote State<br> ↓<br> CI/CD Pipeline<br> ↓<br> Security &amp; Policy<br> ↓<br> AWS Infrastructure<br> ↓<br> Monitoring &amp; Audit<br> ↓<br> Cost Governance</p><p>These are **future enhancements** and were not implemented as part of the current project.</p><p>The distinction is important: the current tutorial documents what was actually implemented, while this section identifies realistic directions for taking the architecture toward production-grade infrastructure management.</p><p>— -</p><p>## Conclusion</p><p>This project provided a practical demonstration of **Terraform Infrastructure as Code on AWS**, with a specific focus on managing the complete lifecycle of an Amazon EC2 environment.</p><p>Rather than stopping after provisioning an EC2 instance, the implementation explored the broader responsibilities involved in Infrastructure as Code:</p><p>**Define → Validate → Plan → Provision → Verify → Modify → Detect Drift → Reconcile → Manage State → Verify → Clean Up**</p><p>The project demonstrated how Terraform can provide visibility and control when infrastructure changes are introduced, while also showing why engineers must understand the difference between desired configuration, Terraform state, and the actual AWS environment.</p><p>Several important engineering practices were reinforced throughout the implementation:</p><p>- Reviewing infrastructure changes before applying them<br>- Understanding Terraform resource replacement behavior<br>- Detecting infrastructure drift<br>- Reconciling infrastructure with the desired configuration<br>- Inspecting Terraform-managed state<br>- Independently verifying AWS resources<br>- Troubleshooting infrastructure and connectivity issues systematically<br>- Managing temporary cloud resources responsibly<br>- Considering security and cloud cost throughout the infrastructure lifecycle</p><p>The hands-on evidence from the **17 captured implementation screenshots** also demonstrates that the project was implemented as a practical Terraform and AWS engineering exercise.</p><p>### Final Takeaway</p><p>The most important lesson from this project is that Infrastructure as Code is not simply about automating infrastructure creation.</p><p>It is about establishing a reliable engineering process for **defining, changing, verifying, reconciling, and eventually decommissioning cloud infrastructure in a controlled and repeatable manner**.</p><p>Terraform provides the declarative foundation, while effective Cloud and DevOps engineering requires the additional disciplines of change management, troubleshooting, security, verification, cost awareness, and operational responsibility.</p><p>This project represents one practical step toward applying those principles to real-world cloud infrastructure environments.</p><p>— -</p><p>## About the Author</p><p>*Olajide Adedayo* is an *AWS Cloud and DevOps Engineer* focused on cloud infrastructure, Infrastructure as Code, automation, CI/CD, containerization, and modern DevOps engineering practices.</p><p>His hands-on portfolio focuses on building and documenting practical cloud engineering solutions using technologies including *Amazon Web Services (AWS), Terraform, Docker, Jenkins, Git, GitHub, Linux, and CI/CD tooling*.</p><p>Through project-based learning and implementation, he develops practical expertise in areas such as:</p><p>- AWS Cloud Infrastructure</p><p>- Infrastructure as Code</p><p>- Terraform</p><p>- CI/CD Automation</p><p>- DevOps Engineering</p><p>- Cloud Security</p><p>- Containerization</p><p>- Infrastructure Automation</p><p>- Cloud Troubleshooting</p><p>- Monitoring and Operational Practices</p><p>He is particularly interested in designing *reliable, automated, scalable, and maintainable cloud infrastructure* while applying engineering principles that can translate into real-world production environments.</p><p>### Connect With Me</p><p>- *LinkedIn:* [Olajide Adedayo](https://www.linkedin.com/in/olajideadedayo/)</p><p>- *Medium:* [Olajide Adedayo](https://medium.com/@olajideadedayo230)</p><p>- *GitHub:* [olajide-adedayo](https://github.com/olajide-adedayo)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ddf50d92a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform and AWS: Automating EC2 Infrastructure with Infrastructure as Code]]></title>
            <link>https://medium.com/@olajideadedayo230/terraform-and-aws-automating-ec2-infrastructure-with-infrastructure-as-code-a2398bdf8293?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2398bdf8293</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 09:22:32 GMT</pubDate>
            <atom:updated>2026-08-15T09:22:32.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFWuD-TujNbmL3sFBGilCg.png" /></figure><p>Terraform and AWS: Automating EC2 Infrastructure with Infrastructure as Code</p><p>A hands-on guide to using Terraform to discover an Ubuntu AMI, provision an Amazon EC2 instance, configure security groups, manage Terraform state, and verify AWS infrastructure</p><p>Infrastructure as Code (IaC) has become a fundamental practice in modern DevOps and cloud engineering. Instead of manually creating and configuring cloud resources through a graphical console, engineers can define infrastructure in code, version it, review changes, and provision resources consistently.</p><p>In this tutorial, we will build an **AWS EC2 infrastructure environment using Terraform** from the ground up.</p><p>You will learn how to use Terraform to:</p><p>- Configure the AWS provider<br>- Discover an Ubuntu Amazon Machine Image (AMI) dynamically<br>- Create an AWS EC2 key pair<br>- Configure an EC2 security group<br>- Provision an Amazon EC2 instance<br>- Generate infrastructure outputs<br>- Initialize and validate a Terraform project<br>- Review infrastructure changes with `terraform plan`<br>- Provision infrastructure with `terraform apply`<br>- Inspect and manage Terraform state<br>- Verify deployed infrastructure using the AWS CLI and AWS Management Console<br>- Reconcile infrastructure using Terraform<br>- Manage the EC2 instance lifecycle<br>- Protect sensitive Terraform and SSH files from Git</p><p>The goal is not simply to run a few Terraform commands. By the end of this tutorial, you should understand **how the different Terraform components work together to manage AWS infrastructure through a repeatable Infrastructure as Code workflow**.</p><p>&gt; **Note:** This tutorial is based on a hands-on AWS and Terraform implementation. Commands, configuration examples, and verification steps are presented in the order required to reproduce the project.</p><p>What We’ll Build</p><p>In this tutorial, we will build and manage a small AWS compute environment using Terraform Infrastructure as Code (IaC).</p><p>The implementation focuses on provisioning an Amazon EC2 instance with the supporting configuration required to access and manage the instance securely.</p><p>TARGET ARCHITECTURE</p><p>The final environment will consist of the following components:</p><p>Terraform</p><p>Terraform will serve as the Infrastructure as Code engine responsible for defining, planning, provisioning, and managing the AWS infrastructure.</p><p>AWS Provider</p><p>The Terraform AWS provider will allow Terraform to communicate with AWS and manage the required resources.</p><p>Terraform Data Source</p><p>A Terraform data source will dynamically discover a suitable Ubuntu Amazon Machine Image (AMI) instead of relying solely on an unexplained hard-coded AMI identifier.</p><p>Amazon EC2</p><p>Terraform will provision an Amazon EC2 instance using the discovered Ubuntu AMI.</p><p>EC2 Key Pair</p><p>An AWS EC2 key pair will be configured to provide SSH authentication for administrative access to the instance.</p><p>Security Group</p><p>A security group will control inbound network traffic to the EC2 instance. The implementation will configure SSH access and HTTP access according to the project requirements.</p><p>Terraform State</p><p>Terraform will maintain local state information to track the resources it manages and determine whether the deployed infrastructure matches the declared configuration.</p><p>ARCHITECTURE WORKFLOW</p><p>The overall workflow will be:</p><p>Terraform Configuration → AWS Provider → AMI Discovery → EC2 Key Pair → Security Group → EC2 Instance → Terraform State → AWS Verification</p><p>The implementation will then use Terraform’s planning and reconciliation capabilities to verify that the deployed infrastructure remains aligned with the declared configuration.</p><p>WHAT YOU WILL ACCOMPLISH</p><p>By completing this tutorial, you will have built a working Terraform project capable of:</p><p>• Discovering an Ubuntu AMI dynamically<br>• Provisioning an Amazon EC2 instance<br>• Associating an EC2 key pair<br>• Applying security group rules<br>• Tracking infrastructure through Terraform state<br>• Validating Terraform configuration<br>• Reviewing infrastructure changes before deployment<br>• Provisioning infrastructure through Terraform<br>• Verifying the resulting AWS resources<br>• Managing the EC2 instance lifecycle</p><p>The objective is to understand not only how to provision the infrastructure, but also how to apply a disciplined Terraform workflow for configuration, validation, deployment, verification, state management, and lifecycle operations.</p><p>Prerequisites</p><p>Before starting the implementation, make sure the following tools, accounts, and permissions are available.</p><p>AWS Account</p><p>You need an active AWS account with permission to create and manage the AWS resources used in this tutorial.</p><p>The implementation uses Amazon EC2, security groups, EC2 key pairs, and related AWS services.</p><p>AWS Region</p><p>This tutorial uses the us-east-1 AWS Region.</p><p>Make sure your AWS CLI and Terraform configuration are working with the same region throughout the implementation.</p><p>Local Operating System</p><p>The implementation was performed from a Windows environment using PowerShell.</p><p>The commands and file-management examples in this tutorial can be adapted for Linux or macOS, but the shell syntax may differ.</p><p>Terraform</p><p>Install Terraform on your local machine.</p><p>Verify the installation with:</p><p>terraform version</p><p>The command should return the installed Terraform version.</p><p>AWS CLI</p><p>Install and configure the AWS Command Line Interface.</p><p>Verify the installation with:</p><p>aws — version</p><p>Then verify that the CLI can communicate with your AWS account:</p><p>aws sts get-caller-identity</p><p>A successful response should return information identifying the AWS account and the IAM identity being used.</p><p>Git</p><p>Git is recommended for version control and for maintaining the Terraform project in a GitHub repository.</p><p>Verify the installation with:</p><p>git — version</p><p>Code Editor</p><p>A code editor such as Visual Studio Code is recommended for creating and editing the Terraform configuration files.</p><p>Required AWS Permissions</p><p>The AWS identity used for this tutorial must have sufficient permissions to perform the required operations.</p><p>At minimum, the implementation requires permissions related to:</p><p>• Amazon EC2<br>• Security groups<br>• EC2 key pairs<br>• AMI discovery<br>• Describing AWS resources</p><p>For production environments, avoid using broad administrative permissions unnecessarily. Apply the principle of least privilege and grant only the permissions required for the intended Terraform operations.</p><p>SSH Key Consideration</p><p>The tutorial creates and uses an EC2 key pair for SSH authentication.</p><p>The private key must be treated as sensitive material.</p><p>Do not commit the private key to Git or upload it to a public repository.</p><p>Terraform Knowledge</p><p>Basic familiarity with Terraform is helpful, but this tutorial explains the important concepts and commands as they are introduced.</p><p>You should be comfortable working with a terminal, navigating directories, creating files, and executing commands.</p><p>IMPORTANT SECURITY NOTE</p><p>Never place AWS access keys, secret keys, passwords, private SSH keys, or other credentials directly inside Terraform configuration files or commit them to a public GitHub repository.</p><p>The objective of this tutorial is to demonstrate Infrastructure as Code while following sensible security practices from the beginning.</p><p>Project Architecture</p><p>Before writing the Terraform configuration, it is important to understand how the individual components fit together.</p><p>The project follows a simple Infrastructure as Code workflow in which Terraform defines the desired AWS infrastructure and AWS provides the underlying compute and networking resources.</p><p>ARCHITECTURE COMPONENTS</p><p>Terraform Configuration</p><p>The Terraform configuration defines the desired infrastructure using HashiCorp Configuration Language (HCL).</p><p>The configuration is divided into focused files so that each infrastructure responsibility can be understood and maintained independently.</p><p>AWS Provider</p><p>The AWS provider establishes the connection between Terraform and AWS.</p><p>Terraform uses the provider to authenticate with AWS and interact with AWS APIs.</p><p>AMI Data Source</p><p>The project uses a Terraform data source to discover an appropriate Ubuntu AMI.</p><p>This avoids depending on a manually selected AMI ID without first querying AWS for the required image characteristics.</p><p>EC2 Key Pair</p><p>The EC2 key pair provides the authentication mechanism required for SSH access to the Linux instance.</p><p>The private key remains on the local machine and is excluded from version control.</p><p>Security Group</p><p>The security group acts as a virtual firewall for the EC2 instance.</p><p>The project configures inbound rules for:</p><p>• SSH — TCP port 22<br>• HTTP — TCP port 80</p><p>SSH access is restricted to a specific source IP address, while HTTP is exposed publicly according to the requirements of this implementation.</p><p>Amazon EC2</p><p>The EC2 resource represents the compute infrastructure provisioned by Terraform.</p><p>Terraform uses the discovered AMI, selected instance configuration, key pair, and security group to create the instance.</p><p>Terraform State</p><p>Terraform records information about the managed infrastructure in its state.</p><p>The state allows Terraform to compare the declared configuration with the resources it manages and determine whether changes are required.</p><p>IMPLEMENTATION WORKFLOW</p><p>The complete workflow can be represented as:</p><p>Terraform Configuration<br> ↓<br>AWS Provider<br> ↓<br>AMI Data Source<br> ↓<br>EC2 Key Pair<br> ↓<br>Security Group<br> ↓<br>Amazon EC2<br> ↓<br>Terraform State<br> ↓<br>AWS CLI Verification<br> ↓<br>AWS Console Verification</p><p>DESIRED OUTCOME</p><p>At the end of the implementation, Terraform will have provisioned an EC2 instance with the required supporting configuration.</p><p>The infrastructure will then be independently verified using the AWS CLI and AWS Management Console.</p><p>This architecture deliberately keeps the implementation small enough to understand while demonstrating the core workflow used when managing cloud infrastructure through Terraform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47BiK4MQeylgCu3BbxDRSw.png" /></figure><p>Create the Terraform Project</p><p>With the prerequisites and architecture understood, we can now create the local Terraform project directory.</p><p>The objective of this step is to establish a clean working directory before creating the individual Terraform configuration files.</p><p>CREATE THE PROJECT DIRECTORY</p><p>Open PowerShell and create a directory for the project:</p><p>mkdir terraform-infrastructure-automation-aws</p><p>Move into the newly created directory:</p><p>cd terraform-infrastructure-automation-aws</p><p>Verify your current location:</p><p>Get-Location</p><p>You should see the path to the newly created project directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StmtJKVAU-vY-vXBVWeiXA.png" /><figcaption>Figure 1 — Terraform project structure showing the configuration files and supporting project files used throughout the implementation.</figcaption></figure><p>VERIFY THE PROJECT DIRECTORY</p><p>List the contents of the directory:</p><p>Get-ChildItem</p><p>At this stage, the directory should be empty or contain only files you intentionally created.</p><p>We will gradually add the Terraform configuration files throughout the tutorial.</p><p>PROJECT FILE STRUCTURE</p><p>By the end of the implementation, the main Terraform configuration will contain the following files:</p><p>provider.tf<br>instance.tf<br>instance-id.tf<br>keypair.tf<br>secgrp.tf<br>.gitignore</p><p>Terraform will also create some local working files and directories during execution, including:</p><p>.terraform/<br>.terraform.lock.hcl<br>terraform.tfstate<br>terraform.tfstate.backup</p><p>The .terraform directory and Terraform state files are generated as part of Terraform’s local workflow and should not be committed to a public Git repository.</p><p>The .terraform.lock.hcl file is different. It records provider dependency selections and should normally be committed to version control.</p><p>IMPORTANT</p><p>Do not create terraform.tfstate manually.</p><p>Terraform will generate the state file automatically after infrastructure operations are performed.</p><p>Similarly, do not manually create the .terraform directory. Terraform creates and manages this directory when you run terraform init.</p><p>NEXT STEP</p><p>The project directory is now ready.</p><p>In the next step, we will create provider.tf and configure Terraform to use the AWS provider and the us-east-1 AWS Region.</p><p>Configure the AWS Provider</p><p>Terraform needs a provider to communicate with AWS.</p><p>The AWS provider acts as the interface between Terraform and the AWS APIs. It allows Terraform to create, modify, inspect, and manage AWS resources defined in the Terraform configuration.</p><p>In this project, we will use the AWS provider and configure the deployment region as us-east-1.</p><p>CREATE provider.tf</p><p>From the project directory, create a file named:</p><p>provider.tf</p><p>In PowerShell, you can create the file with:</p><p>New-Item provider.tf -ItemType File</p><p>Open provider.tf in your code editor and add:</p><p>provider “aws” {<br> region = “us-east-1”<br>}</p><p>UNDERSTANDING THE CONFIGURATION</p><p>The provider block tells Terraform which infrastructure platform it will manage.</p><p>The provider name is:</p><p>aws</p><p>The region argument specifies the AWS Region in which Terraform will operate:</p><p>us-east-1</p><p>This is the N. Virginia AWS Region.</p><p>AUTHENTICATION</p><p>Notice that no AWS access key, secret key, or password has been placed inside provider.tf.</p><p>This is intentional.</p><p>Terraform can use the AWS authentication configuration already available to the AWS CLI or other supported AWS credential mechanisms.</p><p>Keeping credentials outside the Terraform source code reduces the risk of accidentally exposing sensitive authentication information through source control.</p><p>VERIFY THE FILE</p><p>Save provider.tf and run:</p><p>Get-Content provider.tf</p><p>You should see:</p><p>provider “aws” {<br> region = “us-east-1”<br>}</p><p>At this stage, Terraform has been told which provider and AWS Region to use, but the AWS provider has not yet been downloaded or initialized.</p><p>That happens in the next step.</p><p>NEXT STEP</p><p>We will create the Terraform data source that dynamically discovers the Ubuntu AMI that will be used by the EC2 instance.</p><p>Initialize Terraform</p><p>The Terraform configuration now contains an AWS provider definition. Before Terraform can use that provider, the working directory must be initialized.</p><p>Terraform initialization prepares the working directory, downloads the required provider plugins, and creates the local Terraform working environment.</p><p>RUN TERRAFORM INIT</p><p>From inside the project directory, run:</p><p>terraform init</p><p>Terraform will read the provider configuration in provider.tf and download the required AWS provider.</p><p>A successful initialization should end with a message similar to:</p><p>Terraform has been successfully initialized!</p><p>This means the working directory is ready for the next stages of the Terraform workflow.</p><p>WHAT TERRAFORM INIT CREATES</p><p>After successful initialization, Terraform creates a local directory:</p><p>.terraform/</p><p>This directory contains Terraform’s local working data, including the downloaded provider components.</p><p>Terraform also creates:</p><p>.terraform.lock.hcl</p><p>The dependency lock file records the selected provider version and related dependency information.</p><p>The lock file should normally be committed to version control because it helps maintain consistent provider dependency selections across environments.</p><p>VERIFY THE INITIALIZATION</p><p>Run:</p><p>Get-ChildItem</p><p>You should now see files and directories similar to:</p><p>.terraform<br>.terraform.lock.hcl<br>provider.tf</p><p>The exact directory contents may vary depending on the Terraform version and configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pI9CXR7erhgGldWMxC1-Qg.png" /><figcaption>Figure 2 — Successful Terraform initialization showing the AWS provider and Terraform working directory successfully initialized.</figcaption></figure><p>VERIFY THE AWS PROVIDER</p><p>You can also inspect the provider dependency recorded by Terraform with:</p><p>terraform providers</p><p>The output should show the AWS provider required by the root module.</p><p>IMPORTANT</p><p>Do not manually copy provider plugins into the project directory.</p><p>Terraform manages provider installation through terraform init.</p><p>Also, do not commit the .terraform directory to a public Git repository. It is generated local working data and should be excluded through .gitignore.</p><p>WHAT WE HAVE ACHIEVED</p><p>At this point:</p><p>• The Terraform project directory exists.<br>• The AWS provider is declared.<br>• Terraform has been initialized.<br>• The required provider has been downloaded.<br>• The provider dependency has been recorded in .terraform.lock.hcl.</p><p>The project is now ready for the infrastructure configuration itself.</p><p>In the next step, we will create a Terraform data source to dynamically discover an appropriate Ubuntu AMI for the EC2 instance.</p><p>Discover the Ubuntu AMI with a Terraform Data Source</p><p>An Amazon Machine Image (AMI) provides the operating system and initial software configuration used when launching an EC2 instance.</p><p>AMI IDs are specific to AWS Regions and can also change as new image versions are published. Hard-coding an AMI ID without understanding where it came from can therefore make infrastructure configuration less reusable.</p><p>Terraform data sources provide a better approach for retrieving information about existing AWS resources.</p><p>In this project, we will use the AWS AMI data source to dynamically identify the most recent matching Ubuntu AMI.</p><p>CREATE THE AMI DATA SOURCE</p><p>Create a new file named:</p><p>ami-lookup.tf</p><p>In PowerShell:</p><p>New-Item ami-lookup.tf -ItemType File</p><p>Open ami-lookup.tf and add:</p><p>data “aws_ami” “ubuntu” {<br> most_recent = true</p><p>owners = [“099720109477”]</p><p>filter {<br> name = “name”<br> values = [“ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*”]<br> }</p><p>filter {<br> name = “virtualization-type”<br> values = [“hvm”]<br> }</p><p>filter {<br> name = “root-device-type”<br> values = [“ebs”]<br> }<br>}</p><p>UNDERSTANDING THE CONFIGURATION</p><p>The data block tells Terraform that we want to retrieve information about an existing AWS resource rather than create a new one.</p><p>The data source type is:</p><p>aws_ami</p><p>The local Terraform name is:</p><p>ubuntu</p><p>Together, these form:</p><p>data.aws_ami.ubuntu</p><p>MOST_RECENT</p><p>The setting:</p><p>most_recent = true</p><p>instructs Terraform to select the most recent AMI that matches the specified filters.</p><p>This allows the configuration to discover a newer matching image rather than depending on a single manually selected AMI ID.</p><p>UBUNTU OWNER ID</p><p>The configuration contains:</p><p>owners = [“099720109477”]</p><p>This is the AWS account ID associated with the official Ubuntu images published by Canonical.</p><p>It is NOT your personal AWS account number.</p><p>The owner filter helps ensure that Terraform selects an AMI published by the expected Ubuntu image owner.</p><p>AMI NAME FILTER</p><p>The following filter:</p><p>name = “ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*”</p><p>limits the search to the expected Ubuntu 24.04 Noble image naming pattern.</p><p>The wildcard allows Terraform to match the specific version suffix published for the image.</p><p>VIRTUALIZATION TYPE</p><p>The configuration requires:</p><p>virtualization-type = “hvm”</p><p>HVM stands for Hardware Virtual Machine and represents the virtualization type expected for the selected image.</p><p>ROOT DEVICE TYPE</p><p>The configuration also requires:</p><p>root-device-type = “ebs”</p><p>This limits the results to AMIs using Amazon EBS as the root device.</p><p>VERIFY THE DATA SOURCE</p><p>Format the Terraform configuration:</p><p>terraform fmt</p><p>Then validate the configuration:</p><p>terraform validate</p><p>You should receive:</p><p>Success! The configuration is valid.</p><p>Next, run:</p><p>terraform plan</p><p>Terraform should evaluate the AMI data source and identify a matching Ubuntu AMI.</p><p>You can also inspect the data source after Terraform has evaluated it by running:</p><p>terraform console</p><p>Then enter:</p><p>data.aws_ami.ubuntu.id</p><p>Terraform should return the AMI ID selected by the data source.</p><p>Exit the Terraform console with:</p><p>exit</p><p>IMPORTANT REGIONAL CONSIDERATION</p><p>The AMI lookup is performed within the AWS Region configured in provider.tf:</p><p>us-east-1</p><p>AMI availability is regional, so the same AMI ID should not be assumed to exist in every AWS Region.</p><p>If you change the AWS Region, the data source should be evaluated again to identify an appropriate AMI available in that Region.</p><p>WHAT WE HAVE ACHIEVED</p><p>The project can now dynamically discover an appropriate Ubuntu AMI instead of relying on an unexplained hard-coded AMI ID.</p><p>This makes the EC2 configuration more maintainable and demonstrates one of the important differences between Terraform resources and data sources.</p><p>In the next step, we will create the EC2 key pair that Terraform will associate with the instance.</p><p>Create the EC2 SSH Key Pair</p><p>The EC2 instance will require an SSH authentication mechanism for administrative access.</p><p>AWS EC2 key pairs use a public key and private key combination. The public key is registered with AWS, while the private key remains on the administrator’s local machine.</p><p>For this project, we will generate an SSH key pair locally and use Terraform to register the public key with AWS.</p><p>IMPORTANT SECURITY REQUIREMENT</p><p>The private key is sensitive.</p><p>Never commit the private key to GitHub, share it publicly, or include it in screenshots.</p><p>The public key can be used by Terraform to create the AWS EC2 key pair, but the private key must remain protected on your local machine.</p><p>GENERATE THE SSH KEY PAIR</p><p>From inside the Terraform project directory, run:</p><p>ssh-keygen -t ed25519 -f dove-key</p><p>When prompted for a passphrase, you may configure one according to your security requirements.</p><p>The command creates two files:</p><p>dove-key<br>dove-key.pub</p><p>The file:</p><p>dove-key</p><p>is the private key.</p><p>The file:</p><p>dove-key.pub</p><p>is the public key.</p><p>VERIFY THE FILES</p><p>Run:</p><p>Get-ChildItem dove-key*</p><p>You should see:</p><p>dove-key<br>dove-key.pub</p><p>Do not open or publish the private key unnecessarily.</p><p>CREATE keypair.tf</p><p>Create a new Terraform configuration file:</p><p>New-Item keypair.tf -ItemType File</p><p>Open keypair.tf and add:</p><p>resource “aws_key_pair” “dove_key” {<br> key_name = “dove-key”<br> public_key = file(“${path.module}/dove-key.pub”)<br>}</p><p>UNDERSTANDING THE CONFIGURATION</p><p>The resource type:</p><p>aws_key_pair</p><p>instructs Terraform to manage an EC2 key pair in AWS.</p><p>The Terraform resource name:</p><p>dove_key</p><p>is an internal Terraform identifier used to reference this resource from other Terraform configuration files.</p><p>The AWS key pair name is:</p><p>dove-key</p><p>The public_key argument reads the public key from:</p><p>dove-key.pub</p><p>The expression:</p><p>${path.module}</p><p>refers to the directory containing the current Terraform module.</p><p>Therefore:</p><p>file(“${path.module}/dove-key.pub”)</p><p>allows Terraform to read the public key from the project directory.</p><p>VERIFY THE CONFIGURATION</p><p>Format the configuration:</p><p>terraform fmt</p><p>Then validate it:</p><p>terraform validate</p><p>You should receive:</p><p>Success! The configuration is valid.</p><p>IMPORTANT: PROTECT THE PRIVATE KEY</p><p>Before committing this project to Git, make sure the private key is excluded from version control.</p><p>The following entries should be present in .gitignore:</p><p>dove-key<br>dove-key.pub</p><p>For this project, both key files are excluded from the public repository because the key material is part of the local implementation environment.</p><p>Although the public key is not secret in the same way as the private key, excluding both files keeps the local key-pair material out of the repository and ensures that the tutorial does not encourage publishing authentication artifacts.</p><p>WHAT WE HAVE ACHIEVED</p><p>We have generated an SSH key pair and created a Terraform resource that registers the public key with AWS.</p><p>Terraform will later associate this key pair with the EC2 instance.</p><p>The private key remains on the local machine and will be used when SSH access to the instance is required.</p><p>In the next step, we will create the security group that controls network access to the EC2 instance.</p><p>Create the EC2 Security Group</p><p>A security group acts as a virtual firewall for an Amazon EC2 instance.</p><p>It controls which inbound and outbound network traffic is permitted. Rather than exposing every port, we should define only the network access required by the workload.</p><p>For this project, the security group will allow:</p><ul><li>SSH access on TCP port 22 from a specific public IP address<br>• HTTP access on TCP port 80 from the internet.</li></ul><p>This provides restricted administrative access while allowing public HTTP traffic.</p><p>CREATE secgrp.tf</p><p>Create a new Terraform configuration file:</p><p>New-Item secgrp.tf -ItemType File</p><p>Open secgrp.tf and add:</p><p>resource “aws_security_group” “dove_sg” {<br> name = “dove-sg-224”<br> description = “Security group for Terraform EC2 instance”</p><p>ingress {<br> description = “SSH access”<br> from_port = 22<br> to_port = 22<br> protocol = “tcp”<br> cidr_blocks = [“YOUR_PUBLIC_IP/32”]<br> }</p><p>ingress {<br> description = “HTTP access”<br> from_port = 80<br> to_port = 80<br> protocol = “tcp”<br> cidr_blocks = [“0.0.0.0/0”]<br> }</p><p>egress {<br> from_port = 0<br> to_port = 0<br> protocol = “-1”<br> cidr_blocks = [“0.0.0.0/0”]<br> }</p><p>tags = {<br> Name = “dove-sg-224”<br> }<br>}</p><p>IMPORTANT: REPLACE YOUR_PUBLIC_IP</p><p>The following value:</p><p>YOUR_PUBLIC_IP/32</p><p>is a placeholder.</p><p>Replace it with the public IPv4 address from which you will connect to the EC2 instance.</p><p>For example:</p><p>203.0.113.25/32</p><p>Do not use the example address above unless it is actually your public IP address.</p><p>You can determine your current public IP address using a trusted IP-checking service or your organization’s approved network tools.</p><p>The /32 suffix means that only that single IPv4 address is permitted to connect through the SSH rule.</p><p>UNDERSTANDING THE SSH RULE</p><p>The SSH rule allows TCP traffic on port 22.</p><p>Port 22 is commonly used for SSH administration of Linux servers.</p><p>Restricting the source to:</p><p>YOUR_PUBLIC_IP/32</p><p>is significantly safer than:</p><p>0.0.0.0/0</p><p>because it does not expose SSH to every IPv4 address on the internet.</p><p>UNDERSTANDING THE HTTP RULE</p><p>The HTTP rule allows TCP traffic on port 80 from:</p><p>0.0.0.0/0</p><p>This means HTTP traffic can originate from any IPv4 address on the internet.</p><p>This is appropriate for a publicly accessible web service, but in a production environment the rule should be reviewed according to the application’s actual networking requirements.</p><p>UNDERSTANDING THE EGRESS RULE</p><p>The egress rule permits outbound IPv4 traffic.</p><p>The protocol:</p><p>-1</p><p>represents all protocols.</p><p>This configuration allows the EC2 instance to initiate outbound connections.</p><p>FORMAT AND VALIDATE</p><p>Format the Terraform configuration:</p><p>terraform fmt</p><p>Then validate the configuration:</p><p>terraform validate</p><p>You should receive:</p><p>Success! The configuration is valid.</p><p>REVIEW THE SECURITY GROUP</p><p>Run:</p><p>terraform plan</p><p>Terraform should identify the security group configuration that will be created.</p><p>At this stage, the security group is defined in Terraform but has not yet been created in AWS.</p><p>IMPORTANT SECURITY CONSIDERATION</p><p>Do not expose SSH to the entire internet unless there is a specific operational requirement.</p><p>Avoid using:</p><p>cidr_blocks = [“0.0.0.0/0”]</p><p>for SSH access in a normal administrative environment.</p><p>Restrict administrative ports to trusted source networks whenever practical.</p><p>WHAT WE HAVE ACHIEVED</p><p>The Terraform configuration now defines the network access policy for the EC2 instance.</p><p>The security group will:</p><p>• Allow restricted SSH access on TCP port 22<br>• Allow public HTTP access on TCP port 80<br>• Allow outbound IPv4 traffic<br>• Be managed as Infrastructure as Code</p><p>In the next step, we will create the Amazon EC2 resource and connect the AMI, key pair, and security group configurations together.</p><p>Provision the Amazon EC2 Instance</p><p>The core compute resource for this project is an Amazon EC2 instance.</p><p>At this point, the Terraform project already contains the components required by the instance:</p><p>• An AWS provider<br>• A dynamically discovered Ubuntu AMI<br>• An EC2 key pair<br>• A security group</p><p>The next step is to connect these components through an aws_instance resource.</p><p>CREATE instance.tf</p><p>Create a new Terraform configuration file:</p><p>New-Item instance.tf -ItemType File</p><p>Open instance.tf and add:</p><p>resource “aws_instance” “dove” {<br> ami = data.aws_ami.ubuntu.id<br> instance_type = “t3.micro”<br> key_name = aws_key_pair.dove_key.key_name<br> vpc_security_group_ids = [aws_security_group.dove_sg.id]</p><p>tags = {<br> Name = “dove”<br> }<br>}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42u1DKKPkLolGaaFSQPheQ.png" /><figcaption>Figure 7 — Terraform Amazon EC2 resource configuration connecting the dynamically discovered AMI, key pair, and security group.</figcaption></figure><p>UNDERSTANDING THE EC2 RESOURCE</p><p>The resource declaration:</p><p>resource “aws_instance” “dove”</p><p>tells Terraform to manage an Amazon EC2 instance.</p><p>The AMI is obtained dynamically from the data source created earlier:</p><p>ami = data.aws_ami.ubuntu.id</p><p>This means the EC2 instance uses the Ubuntu AMI selected by the Terraform data source rather than requiring an AMI ID to be manually entered into the instance configuration.</p><p>INSTANCE TYPE</p><p>The configuration uses:</p><p>instance_type = “t3.micro”</p><p>This specifies the EC2 instance type used for the project.</p><p>The appropriate instance type for a production workload should be selected according to workload requirements, performance requirements, availability, and cost considerations.</p><p>KEY PAIR ASSOCIATION</p><p>The EC2 instance references the Terraform-managed key pair:</p><p>key_name = aws_key_pair.dove_key.key_name</p><p>This associates the AWS key pair with the instance and enables SSH authentication using the corresponding private key.</p><p>SECURITY GROUP ASSOCIATION</p><p>The instance references the security group created earlier:</p><p>vpc_security_group_ids = [aws_security_group.dove_sg.id]</p><p>This associates the EC2 instance with the security group and therefore applies the network access rules defined in secgrp.tf.</p><p>RESOURCE TAGGING</p><p>The instance is assigned the tag:</p><p>Name = “dove”</p><p>Tags make AWS resources easier to identify, organize, manage, and monitor.</p><p>FORMAT THE CONFIGURATION</p><p>Run:</p><p>terraform fmt</p><p>Terraform should format the configuration according to its standard formatting conventions.</p><p>VALIDATE THE CONFIGURATION</p><p>Run:</p><p>terraform validate</p><p>You should receive:</p><p>Success! The configuration is valid.</p><p>REVIEW THE COMPLETE INFRASTRUCTURE PLAN</p><p>Now run:</p><p>terraform plan</p><p>Terraform should evaluate the complete configuration and identify the resources that need to be created.</p><p>At this stage, Terraform should be able to evaluate the relationships between:</p><p>AMI Data Source<br> ↓<br>EC2 Key Pair<br> ↓<br>Security Group<br> ↓<br>EC2 Instance</p><p>Do not proceed directly to terraform apply without reviewing the plan.</p><p>The plan is an important safety checkpoint because it allows you to inspect the infrastructure changes Terraform intends to make before those changes are executed against AWS.</p><p>WHAT WE HAVE ACHIEVED</p><p>The Terraform configuration now defines the EC2 compute resource and connects it to the dynamically discovered Ubuntu AMI, EC2 key pair, and security group.</p><p>The project now contains the core infrastructure required for provisioning the AWS environment.</p><p>In the next step, we will create an output that exposes the EC2 instance ID after Terraform provisions the infrastructure.</p><p>Create a Terraform Output for the EC2 Instance ID</p><p>Terraform outputs provide a convenient way to expose useful information about infrastructure managed by Terraform.</p><p>For this project, we will create an output that displays the Amazon EC2 instance ID after the instance has been provisioned.</p><p>This makes it easier to identify the deployed instance from the Terraform command line without manually searching through the AWS Management Console.</p><p>CREATE instance-id.tf</p><p>Create a new Terraform configuration file:</p><p>New-Item instance-id.tf -ItemType File</p><p>Open instance-id.tf and add:</p><p>output “instance_id” {<br> description = “ID of the EC2 instance”<br> value = aws_instance.dove.id<br>}</p><p>UNDERSTANDING THE OUTPUT</p><p>The output block creates a Terraform output named:</p><p>instance_id</p><p>The description documents what the output represents:</p><p>description = “ID of the EC2 instance”</p><p>The value:</p><p>aws_instance.dove.id</p><p>references the ID generated by AWS for the EC2 instance managed by the Terraform resource:</p><p>aws_instance.dove</p><p>Terraform will populate this value after the EC2 instance has been created.</p><p>FORMAT THE CONFIGURATION</p><p>Run:</p><p>terraform fmt</p><p>Terraform should format the configuration according to its standard formatting conventions.</p><p>VALIDATE THE CONFIGURATION</p><p>Run:</p><p>terraform validate</p><p>You should receive:</p><p>Success! The configuration is valid.</p><p>REVIEW THE OUTPUT DURING PLANNING</p><p>Run:</p><p>terraform plan</p><p>The plan should include the output definition.</p><p>However, the actual EC2 instance ID will not be known until the instance has been created.</p><p>After the infrastructure is provisioned, run:</p><p>terraform output</p><p>You should see an output similar to:</p><p>instance_id = “i-xxxxxxxxxxxxxxxxx”</p><p>The exact instance ID will be different for every AWS account and deployment.</p><p>You can also retrieve only the value with:</p><p>terraform output -raw instance_id</p><p>This is useful when the output needs to be passed into another command or script.</p><p>WHY OUTPUTS ARE USEFUL</p><p>Terraform outputs can expose important infrastructure information such as:</p><p>• EC2 instance IDs<br>• Public IP addresses<br>• Private IP addresses<br>• Load balancer DNS names<br>• Resource ARNs<br>• Other values required by users or downstream automation</p><p>Outputs are particularly useful when Terraform becomes part of a larger automation or CI/CD workflow.</p><p>WHAT WE HAVE ACHIEVED</p><p>The Terraform configuration can now expose the EC2 instance ID after deployment.</p><p>The project has now defined:</p><p>• The AWS provider<br>• The Ubuntu AMI data source<br>• The EC2 key pair<br>• The security group<br>• The EC2 instance<br>• The EC2 instance ID output</p><p>Before provisioning the infrastructure, we should protect local Terraform artifacts and SSH key material from being committed to the Git repository.</p><p>In the next step, we will configure the project’s .gitignore file.</p><p>Configure .gitignore for Terraform and SSH Files</p><p>Before committing the Terraform project to Git, it is important to identify files that should remain local.</p><p>Terraform generates local working data and state files during execution. The project also contains SSH key material that must not be published to a public repository.</p><p>A properly configured .gitignore helps prevent these files from being accidentally committed.</p><p>CREATE .gitignore</p><p>From the project directory, create the file:</p><p>New-Item .gitignore -ItemType File</p><p>Open .gitignore and add:</p><p># Terraform working directory<br>.terraform/</p><p># Terraform state files<br>*.tfstate<br>*.tfstate.*<br>crash.log<br>crash.*.log</p><p># Terraform variable files<br>*.tfvars<br>*.tfvars.json</p><p># Sensitive local files<br>*.pem<br>dove-key<br>dove-key.pub</p><p># Terraform override files<br>override.tf<br>override.tf.json<br>*_override.tf<br>*_override.tf.json</p><p># Local environment files<br>.env</p><p>UNDERSTANDING THE ENTRIES</p><p>Terraform Working Directory</p><p>.terraform/</p><p>Terraform creates the .terraform directory when terraform init is executed.</p><p>It contains local Terraform working data and provider-related files and should not normally be committed.</p><p>Terraform State</p><p>*.tfstate<br>*.tfstate.*</p><p>Terraform state can contain information about managed infrastructure and, depending on the configuration, potentially sensitive values.</p><p>For this project, local state files are therefore excluded from version control.</p><p>Terraform Variable Files</p><p>*.tfvars<br>*.tfvars.json</p><p>Variable files can contain environment-specific configuration and, in some implementations, sensitive values.</p><p>They should not be committed unless their contents are explicitly reviewed and safe for version control.</p><p>SSH Private Key</p><p>dove-key</p><p>The private SSH key must never be committed to a public repository.</p><p>It should remain protected on the local machine.</p><p>SSH Public Key</p><p>dove-key.pub</p><p>The public key is not confidential in the same way as the private key, but this project excludes it as well so that the complete local key-pair material remains outside the public repository.</p><p>Terraform Crash Logs</p><p>crash.log<br>crash.*.log</p><p>These entries prevent Terraform crash logs from being accidentally committed.</p><p>Override Files</p><p>Terraform override files can change configuration behavior locally and are therefore excluded unless there is an intentional reason to version them.</p><p>VERIFY .gitignore</p><p>Run:</p><p>Get-Content .gitignore</p><p>Review the output and confirm that the required entries are present.</p><p>Then check the Git working tree:</p><p>git status</p><p>The local Terraform working directory and ignored files should not appear as untracked files.</p><p>IMPORTANT SECURITY CHECK</p><p>Before publishing the repository, confirm that no private key, AWS credential, Terraform state file, or other sensitive artifact is being tracked by Git.</p><p>You can check ignored files with:</p><p>git status — ignored</p><p>Review the result carefully.</p><p>A .gitignore file is a safeguard, not a substitute for reviewing files before committing them.</p><p>WHAT WE HAVE ACHIEVED</p><p>The project now has a basic protection layer against accidentally committing:</p><p>• Terraform working data<br>• Terraform state files<br>• Sensitive variable files<br>• SSH private key material<br>• Local environment files<br>• Terraform crash logs<br>• Local override files</p><p>The Terraform configuration is now ready for the validation and planning workflow.</p><p>In the next step, we will format and validate the complete Terraform configuration before making any infrastructure changes.</p><p>Validate the Complete Terraform Configuration</p><p>Before provisioning any AWS resources, the Terraform configuration should be formatted and validated.</p><p>This is an important engineering checkpoint. Validation allows configuration errors to be identified before Terraform attempts to create or modify infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnF4zlrME-GG3-XJEi_hEQ.png" /><figcaption>Figure 3 — Successful Terraform configuration validation confirming that the infrastructure code is syntactically and structurally valid.</figcaption></figure><p>FORMAT THE TERRAFORM CONFIGURATION</p><p>From the project directory, run:</p><p>terraform fmt</p><p>Terraform will format the Terraform configuration files using its standard formatting rules.</p><p>To see which files were changed by formatting, run:</p><p>terraform fmt -check</p><p>If all files are already correctly formatted, Terraform will return without listing any files.</p><p>You can also run:</p><p>terraform fmt -recursive</p><p>This formats Terraform configuration files within the current directory and its subdirectories.</p><p>VALIDATE THE CONFIGURATION</p><p>Run:</p><p>terraform validate</p><p>A successful validation should return:</p><p>Success! The configuration is valid.</p><p>This confirms that Terraform can parse the configuration and that the configuration is internally consistent enough to proceed to the planning stage.</p><p>IMPORTANT DISTINCTION</p><p>terraform validate does not create AWS resources.</p><p>It checks the Terraform configuration itself.</p><p>Similarly, terraform fmt does not provision infrastructure.</p><p>It only formats Terraform configuration files.</p><p>REVIEW THE PROJECT FILES</p><p>At this stage, your project should contain the following Terraform configuration files:</p><p>provider.tf<br>ami-lookup.tf<br>keypair.tf<br>secgrp.tf<br>instance.tf<br>instance-id.tf<br>.gitignore</p><p>You can verify the files with:</p><p>Get-ChildItem</p><p>You should also see the Terraform provider dependency lock file:</p><p>.terraform.lock.hcl</p><p>The .terraform directory will also exist because Terraform was previously initialized.</p><p>VERIFY THE TERRAFORM PROVIDERS</p><p>Run:</p><p>terraform providers</p><p>The output should show the AWS provider required by the root module.</p><p>This confirms that the project configuration has a dependency on the HashiCorp AWS provider.</p><p>CHECK THE GIT WORKING TREE</p><p>If the project is under Git version control, run:</p><p>git status</p><p>Confirm that sensitive local files such as:</p><p>dove-key<br>dove-key.pub<br>.terraform/<br>terraform.tfstate</p><p>are not being presented as files that should be committed.</p><p>WHAT WE HAVE ACHIEVED</p><p>The Terraform configuration has now been:</p><p>• Formatted using Terraform’s standard formatting rules<br>• Parsed and validated<br>• Checked for provider dependencies<br>• Reviewed for expected project files<br>• Checked for unwanted sensitive files before infrastructure deployment</p><p>No AWS infrastructure has been created by these commands.</p><p>The next step is one of the most important stages in the Terraform workflow: generating and reviewing the execution plan before applying any changes.</p><p>Review the Terraform Execution Plan</p><p>The Terraform configuration has been formatted and validated successfully.</p><p>Before creating any AWS infrastructure, we need to generate an execution plan.</p><p>The Terraform plan is a critical control point because it shows what Terraform intends to create, modify, or destroy before those changes are applied.</p><p>RUN TERRAFORM PLAN</p><p>From the project directory, run:</p><p>terraform plan</p><p>Terraform will evaluate the configuration, query the AWS API for the required AMI information, compare the desired configuration with the current Terraform state, and calculate the proposed infrastructure changes.</p><p>Because this is the first deployment, Terraform should identify the resources that need to be created.</p><p>EXPECTED RESOURCE CHANGES</p><p>The plan should identify resources corresponding to the configuration created in the previous steps, including:</p><p>• AWS key pair<br>• AWS security group<br>• Amazon EC2 instance</p><p>The AMI data source is used to retrieve information about an existing AMI. It is not itself an AWS resource that Terraform creates.</p><p>The exact plan output may differ depending on your AWS account, Region, AMI availability, and current infrastructure state.</p><p>UNDERSTANDING THE PLAN SYMBOLS</p><p>Terraform uses symbols to describe planned actions.</p><p>A plus sign:</p><p>+</p><p>indicates that a resource will be created.</p><p>A minus sign:</p><p>-</p><p>indicates that a resource will be destroyed.</p><p>A combined symbol:</p><p>-/+</p><p>indicates that Terraform will destroy and recreate a resource because it cannot safely update it in place.</p><p>An arrow:</p><p>~</p><p>indicates that a resource will be modified in place.</p><p>These symbols allow engineers to review infrastructure changes before execution.</p><p>REVIEW THE PLAN CAREFULLY</p><p>Do not approve or apply a Terraform plan simply because Terraform generated it successfully.</p><p>Review the proposed changes and confirm that:</p><p>• The expected AWS Region is being used.<br>• The expected EC2 instance type is shown.<br>• The expected security group is being created.<br>• SSH access is restricted to the intended source IP address.<br>• HTTP access is configured as intended.<br>• The expected key pair is associated with the instance.<br>• No unexpected resources are being created.<br>• No existing resources are being modified or destroyed unintentionally.</p><p>PLAN WITHOUT APPLYING</p><p>The command:</p><p>terraform plan</p><p>only creates and displays the proposed execution plan.</p><p>It does not create the EC2 instance.</p><p>It does not create the security group.</p><p>It does not create the AWS key pair.</p><p>This separation between planning and execution is one of Terraform’s important safety features.</p><p>OPTIONAL: SAVE THE PLAN</p><p>For controlled workflows, Terraform can save a generated plan to a file:</p><p>terraform plan -out=tfplan</p><p>The saved plan can then be reviewed or applied later:</p><p>terraform apply tfplan</p><p>For this tutorial, the important concept is understanding that the plan represents the proposed infrastructure changes before they are executed.</p><p>WHAT WE HAVE ACHIEVED</p><p>Terraform has now evaluated the complete infrastructure configuration and generated a proposed execution plan.</p><p>We have reached the final review point before provisioning the AWS resources.</p><p>Only after reviewing the plan and confirming that the proposed changes are correct should we proceed to terraform apply.</p><p>In the next step, we will provision the AWS infrastructure.</p><p>Provision the AWS Infrastructure</p><p>The Terraform configuration has been formatted, validated, and reviewed through terraform plan.</p><p>We are now ready to provision the infrastructure.</p><p>This is the point at which Terraform will communicate with AWS and create the resources defined in the configuration.</p><p>RUN TERRAFORM APPLY</p><p>From the project directory, run:</p><p>terraform apply</p><p>Terraform will generate a new execution plan and ask for confirmation before making changes.</p><p>Review the proposed resources carefully.</p><p>When prompted:</p><p>Enter a value:</p><p>type:</p><p>yes</p><p>and press Enter.</p><p>Terraform will then begin creating the AWS infrastructure.</p><p>EXPECTED RESOURCES</p><p>The implementation should provision the following managed resources:</p><p>• AWS EC2 key pair<br>• AWS security group<br>• Amazon EC2 instance</p><p>Terraform will also evaluate the Ubuntu AMI data source to identify the AMI used by the EC2 instance.</p><p>The exact creation times and resource identifiers will vary.</p><p>MONITOR THE APPLY OPERATION</p><p>During execution, Terraform displays the progress of each resource.</p><p>You may see messages similar to:</p><p>aws_key_pair.dove_key: Creating…<br>aws_security_group.dove_sg: Creating…<br>aws_instance.dove: Creating…</p><p>After successful creation, Terraform should report that the resources were created.</p><p>The final output should include the EC2 instance ID because we defined the instance_id output earlier.</p><p>VERIFY THE TERRAFORM OUTPUT</p><p>Run:</p><p>terraform output</p><p>You should see something similar to:</p><p>instance_id = “i-xxxxxxxxxxxxxxxxx”</p><p>The actual instance ID will be different in your AWS environment.</p><p>You can retrieve only the instance ID with:</p><p>terraform output -raw instance_id</p><p>VERIFY THE TERRAFORM STATE</p><p>Run:</p><p>terraform state list</p><p>The output should show the Terraform-managed resources.</p><p>You should see entries similar to:</p><p>data.aws_ami.ubuntu<br>aws_key_pair.dove_key<br>aws_security_group.dove_sg<br>aws_instance.dove</p><p>The exact output depends on the final Terraform configuration and the resources successfully created.</p><p>IMPORTANT: APPLY IS A REAL INFRASTRUCTURE OPERATION</p><p>Unlike:</p><p>terraform fmt<br>terraform validate<br>terraform plan</p><p>terraform apply makes actual changes to AWS.</p><p>The command may create resources that incur AWS charges.</p><p>Always review the execution plan before approving an apply operation.</p><p>WHAT WE HAVE ACHIEVED</p><p>Terraform has now transitioned from configuration and planning into actual infrastructure provisioning.</p><p>The AWS environment defined in the Terraform configuration has been created and is being tracked through Terraform state.</p><p>The next step is to independently verify that the EC2 instance actually exists in AWS rather than relying only on Terraform’s output.</p><p>Verify the EC2 Instance with the AWS CLI</p><p>Terraform has now provisioned the AWS infrastructure.</p><p>Although Terraform reports the resources it created, a professional infrastructure workflow should include independent verification.</p><p>In this step, we will use the AWS Command Line Interface (AWS CLI) to verify that the EC2 instance exists in the expected AWS Region and that its configuration matches the Terraform deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3SyW1I11je0hDVmBHavqA.png" /><figcaption>Figure 8 — AWS CLI verification confirming the Terraform-provisioned EC2 instance and its current AWS infrastructure state.</figcaption></figure><p>RETRIEVE THE INSTANCE ID</p><p>First, retrieve the instance ID from Terraform:</p><p>terraform output -raw instance_id</p><p>Copy the returned instance ID.</p><p>It should look similar to:</p><p>i-0123456789abcdef0</p><p>The actual value will be different in your AWS account.</p><p>VERIFY THE INSTANCE WITH AWS CLI</p><p>Run the following command, replacing YOUR_INSTANCE_ID with the instance ID returned by Terraform:</p><p>aws ec2 describe-instances — instance-ids YOUR_INSTANCE_ID — region us-east-1</p><p>AWS CLI should return detailed information about the EC2 instance.</p><p>The response contains information such as:</p><p>• Instance ID<br>• Instance state<br>• AMI ID<br>• Instance type<br>• Private IP address<br>• Public IP address, if assigned<br>• Security group association<br>• Key pair name<br>• Availability Zone<br>• Network interface information</p><p>VERIFY ONLY THE INSTANCE STATE</p><p>For a more concise verification, run:</p><p>aws ec2 describe-instances — instance-ids YOUR_INSTANCE_ID — region us-east-1 — query “Reservations[].Instances[].State.Name” — output text</p><p>A successfully running instance should return:</p><p>running</p><p>VERIFY THE INSTANCE ID AND PUBLIC IP</p><p>You can retrieve the instance ID and public IP address together with:</p><p>aws ec2 describe-instances — instance-ids YOUR_INSTANCE_ID — region us-east-1 — query “Reservations[].Instances[].{InstanceId:InstanceId,PublicIP:PublicIpAddress,State:State.Name}” — output table</p><p>The output should provide a table containing the instance ID, public IP address, and current instance state.</p><p>VERIFY THE SECURITY GROUP ASSOCIATION</p><p>Run:</p><p>aws ec2 describe-instances — instance-ids YOUR_INSTANCE_ID — region us-east-1 — query “Reservations[].Instances[].SecurityGroups[].{GroupId:GroupId,GroupName:GroupName}” — output table</p><p>This confirms which security group is associated with the EC2 instance.</p><p>VERIFY THE KEY PAIR</p><p>Run:</p><p>aws ec2 describe-instances — instance-ids YOUR_INSTANCE_ID — region us-east-1 — query “Reservations[].Instances[].KeyName” — output text</p><p>The result should show:</p><p>dove-key</p><p>This confirms that the EC2 instance was launched with the expected key pair.</p><p>WHY INDEPENDENT VERIFICATION MATTERS</p><p>Terraform state represents Terraform’s understanding of the infrastructure it manages.</p><p>AWS CLI queries the actual AWS environment.</p><p>Using both provides a stronger verification process because it allows us to compare:</p><p>Terraform configuration<br> ↓<br>Terraform state<br> ↓<br>AWS API response</p><p>This approach is useful when troubleshooting infrastructure drift, unexpected changes, or deployment failures.</p><p>WHAT WE HAVE ACHIEVED</p><p>We have independently verified the EC2 instance through the AWS API using the AWS CLI.</p><p>The verification confirms that the instance exists in the expected Region and allows us to inspect its operational state, networking information, security group association, and key pair.</p><p>In the next step, we will verify the same infrastructure through the AWS Management Console.</p><p>Verify the EC2 Instance in the AWS Management Console</p><p>The AWS CLI has confirmed that the EC2 instance exists.</p><p>As a second verification method, we will inspect the deployed infrastructure through the AWS Management Console.</p><p>Using both command-line and console-based verification provides useful operational evidence and helps confirm that the infrastructure visible through AWS matches what Terraform provisioned.</p><p>OPEN THE AMAZON EC2 CONSOLE</p><p>Sign in to the AWS Management Console.</p><p>Navigate to:</p><p>EC2 → Instances</p><p>Make sure the selected AWS Region is:</p><p>US East (N. Virginia) — us-east-1</p><p>This is important because EC2 resources are regional.</p><p>If the console is displaying a different Region, the instance may not appear in the instance list.</p><p>LOCATE THE INSTANCE</p><p>In the EC2 Instances page, locate the instance created by Terraform.</p><p>You can identify it using:</p><p>• Instance ID<br>• Name tag<br>• Instance state<br>• Instance type</p><p>The instance should have the Name tag:</p><p>dove</p><p>Select the instance to open its details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1OpuyUvwAMWA5Qnql9znlg.png" /><figcaption>Figure 9 — Amazon EC2 Management Console showing the Terraform-provisioned instance and its operational status.</figcaption></figure><p>VERIFY THE INSTANCE STATE</p><p>In the instance details, locate the instance state.</p><p>The expected state after successful provisioning is:</p><p>Running</p><p>The instance may briefly display:</p><p>Pending</p><p>while AWS completes the launch process.</p><p>Wait until the state changes to:</p><p>Running</p><p>VERIFY THE INSTANCE TYPE</p><p>Check the instance type shown in the EC2 console.</p><p>The Terraform configuration specifies:</p><p>t3.micro</p><p>The console should therefore show the corresponding instance type.</p><p>VERIFY THE AMI</p><p>Locate the AMI information in the instance details.</p><p>The AMI ID should correspond to the Ubuntu AMI selected by the Terraform data source.</p><p>This demonstrates the relationship between:</p><p>Terraform AMI Data Source → EC2 Instance</p><p>VERIFY THE KEY PAIR</p><p>Locate the key pair information for the instance.</p><p>It should show:</p><p>dove-key</p><p>This confirms that the EC2 instance was launched with the key pair defined in keypair.tf.</p><p>VERIFY THE SECURITY GROUP</p><p>Locate the security group associated with the instance.</p><p>The security group should correspond to the Terraform-managed security group:</p><p>dove-sg-224</p><p>Open the security group to inspect its inbound rules.</p><p>The expected inbound configuration is:</p><p>SSH — TCP 22 — restricted to your configured public IP address</p><p>HTTP — TCP 80–0.0.0.0/0</p><p>Do not expose SSH to 0.0.0.0/0 unless there is a specific and justified operational requirement.</p><p>VERIFY NETWORK INFORMATION</p><p>Review the instance networking information.</p><p>Depending on the AWS environment, you may see:</p><p>• Private IPv4 address<br>• Public IPv4 address<br>• Private DNS name<br>• Public DNS name<br>• VPC<br>• Subnet<br>• Availability Zone</p><p>These values are useful when troubleshooting connectivity and validating the deployed environment.</p><p>CAPTURE IMPLEMENTATION EVIDENCE</p><p>For a documented project, useful screenshots include:</p><p>• EC2 instance showing the Running state<br>• EC2 instance details showing the instance ID<br>• Security group inbound rules<br>• Terraform terminal output showing successful provisioning<br>• AWS CLI verification output</p><p>Avoid capturing sensitive credentials, private keys, or other confidential information in screenshots.</p><p>WHY CONSOLE VERIFICATION MATTERS</p><p>The AWS Management Console provides a visual representation of the infrastructure currently deployed in AWS.</p><p>Combined with Terraform and AWS CLI verification, the workflow becomes:</p><p>Terraform Configuration<br> ↓<br>Terraform Plan<br> ↓<br>Terraform Apply<br> ↓<br>Terraform State<br> ↓<br>AWS CLI Verification<br> ↓<br>AWS Console Verification</p><p>This provides multiple points of evidence that the infrastructure has been provisioned as intended.</p><p>WHAT WE HAVE ACHIEVED</p><p>The EC2 instance and its supporting configuration have now been verified through the AWS Management Console.</p><p>We have confirmed the deployed instance, instance state, instance type, AMI, key pair, security group, and network configuration.</p><p>In the next step, we will inspect Terraform state to understand how Terraform tracks the infrastructure it manages.</p><p>Inspect and Understand Terraform State</p><p>Terraform state is one of the most important concepts to understand when working with Infrastructure as Code.</p><p>Terraform uses state to maintain a record of the infrastructure it manages. The state allows Terraform to associate resources defined in configuration with the corresponding real-world resources in AWS.</p><p>In this project, Terraform is using local state.</p><p>INSPECT THE TERRAFORM STATE FILE</p><p>After terraform apply has successfully created the infrastructure, Terraform should have generated:</p><p>terraform.tfstate</p><p>You can confirm its presence with:</p><p>Get-ChildItem terraform.tfstate</p><p>Do not edit this file manually.</p><p>Terraform manages the state file and updates it as infrastructure changes are applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tb2CfCfxAHUsDCUShGUXzA.png" /><figcaption>Figure 5 — Terraform state inspection showing the AWS resources currently tracked and managed by Terraform.</figcaption></figure><p>LIST RESOURCES TRACKED BY TERRAFORM</p><p>Run:</p><p>terraform state list</p><p>You should see resources similar to:</p><p>data.aws_ami.ubuntu<br>aws_key_pair.dove_key<br>aws_security_group.dove_sg<br>aws_instance.dove</p><p>The exact list depends on the final configuration.</p><p>The important point is that Terraform now has records connecting the configuration to the corresponding AWS resources.</p><p>INSPECT A SPECIFIC RESOURCE</p><p>To inspect the EC2 instance stored in Terraform state, run:</p><p>terraform state show aws_instance.dove</p><p>Terraform will display the attributes it currently knows about the managed EC2 instance.</p><p>This can include information such as:</p><p>• Instance ID<br>• AMI ID<br>• Instance type<br>• Key pair<br>• Security groups<br>• Private IP address<br>• Public IP address<br>• Availability Zone<br>• Tags</p><p>You can also inspect the security group:</p><p>terraform state show aws_security_group.dove_sg</p><p>And the key pair:</p><p>terraform state show aws_key_pair.dove_key</p><p>UNDERSTANDING TERRAFORM STATE</p><p>The Terraform state establishes a relationship between:</p><p>Terraform Configuration<br> ↓<br>Terraform State<br> ↓<br>Real AWS Infrastructure</p><p>For example, the configuration contains:</p><p>resource “aws_instance” “dove”</p><p>Terraform state records the corresponding AWS EC2 instance and its attributes.</p><p>This allows Terraform to determine what already exists and what changes are required during subsequent planning operations.</p><p>STATE IS NOT THE CONFIGURATION</p><p>It is important to distinguish Terraform configuration from Terraform state.</p><p>Terraform configuration describes the desired infrastructure.</p><p>Terraform state records information about infrastructure Terraform is managing.</p><p>The configuration is written and maintained by the engineer.</p><p>The state is maintained by Terraform.</p><p>SECURITY CONSIDERATION</p><p>Terraform state can contain sensitive infrastructure information depending on the resources and configuration being managed.</p><p>For this reason, local state files should not be committed to a public Git repository.</p><p>The project’s .gitignore includes:</p><p>*.tfstate<br>*.tfstate.*</p><p>This prevents local Terraform state files from being tracked by Git.</p><p>LOCAL STATE VS REMOTE STATE</p><p>This project uses local Terraform state because the objective is to demonstrate the fundamental Terraform workflow in a controlled learning environment.</p><p>In a production or collaborative environment, Terraform state is commonly stored remotely with appropriate locking, access control, encryption, backup, and recovery mechanisms.</p><p>Examples of production-oriented approaches include using an Amazon S3 backend together with appropriate state locking and access controls.</p><p>Do not treat local state as the preferred architecture for a large team or production environment.</p><p>WHAT WE HAVE ACHIEVED</p><p>We have inspected the Terraform state and confirmed that Terraform is tracking the resources provisioned in AWS.</p><p>We have also established an important Infrastructure as Code concept:</p><p>Terraform configuration defines the desired state, while Terraform state allows Terraform to track the infrastructure it manages.</p><p>In the next step, we will test Terraform’s reconciliation behavior by running another plan after the infrastructure has already been provisioned.</p><p>Test Terraform Reconciliation with a No-Change Plan</p><p>The infrastructure has now been provisioned and Terraform state contains information about the resources it manages.</p><p>A key capability of Terraform is reconciliation.</p><p>Terraform compares the desired configuration with the current state and the real infrastructure information available through the provider. If the infrastructure already matches the declared configuration, Terraform should determine that no changes are required.</p><p>RUN TERRAFORM PLAN AGAIN</p><p>From the project directory, run:</p><p>terraform plan</p><p>Because the infrastructure has already been provisioned and no configuration changes have been made, Terraform should report:</p><p>No changes. Your infrastructure matches the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-M9yCseaJqRPlKO3CuiROA.png" /><figcaption>Figure 4 — Terraform reconciliation showing that the deployed infrastructure matches the declared configuration and requires no changes.</figcaption></figure><p>This is an important result.</p><p>It means Terraform has evaluated the configuration and determined that there is currently no infrastructure change that needs to be applied.</p><p>UNDERSTANDING “NO CHANGES”</p><p>The no-change result demonstrates the relationship between:</p><p>Terraform Configuration<br> ↓<br>Terraform State<br> ↓<br>AWS Infrastructure</p><p>The configuration describes what the infrastructure should look like.</p><p>Terraform state records the resources Terraform manages.</p><p>The AWS provider allows Terraform to evaluate the infrastructure through AWS.</p><p>When these are aligned, Terraform has no reason to create, modify, or destroy resources.</p><p>WHY THIS MATTERS</p><p>The ability to repeatedly run Terraform against the same infrastructure without unnecessarily recreating resources is fundamental to Infrastructure as Code.</p><p>It allows engineers to:</p><p>• Review infrastructure safely<br>• Detect configuration changes<br>• Identify potential drift<br>• Apply only required changes<br>• Maintain a predictable infrastructure workflow</p><p>SIMULATE A CONFIGURATION CHANGE</p><p>To understand reconciliation more clearly, consider changing a non-critical configuration value such as the EC2 instance tag.</p><p>For example, change:</p><p>Name = “dove”</p><p>to:</p><p>Name = “dove-updated”</p><p>Then run:</p><p>terraform plan</p><p>Terraform should identify the tag modification that would be required.</p><p>The plan allows you to review the proposed change before it is applied.</p><p>Do not apply this test change unless you intentionally want to modify the deployed resource.</p><p>If you made the change only for demonstration purposes, restore the original value:</p><p>Name = “dove”</p><p>Then run:</p><p>terraform plan</p><p>Terraform should again report:</p><p>No changes. Your infrastructure matches the configuration.</p><p>IMPORTANT DISTINCTION</p><p>terraform plan does not automatically repair infrastructure.</p><p>It identifies differences between the declared configuration and the infrastructure Terraform can determine from its state and provider information.</p><p>When changes are required, terraform apply is used to execute the approved changes.</p><p>WHAT WE HAVE ACHIEVED</p><p>We have demonstrated Terraform’s reconciliation workflow and confirmed that the deployed infrastructure matches the current Terraform configuration.</p><p>A successful no-change plan is an important verification point because it demonstrates that the configuration, Terraform state, and deployed infrastructure are currently aligned.</p><p>In the next step, we will examine how Terraform responds when infrastructure is intentionally changed outside Terraform.</p><p>Test Infrastructure Drift Detection</p><p>One of the practical benefits of Infrastructure as Code is the ability to identify when infrastructure no longer matches the configuration used to manage it.</p><p>This situation is commonly referred to as infrastructure drift.</p><p>Drift can occur when a resource managed by Terraform is changed manually through the AWS Management Console, AWS CLI, another automation system, or another administrator.</p><p>For this demonstration, we will make a controlled change to the EC2 instance outside Terraform and then use Terraform to identify the difference.</p><p>IMPORTANT</p><p>Only perform this test if you are comfortable making a temporary change to the EC2 instance.</p><p>Do not modify critical production infrastructure as part of a learning exercise.</p><p>IDENTIFY THE EC2 INSTANCE</p><p>Retrieve the instance ID:</p><p>terraform output -raw instance_id</p><p>Copy the returned instance ID.</p><p>MAKE A CONTROLLED CHANGE IN AWS</p><p>Open:</p><p>AWS Management Console → EC2 → Instances</p><p>Select the Terraform-managed instance.</p><p>Choose:</p><p>Actions → Instance settings → Change instance type</p><p>If the instance is running, AWS may require you to stop it before changing the instance type.</p><p>For this demonstration, change the instance type from:</p><p>t3.micro</p><p>to:</p><p>t3.small</p><p>Apply the change in the AWS Console.</p><p>VERIFY THE MANUAL CHANGE</p><p>After the instance becomes available again, verify the current instance type through the AWS CLI:</p><p>aws ec2 describe-instances — instance-ids YOUR_INSTANCE_ID — region us-east-1 — query “Reservations[].Instances[].InstanceType” — output text</p><p>The result should show:</p><p>t3.small</p><p>However, the Terraform configuration still declares:</p><p>instance_type = “t3.micro”</p><p>RUN TERRAFORM PLAN</p><p>Now return to the Terraform project directory and run:</p><p>terraform plan</p><p>Terraform should identify that the actual infrastructure no longer matches the declared configuration.</p><p>Depending on the exact resource behavior and current Terraform state, the plan may propose changing the instance back to:</p><p>t3.micro</p><p>This demonstrates how Terraform can identify an infrastructure difference that occurred outside the Terraform workflow.</p><p>UNDERSTANDING DRIFT</p><p>The simplified workflow is:</p><p>Terraform Configuration<br> ↓<br>Desired State</p><p>AWS Infrastructure<br> ↓<br>Current Infrastructure</p><p>Terraform compares the information available through its state and provider with the declared configuration.</p><p>When a difference is detected, Terraform can propose corrective changes.</p><p>RESTORE THE DECLARED CONFIGURATION</p><p>Because this is a temporary demonstration, return the EC2 instance to the configuration declared in Terraform.</p><p>The desired instance type is:</p><p>t3.micro</p><p>The safest approach is to allow Terraform to perform the correction after reviewing its plan.</p><p>Run:</p><p>terraform apply</p><p>Review the proposed change carefully.</p><p>When prompted:</p><p>Enter a value:</p><p>type:</p><p>yes</p><p>Terraform should reconcile the EC2 instance with the configuration.</p><p>VERIFY THE INSTANCE TYPE</p><p>After the operation completes, verify the instance type:</p><p>aws ec2 describe-instances — instance-ids YOUR_INSTANCE_ID — region us-east-1 — query “Reservations[].Instances[].InstanceType” — output text</p><p>The result should now be:</p><p>t3.micro</p><p>RUN A FINAL PLAN</p><p>Finally, run:</p><p>terraform plan</p><p>The expected result is:</p><p>No changes. Your infrastructure matches the configuration.</p><p>IMPORTANT ENGINEERING LESSON</p><p>Terraform should not be viewed simply as a tool for creating infrastructure.</p><p>It is also a mechanism for defining and maintaining the desired state of infrastructure.</p><p>Manual changes to Terraform-managed resources can create operational inconsistencies, so production environments should establish clear ownership and change-management practices.</p><p>WHAT WE HAVE ACHIEVED</p><p>We intentionally introduced a controlled infrastructure difference, used Terraform to identify the resulting discrepancy, and then reconciled the resource with the declared configuration.</p><p>This demonstrates an important operational concept:</p><p>Configuration → Detection → Review → Reconciliation → Verification</p><p>In the next step, we will examine the Terraform resource lifecycle and safely destroy the temporary infrastructure when the project is complete.</p><p>Manage the Terraform Infrastructure Lifecycle</p><p>Terraform is designed to manage infrastructure throughout its lifecycle, not only during initial provisioning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnRsKDAXSwYq75VuHnc7XA.png" /></figure><p>A typical Terraform lifecycle includes:</p><p>Configuration<br> ↓<br>Initialization<br> ↓<br>Validation<br> ↓<br>Planning<br> ↓<br>Provisioning<br> ↓<br>Verification<br> ↓<br>Modification<br> ↓<br>Destruction</p><p>In the previous steps, we provisioned the AWS infrastructure, verified it, and demonstrated Terraform’s reconciliation behavior.</p><p>The final lifecycle operation for this learning environment is to safely remove the resources when they are no longer required.</p><p>REVIEW THE CURRENT INFRASTRUCTURE</p><p>Before destroying anything, confirm the resources currently tracked by Terraform:</p><p>terraform state list</p><p>Review the output carefully.</p><p>You should see the Terraform-managed resources, such as:</p><p>data.aws_ami.ubuntu<br>aws_key_pair.dove_key<br>aws_security_group.dove_sg<br>aws_instance.dove</p><p>The exact output depends on the final configuration.</p><p>CREATE A FINAL PLAN</p><p>Before destruction, run:</p><p>terraform plan</p><p>Confirm that Terraform reports:</p><p>No changes. Your infrastructure matches the configuration.</p><p>This provides an additional verification point before beginning the destruction process.</p><p>DESTROY THE INFRASTRUCTURE</p><p>When you are certain that the infrastructure is no longer required, run:</p><p>terraform destroy</p><p>Terraform will generate a destruction plan and ask for confirmation.</p><p>Review the resources that Terraform proposes to remove.</p><p>When prompted:</p><p>Enter a value:</p><p>type:</p><p>yes</p><p>and press Enter.</p><p>Terraform will then remove the resources it manages.</p><p>IMPORTANT COST AND DATA WARNING</p><p>terraform destroy is a destructive operation.</p><p>It can permanently remove cloud resources and any data stored on those resources.</p><p>Do not run terraform destroy against production infrastructure unless the destruction is explicitly planned, reviewed, authorized, and understood.</p><p>For this tutorial, the infrastructure is a learning environment and can be safely removed after the implementation has been verified.</p><p>VERIFY THE DESTRUCTION</p><p>After terraform destroy completes, run:</p><p>terraform state list</p><p>Terraform should no longer list the previously managed infrastructure resources.</p><p>You can also run:</p><p>terraform plan</p><p>Because the resources have been destroyed, Terraform may propose creating them again if the configuration remains present.</p><p>This is expected.</p><p>If the objective is to completely retire the Terraform configuration as well, the configuration files can subsequently be archived or removed according to your project requirements.</p><p>VERIFY THROUGH AWS CLI</p><p>You can also confirm that the EC2 instance no longer exists by querying AWS:</p><p>aws ec2 describe-instances — instance-ids YOUR_INSTANCE_ID — region us-east-1</p><p>If the instance has been successfully terminated, AWS should no longer report it as an active instance.</p><p>The exact CLI response can vary depending on the instance’s final state and AWS API behavior.</p><p>UNDERSTANDING THE LIFECYCLE</p><p>The complete workflow demonstrated in this project is:</p><p>1. Define infrastructure as code.<br>2. Initialize Terraform.<br>3. Discover existing AWS information through a data source.<br>4. Validate the configuration.<br>5. Review the execution plan.<br>6. Provision AWS infrastructure.<br>7. Verify the deployed resources.<br>8. Inspect Terraform state.<br>9. Test reconciliation and drift handling.<br>10. Destroy the infrastructure when it is no longer required.</p><p>This lifecycle demonstrates that Terraform is not simply an EC2 provisioning tool. It is an Infrastructure as Code framework for defining, planning, managing, modifying, verifying, and removing infrastructure through a declarative workflow.</p><p>WHAT WE HAVE ACHIEVED</p><p>The complete Terraform infrastructure lifecycle has now been demonstrated.</p><p>The AWS resources can be created from code, verified independently, reconciled when differences occur, and safely removed when the environment is no longer required.</p><p>In the next section, we will review common troubleshooting scenarios encountered during this implementation and the practical approaches used to resolve them.</p><p>Troubleshooting and Common Issues</p><p>Infrastructure automation rarely succeeds without encountering configuration, authentication, networking, or environment-related issues.</p><p>A strong Terraform workflow therefore includes not only successful deployment steps, but also a methodical approach to diagnosing failures.</p><p>The following troubleshooting scenarios are particularly relevant to this project.</p><p>1. TERRAFORM COMMAND NOT RECOGNIZED</p><p>If PowerShell returns an error indicating that terraform is not recognized, Terraform may not be installed correctly or its executable directory may not be included in the system PATH.</p><p>Verify the installation:</p><p>terraform version</p><p>If the command fails, confirm that Terraform is installed and that its installation directory is available through the PATH environment variable.</p><p>After updating PATH, restart PowerShell and run:</p><p>terraform version</p><p>2. AWS CLI AUTHENTICATION FAILURE</p><p>If:</p><p>aws sts get-caller-identity</p><p>fails, verify that the AWS CLI is configured correctly.</p><p>Run:</p><p>aws configure</p><p>Then provide the required AWS credentials and default Region when prompted.</p><p>After configuration, test again:</p><p>aws sts get-caller-identity</p><p>For production environments, prefer secure credential mechanisms such as IAM roles, AWS IAM Identity Center, environment-specific credential profiles, or other approved AWS authentication methods rather than embedding long-lived credentials in Terraform files.</p><p>3. TERRAFORM INIT FAILS</p><p>If:</p><p>terraform init</p><p>fails, check:</p><p>• Internet connectivity<br>• AWS provider source<br>• Terraform version<br>• Provider registry availability<br>• Proxy or firewall configuration</p><p>The project should contain a valid provider declaration similar to:</p><p>terraform {<br> required_providers {<br> aws = {<br> source = “hashicorp/aws”<br> }<br> }<br>}</p><p>Run:</p><p>terraform init</p><p>again after correcting the underlying issue.</p><p>4. TERRAFORM VALIDATE FAILS</p><p>If:</p><p>terraform validate</p><p>returns an error, read the error message carefully.</p><p>Terraform normally identifies the configuration file, line, and attribute associated with the problem.</p><p>Common causes include:</p><p>• Incorrect resource names<br>• Missing braces<br>• Incorrect attribute names<br>• Invalid references<br>• Typographical errors<br>• Incorrect data source configuration</p><p>After correcting the configuration, run:</p><p>terraform fmt</p><p>Then:</p><p>terraform validate</p><p>5. AMI DATA SOURCE RETURNS NO RESULTS</p><p>If the AMI data source cannot find a matching image, verify:</p><p>• The configured AWS Region<br>• The AMI owner ID<br>• The Ubuntu image name pattern<br>• The virtualization type<br>• The root device type</p><p>The project uses the Ubuntu owner ID:</p><p>099720109477</p><p>Remember that this is the Ubuntu image publisher’s AWS account ID, not your personal AWS account ID.</p><p>You can also inspect the configured Region in provider.tf.</p><p>6. SSH ACCESS FAILS</p><p>If SSH access to the EC2 instance fails, check:</p><p>• The EC2 instance is running.<br>• The instance has a reachable public IP address.<br>• TCP port 22 is allowed by the security group.<br>• The SSH source CIDR matches your current public IP address.<br>• The correct private key is being used.<br>• The private key has appropriate local permissions.<br>• Network ACLs and routing are not blocking traffic.</p><p>If your public IP address has changed since the security group was created, the existing SSH rule may no longer permit your connection.</p><p>Review the security group before making changes.</p><p>7. EC2 INSTANCE IS NOT REACHABLE</p><p>If the instance is running but cannot be reached, verify:</p><p>aws ec2 describe-instances — instance-ids YOUR_INSTANCE_ID — region us-east-1</p><p>Check the instance state, public IP address, subnet, VPC, and security group association.</p><p>Then inspect the security group’s inbound rules.</p><p>8. TERRAFORM PLAN SHOWS UNEXPECTED CHANGES</p><p>If:</p><p>terraform plan</p><p>shows changes you did not expect, do not immediately run:</p><p>terraform apply</p><p>First determine why Terraform believes a change is necessary.</p><p>Review:</p><p>terraform state list</p><p>Then inspect the affected resource:</p><p>terraform state show RESOURCE_ADDRESS</p><p>For example:</p><p>terraform state show aws_instance.dove</p><p>Also compare the Terraform configuration with the current AWS resource configuration.</p><p>Unexpected changes can result from:</p><p>• Manual AWS changes<br>• Configuration modifications<br>• Provider behavior<br>• Changed data source results<br>• Resource drift<br>• Incorrect state<br>• Different Terraform workspaces or environments</p><p>9. TERRAFORM STATE DOES NOT MATCH EXPECTATIONS</p><p>If the state appears inconsistent with the configuration, inspect it rather than manually editing terraform.tfstate.</p><p>Use:</p><p>terraform state list</p><p>and:</p><p>terraform state show RESOURCE_ADDRESS</p><p>State manipulation should be performed only with appropriate Terraform commands and a clear understanding of the consequences.</p><p>For production environments, maintain appropriate state backup, access control, locking, and recovery procedures.</p><p>10. TERRAFORM DESTROY FAILS</p><p>If:</p><p>terraform destroy</p><p>fails, inspect the error message and identify which resource could not be removed.</p><p>Common causes may include:</p><p>• Resource dependencies<br>• AWS permissions<br>• Resources changed outside Terraform<br>• Service-level protection<br>• Networking dependencies</p><p>Do not manually delete Terraform state simply because destruction failed.</p><p>The state represents Terraform’s record of managed infrastructure and should be handled carefully.</p><p>A METHODICAL TROUBLESHOOTING APPROACH</p><p>When a Terraform operation fails, use the following sequence:</p><p>1. Read the complete Terraform error message.<br>2. Identify the resource and attribute involved.<br>3. Check the Terraform configuration.<br>4. Verify AWS credentials and permissions.<br>5. Confirm the configured AWS Region.<br>6. Inspect Terraform state when appropriate.<br>7. Verify the actual AWS resource through the AWS CLI or Console.<br>8. Correct the underlying problem.<br>9. Run terraform fmt.<br>10. Run terraform validate.<br>11. Run terraform plan.<br>12. Apply the change only after reviewing the resulting plan.</p><p>This approach avoids making additional changes before understanding the original failure.</p><p>WHAT WE HAVE ACHIEVED</p><p>The project now includes a practical troubleshooting methodology covering Terraform, AWS authentication, AMI discovery, EC2 connectivity, security groups, state management, unexpected plans, and infrastructure destruction.</p><p>The key principle is simple:</p><p>Diagnose first → Understand the cause → Correct the configuration or environment → Validate → Plan → Apply</p><p>In the next section, we will review the security practices applied throughout the implementation and distinguish the learning environment from production-oriented Terraform practices.</p><p>Security Considerations</p><p>Infrastructure as Code makes cloud infrastructure easier to reproduce and manage, but automation does not automatically make an environment secure.</p><p>Security requirements should therefore be considered throughout the Terraform lifecycle rather than treated as an afterthought.</p><p>This project is a learning implementation, so some configurations are intentionally simplified. The following practices should be considered when adapting the approach to a production environment.</p><p>PROTECT AWS CREDENTIALS</p><p>AWS credentials should never be hard-coded inside Terraform configuration files.</p><p>Do not place credentials such as:</p><p>AWS_ACCESS_KEY_ID<br>AWS_SECRET_ACCESS_KEY</p><p>directly inside provider.tf or other Terraform files.</p><p>Instead, use an approved AWS authentication mechanism such as:</p><p>• AWS CLI credential profiles<br>• IAM roles<br>• IAM Identity Center<br>• Environment-specific credential mechanisms<br>• Workload identity mechanisms where supported</p><p>The authentication method should be selected according to the environment and organizational security requirements.</p><p>PROTECT SSH PRIVATE KEYS</p><p>The private SSH key used by the EC2 instance must remain protected.</p><p>For this project, the private key is:</p><p>dove-key</p><p>It must not be committed to GitHub or shared publicly.</p><p>The project’s .gitignore excludes the local key material.</p><p>A compromised private key can provide unauthorized access to systems that trust the corresponding public key.</p><p>RESTRICT SSH ACCESS</p><p>The security group restricts SSH access to a specific source IP address.</p><p>The rule follows the pattern:</p><p>TCP 22 → YOUR_PUBLIC_IP/32</p><p>The /32 notation limits the rule to one IPv4 address.</p><p>Avoid using:</p><p>0.0.0.0/0</p><p>for SSH access in normal administrative environments.</p><p>If a broader administrative access model is required, use controlled networking mechanisms such as VPN, bastion architecture, AWS Systems Manager, or other approved access solutions.</p><p>HTTP ACCESS</p><p>The project permits HTTP traffic on TCP port 80 from:</p><p>0.0.0.0/0</p><p>This allows public IPv4 HTTP traffic and is suitable for demonstrating a publicly reachable web service.</p><p>For production applications, evaluate whether HTTP should remain publicly exposed and whether HTTPS should be used instead.</p><p>MINIMIZE IAM PERMISSIONS</p><p>The identity used by Terraform should have only the permissions required to perform the intended infrastructure operations.</p><p>Avoid using unrestricted administrator privileges for routine automation when a more narrowly scoped IAM policy can be implemented.</p><p>This follows the principle of least privilege.</p><p>PROTECT TERRAFORM STATE</p><p>Terraform state can contain sensitive infrastructure information.</p><p>The local state file:</p><p>terraform.tfstate</p><p>should not be committed to a public repository.</p><p>For production environments, consider using a secure remote backend with:</p><p>• Encryption at rest<br>• Access control<br>• State locking<br>• Versioning<br>• Backup and recovery<br>• Controlled administrative access</p><p>REVIEW TERRAFORM PLANS</p><p>Always review:</p><p>terraform plan</p><p>before:</p><p>terraform apply</p><p>A plan provides an opportunity to identify unexpected resource creation, modification, or destruction before changes are made to AWS.</p><p>This becomes especially important in production environments.</p><p>CONTROL MANUAL CHANGES</p><p>Avoid making manual changes to infrastructure that is managed by Terraform unless there is a defined operational reason.</p><p>Manual changes can introduce infrastructure drift.</p><p>When an emergency manual change is required, the Terraform configuration should subsequently be updated so that the desired state remains documented and reproducible.</p><p>USE VERSION CONTROL</p><p>Terraform configuration should be maintained in version control.</p><p>Git provides:</p><p>• Change history<br>• Collaboration<br>• Code review<br>• Rollback capability<br>• Traceability</p><p>However, version control should contain infrastructure configuration rather than sensitive credentials or local Terraform state.</p><p>LEARNING ENVIRONMENT VS PRODUCTION</p><p>This tutorial intentionally uses a small EC2 environment to demonstrate Terraform fundamentals.</p><p>A production implementation would typically introduce additional controls such as:</p><p>• Remote Terraform state<br>• State locking<br>• IAM least privilege<br>• Multiple AWS accounts or environments<br>• Separate development, staging, and production configurations<br>• CI/CD-based Terraform execution<br>• Automated security scanning<br>• Policy validation<br>• Secrets management<br>• Private networking where appropriate<br>• Centralized logging and monitoring<br>• Backup and disaster recovery procedures<br>• Formal change management</p><p>SECURITY PRINCIPLE</p><p>The central security principle demonstrated throughout this project is:</p><p>Automate infrastructure without automating insecurity.</p><p>Terraform provides repeatability and consistency, but security still depends on the design decisions made by the engineer.</p><p>WHAT WE HAVE ACHIEVED</p><p>The project has incorporated fundamental security practices around credentials, SSH access, security groups, Terraform state, IAM permissions, infrastructure changes, and version control.</p><p>These practices provide a foundation for evolving the learning implementation toward a more production-oriented Infrastructure as Code architecture.</p><p>In the next section, we will examine AWS cost considerations and explain how to avoid unnecessary charges when running Terraform-managed infrastructure.</p><p>AWS Cost Considerations</p><p>Terraform makes infrastructure provisioning repeatable, but it does not eliminate cloud costs.</p><p>Every AWS resource created through Terraform should therefore be treated as a real infrastructure resource with a potential financial impact.</p><p>This project uses Amazon EC2 and related AWS resources for learning purposes. Before provisioning the environment, understand which resources may generate charges and how to safely remove them when the exercise is complete.</p><p>EC2 INSTANCE COSTS</p><p>The primary compute resource in this project is an Amazon EC2 instance.</p><p>The instance type used in the Terraform configuration is:</p><p>t3.micro</p><p>AWS pricing depends on factors such as:</p><p>• AWS Region<br>• Instance type<br>• Operating system<br>• Usage duration<br>• Pricing model<br>• Additional attached services</p><p>Do not assume that an instance is free simply because it is a small instance type.</p><p>Always check the current AWS pricing and Free Tier eligibility for your account before deploying resources.</p><p>EBS STORAGE</p><p>An EC2 instance normally uses Amazon Elastic Block Store (EBS) storage.</p><p>EBS storage can generate charges depending on the volume type, capacity, and usage.</p><p>Terminating an EC2 instance does not always mean every associated AWS resource should be assumed to incur no cost. Review the attached storage and other resources when cleaning up an environment.</p><p>PUBLIC IPV4 ADDRESS COSTS</p><p>AWS pricing for public IPv4 addresses should also be considered.</p><p>Public IPv4 usage can incur charges depending on the resource and AWS pricing model in effect.</p><p>For this reason, avoid leaving unused public IPv4 resources allocated.</p><p>REGION SELECTION</p><p>AWS pricing varies by Region.</p><p>This project uses:</p><p>us-east-1</p><p>Before deploying the infrastructure, verify the pricing applicable to the selected Region.</p><p>COST CONTROL PRACTICES</p><p>For learning environments, use the following practices:</p><p>• Deploy only the resources required for the exercise.<br>• Avoid leaving development infrastructure running unnecessarily.<br>• Monitor AWS billing and cost information.<br>• Use AWS Budgets where appropriate.<br>• Tag resources consistently.<br>• Destroy temporary infrastructure after completing the exercise.<br>• Review the AWS Console for resources that remain after Terraform destruction.</p><p>DESTROY TEMPORARY INFRASTRUCTURE</p><p>When the project is complete, use:</p><p>terraform destroy</p><p>Review the destruction plan carefully before confirming with:</p><p>yes</p><p>After destruction, verify that the EC2 instance and associated resources have been removed.</p><p>Also check the AWS Management Console for any resources that may have been created outside Terraform or remain because of dependencies.</p><p>IMPORTANT</p><p>Do not run:</p><p>terraform destroy</p><p>against production infrastructure simply because it is included in this tutorial.</p><p>Destruction should always be intentional and authorized.</p><p>COST AWARENESS IN INFRASTRUCTURE AS CODE</p><p>A professional Infrastructure as Code workflow considers cost alongside technical requirements.</p><p>The engineering decision is not simply:</p><p>“Can Terraform create this resource?”</p><p>It should also consider:</p><p>“Is this resource required, what will it cost, and how will its lifecycle be managed?”</p><p>This mindset becomes increasingly important as infrastructure grows from a single EC2 instance to multiple environments, networking components, databases, load balancers, and other managed AWS services.</p><p>WHAT WE HAVE ACHIEVED</p><p>We have considered the financial implications of running Terraform-managed AWS infrastructure and established practical cost-control measures for a learning environment.</p><p>The most important operational practice for this project is simple:</p><p>Deploy what you need → Monitor usage → Destroy temporary infrastructure when finished.</p><p>In the next section, we will document the key engineering lessons learned from implementing this Terraform and AWS project.</p><p>Key Engineering Lessons</p><p>This project demonstrates more than the syntax required to provision an Amazon EC2 instance.</p><p>The implementation provides a practical foundation for understanding how Terraform is used as an Infrastructure as Code tool to define, provision, verify, reconcile, and manage cloud infrastructure.</p><p>INFRASTRUCTURE SHOULD BE DEFINED AS CODE</p><p>One of the most important lessons is the transition from manually creating infrastructure through the AWS Management Console to defining infrastructure declaratively.</p><p>Instead of manually configuring each resource, Terraform configuration describes the desired infrastructure.</p><p>This approach improves:</p><p>• Repeatability<br>• Consistency<br>• Reviewability<br>• Maintainability<br>• Version control<br>• Automation</p><p>UNDERSTAND RESOURCES VS DATA SOURCES</p><p>Terraform resources and data sources serve different purposes.</p><p>A resource tells Terraform to create or manage infrastructure.</p><p>For example:</p><p>resource “aws_instance” “dove”</p><p>A data source retrieves information about an existing resource or external system.</p><p>For example:</p><p>data “aws_ami” “ubuntu”</p><p>Understanding this distinction is fundamental to writing effective Terraform configurations.</p><p>DYNAMIC AMI DISCOVERY IMPROVES MAINTAINABILITY</p><p>The project uses an AWS AMI data source rather than relying on an unexplained hard-coded AMI ID.</p><p>The configuration filters the available images based on characteristics such as:</p><p>• Ubuntu image owner<br>• Image name<br>• Virtualization type<br>• Root device type</p><p>This demonstrates how Terraform can query AWS dynamically before provisioning infrastructure.</p><p>REGIONS MATTER</p><p>AWS resources are not universally identified by a single global resource ID.</p><p>AMI availability is regional, which means an AMI selected in one AWS Region should not automatically be assumed to exist in another Region.</p><p>This is why the AWS provider configuration and AMI discovery logic must be considered together.</p><p>PLAN BEFORE APPLY</p><p>A disciplined Terraform workflow does not immediately apply configuration changes.</p><p>The workflow should be:</p><p>terraform fmt<br> ↓<br>terraform validate<br> ↓<br>terraform plan<br> ↓<br>Review<br> ↓<br>terraform apply</p><p>The plan provides an important opportunity to detect unintended changes before they are executed.</p><p>TERRAFORM STATE IS FUNDAMENTAL</p><p>Terraform state allows Terraform to track the infrastructure it manages.</p><p>The state provides the relationship between the Terraform configuration and the real infrastructure represented through the provider.</p><p>Understanding state is essential when troubleshooting:</p><p>• Unexpected plans<br>• Resource changes<br>• Infrastructure drift<br>• Resource addresses<br>• Terraform reconciliation</p><p>DO NOT MANUALLY EDIT TERRAFORM STATE</p><p>Terraform state should not be treated as an ordinary configuration file.</p><p>If state requires intervention, use appropriate Terraform commands and understand their implications before making changes.</p><p>In production environments, state should also be protected through appropriate backend, access-control, locking, backup, and recovery strategies.</p><p>SECURITY MUST BE PART OF THE DESIGN</p><p>Security cannot be added after infrastructure has already been deployed.</p><p>The project demonstrates several basic security practices:</p><p>• Restricting SSH access to a specific source IP<br>• Protecting SSH private keys<br>• Excluding sensitive local files from Git<br>• Avoiding hard-coded AWS credentials<br>• Reviewing Terraform plans before applying changes<br>• Considering least-privilege IAM permissions</p><p>These practices should become part of the normal Infrastructure as Code workflow.</p><p>VERIFICATION SHOULD BE INDEPENDENT</p><p>A successful terraform apply is not the only evidence that infrastructure is working correctly.</p><p>This project verifies the infrastructure through:</p><p>Terraform outputs<br> ↓<br>Terraform state<br> ↓<br>AWS CLI<br> ↓<br>AWS Management Console</p><p>Independent verification provides greater confidence that the infrastructure actually exists and matches the intended configuration.</p><p>DRIFT REQUIRES OPERATIONAL AWARENESS</p><p>Infrastructure managed by Terraform can still be changed outside Terraform.</p><p>Manual AWS Console changes, emergency modifications, or changes made by other automation can introduce drift.</p><p>Terraform’s planning and reconciliation workflow helps identify differences and provides a mechanism for restoring the declared configuration.</p><p>INFRASTRUCTURE LIFECYCLE MANAGEMENT MATTERS</p><p>Provisioning infrastructure is only one part of infrastructure management.</p><p>A complete lifecycle includes:</p><p>Define → Validate → Plan → Apply → Verify → Modify → Reconcile → Destroy</p><p>Thinking in terms of the complete lifecycle helps prevent abandoned resources, unnecessary costs, unmanaged changes, and configuration inconsistencies.</p><p>PRODUCTION REQUIRES ADDITIONAL ENGINEERING</p><p>The implementation intentionally remains small enough to demonstrate core Terraform concepts.</p><p>A production-grade Terraform architecture would normally introduce additional capabilities such as:</p><p>• Remote state management<br>• State locking<br>• Multiple environments<br>• Reusable modules<br>• CI/CD automation<br>• Policy enforcement<br>• Security scanning<br>• Secrets management<br>• Least-privilege IAM<br>• Centralized logging and monitoring<br>• Change approval processes</p><p>The important lesson is not to over-engineer a learning project, but to understand how the foundational Terraform workflow evolves toward production engineering practices.</p><p>FINAL ENGINEERING TAKEAWAY</p><p>The most important lesson from this project is that Infrastructure as Code is not simply about replacing AWS Console clicks with Terraform commands.</p><p>It is about creating a controlled engineering process in which infrastructure can be:</p><p>Defined as code<br> ↓<br>Reviewed<br> ↓<br>Validated<br> ↓<br>Planned<br> ↓<br>Provisioned<br> ↓<br>Verified<br> ↓<br>Reconciled<br> ↓<br>Safely retired</p><p>This mindset is what makes Terraform valuable as an Infrastructure as Code platform and provides a foundation for more advanced AWS and DevOps automation.</p><p>Conclusion</p><p>In this tutorial, we built an AWS EC2 infrastructure environment using Terraform and followed a complete Infrastructure as Code workflow from configuration through deployment, verification, reconciliation, and lifecycle management.</p><p>Starting with an empty project directory, we progressively built the Terraform configuration and connected the individual components required to provision and manage the AWS environment.</p><p>The implementation covered:</p><p>• AWS provider configuration<br>• Dynamic Ubuntu AMI discovery using a Terraform data source<br>• EC2 SSH key pair configuration<br>• Security group configuration<br>• Amazon EC2 provisioning<br>• Terraform outputs<br>• Terraform formatting and validation<br>• Terraform execution planning<br>• Infrastructure provisioning<br>• Terraform state inspection<br>• AWS CLI verification<br>• AWS Management Console verification<br>• Infrastructure reconciliation<br>• Controlled infrastructure drift detection<br>• Security considerations<br>• AWS cost considerations<br>• Infrastructure lifecycle management and destruction</p><p>More importantly, the project demonstrated a disciplined Terraform workflow:</p><p>Define → Format → Validate → Plan → Review → Apply → Verify → Reconcile → Destroy</p><p>This workflow provides a repeatable foundation for managing cloud infrastructure and can be extended as infrastructure requirements become more complex.</p><p>KEY TAKEAWAY</p><p>Terraform is not simply a tool for replacing manual AWS Console operations with command-line commands.</p><p>It provides an engineering approach for defining infrastructure as code, reviewing proposed changes, provisioning resources consistently, maintaining infrastructure state, identifying configuration differences, and managing the lifecycle of cloud infrastructure.</p><p>Although this project focuses on a relatively small EC2 environment, the same principles can be extended to more advanced AWS architectures involving networking, load balancing, auto scaling, managed databases, containers, CI/CD pipelines, monitoring, security automation, and reusable Terraform modules.</p><p>The next stage of development would be to evolve this foundational implementation toward production-oriented Terraform practices such as remote state management, reusable modules, multiple environments, CI/CD automation, policy enforcement, security scanning, least-privilege IAM, and automated infrastructure validation.</p><p>ABOUT THE AUTHOR</p><p>Olajide Adedayo is an AWS Cloud and DevOps Engineer focused on AWS Cloud, Infrastructure as Code, Terraform, CI/CD automation, containerization, and modern DevOps engineering practices.</p><p>Through hands-on projects, Olajide documents practical implementations designed to demonstrate how cloud infrastructure and DevOps technologies can be applied to real-world engineering workflows.</p><p>PROFESSIONAL &amp; PORTFOLIO LINKS</p><p>GitHub Profile</p><p><a href="https://github.com/olajide-adedayo">https://github.com/olajide-adedayo</a></p><p>GitHub Repository — Terraform Infrastructure Automation with AWS</p><p><a href="https://github.com/olajide-adedayo/terraform-infrastructure-automation-aws">https://github.com/olajide-adedayo/terraform-infrastructure-automation-aws</a></p><p>LinkedIn</p><p><a href="https://www.linkedin.com/in/olajideadedayo/">https://www.linkedin.com/in/olajideadedayo/</a></p><p>PROJECT DOCUMENTATION</p><p>The complete project repository contains the Terraform configuration, implementation screenshots, project documentation, and supporting files:</p><p><a href="https://github.com/olajide-adedayo/terraform-infrastructure-automation-aws">https://github.com/olajide-adedayo/terraform-infrastructure-automation-aws</a></p><p>FINAL THOUGHT</p><p>Infrastructure as Code is most valuable when it becomes an engineering discipline rather than simply a collection of commands.</p><p>Define infrastructure clearly.</p><p>Review changes carefully.</p><p>Automate consistently.</p><p>Verify independently.</p><p>Manage the lifecycle responsibly.</p><p>That is the foundation on which reliable cloud and DevOps engineering practices are built.</p><p>Thank you for following this hands-on Terraform and AWS Infrastructure as Code tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2398bdf8293" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an End-to-End GitLab CI/CD Pipeline for a Java Application: Build, Test, Security Scan…]]></title>
            <link>https://medium.com/@olajideadedayo230/building-an-end-to-end-gitlab-ci-cd-pipeline-for-a-java-application-build-test-security-scan-3d0de1b832f3?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d0de1b832f3</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 13:16:30 GMT</pubDate>
            <atom:updated>2026-08-03T13:16:30.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmG534oQmqyjLL4220StFA.jpeg" /></figure><p>Building an End-to-End GitLab CI/CD Pipeline for a Java Application: Build, Test, Security Scan, Docker &amp; Container Registry</p><p>Learn how to build a production-oriented GitLab CI/CD pipeline using Maven, Trivy, Docker, and GitLab Container Registry while implementing DevSecOps best practices.</p><p>Introduction</p><p>Continuous Integration and Continuous Delivery (CI/CD) have become essential practices in modern software development. Automating the build, testing, security scanning, and packaging of applications enables teams to deliver software faster, more reliably, and with greater confidence.</p><p>In this hands-on tutorial, we&#39;ll build an end-to-end GitLab CI/CD pipeline for a Java web application using GitLab CI/CD. Along the way, we&#39;ll implement a multi-stage pipeline that compiles the application with Maven, executes automated tests, performs vulnerability scanning with Trivy, builds a Docker image, and prepares it for publication to the GitLab Container Registry.</p><p>Rather than focusing only on the final configuration, this tutorial walks through the implementation step by step, explaining the purpose of each stage and the GitLab features used throughout the pipeline. You&#39;ll also see how branch-based development, Merge Requests, CI/CD variables, artifacts, and conditional pipeline execution contribute to a production-oriented DevOps workflow.</p><p>By the end of this guide, you&#39;ll have a practical understanding of how GitLab&#39;s integrated DevOps platform can be used to automate software delivery while incorporating security early in the development lifecycle.</p><p>Project Overview</p><p>In this project, we will build a complete GitLab CI/CD pipeline for a Java web application using GitLab&#39;s integrated DevOps platform. The objective is to automate the software delivery lifecycle—from source code commit to Docker image creation—while incorporating security checks and modern CI/CD best practices.</p><p>The pipeline is designed using multiple stages, with each stage responsible for a specific task in the software delivery process:</p><p>Build: Compile the Java application using Apache Maven.</p><p>Test: Execute automated tests to validate the application.</p><p>Security Scan: Integrate Trivy to identify vulnerabilities within the project before deployment.</p><p>Docker Build &amp; Publish: Build a Docker image using a multi-stage Dockerfile and publish it to the GitLab Container Registry.</p><p>Notifications: Configure pipeline notifications to improve visibility into pipeline execution and failures.</p><p>Throughout the implementation, we will also explore several core GitLab CI/CD features, including:</p><p>GitLab CI/CD Variables for secure configuration management.</p><p>Pipeline Rules for conditional job execution.</p><p>Merge Requests for collaborative code reviews.</p><p>Artifacts for sharing build outputs between jobs.</p><p>Job Dependencies using the needs: keyword to optimize pipeline execution.</p><p>Docker-in-Docker (DinD) for container image creation within GitLab runners.</p><p>By the end of this tutorial, you will have implemented a production-oriented CI/CD pipeline that demonstrates Continuous Integration, DevSecOps practices, containerization, and GitLab-native automation. More importantly, you will understand not only how to configure each stage, but also why each component is an important part of a modern software delivery workflow.</p><p>Prerequisites</p><p>Before getting started, ensure you have the following tools, accounts, and basic knowledge. While this tutorial explains each implementation step, having these prerequisites in place will allow you to follow along seamlessly.</p><p>Accounts</p><p>A GitLab account</p><p>A GitHub account (optional, for portfolio documentation and source code backup)</p><p>Software &amp; Tools</p><p>Git</p><p>Visual Studio Code (or your preferred code editor)</p><p>Java Development Kit (JDK 17 or later)</p><p>Apache Maven</p><p>Docker Desktop (for local Docker testing)</p><p>A modern web browser (Google Chrome, Microsoft Edge, or Mozilla Firefox)</p><p>Technical Knowledge</p><p>This tutorial assumes a basic understanding of:</p><p>Git fundamentals (clone, add, commit, push, branches)</p><p>Java applications and Maven projects</p><p>Basic Docker concepts</p><p>Fundamental CI/CD concepts</p><p>Don&#39;t worry if you&#39;re new to GitLab CI/CD. Every stage of the pipeline is explained in detail, including why it is required and how it contributes to an automated software delivery workflow.</p><p>What You Will Build</p><p>By the end of this tutorial, you will have successfully implemented a GitLab CI/CD pipeline capable of:</p><p>Automatically building a Java application using Maven.</p><p>Running automated tests.</p><p>Performing vulnerability scanning with Trivy.</p><p>Managing build artifacts between pipeline stages.</p><p>Applying conditional job execution using GitLab Rules.</p><p>Building Docker images using Docker-in-Docker (DinD).</p><p>Publishing Docker images to the GitLab Container Registry.</p><p>Managing secure credentials using GitLab CI/CD Variables.</p><p>Implementing a Merge Request workflow for collaborative development.</p><p>The completed project serves as a practical example of modern DevOps and DevSecOps practices and can be used as part of a professional technical portfolio.</p><p>Solution Architecture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*Zg4AI66p6UuQ2nsySbeJCA.jpeg" /></figure><p>The solution is built around GitLab&#39;s integrated CI/CD platform, where every code change triggers an automated pipeline responsible for building, testing, securing, and packaging the application.</p><p>Instead of performing these tasks manually, GitLab CI/CD orchestrates the entire workflow through a series of well-defined stages. Each stage has a specific responsibility and passes its output to the next stage, creating a streamlined and repeatable software delivery process.</p><p>The pipeline follows the workflow below:Developer │ ▼ GitLab Repository │ ▼ GitLab CI/CD Pipeline │ ├── Build Stage (Apache Maven) │ ├── Test Stage │ ├── Security Scan Stage (Trivy) │ ├── Docker Build &amp; Publish Stage │ ▼ GitLab Container Registry</p><p>Pipeline Components</p><p>GitLab Repository</p><p>The GitLab repository serves as the central source code repository. Developers push code changes, create feature branches, and collaborate using Merge Requests before changes are merged into the main branch.</p><p>Build Stage</p><p>The pipeline begins by compiling the Java application with Apache Maven. During this stage, project dependencies are downloaded, the source code is compiled, and a deployable WAR artifact is generated.</p><p>Test Stage</p><p>Once the application is successfully built, automated tests are executed to validate that the application behaves as expected. This helps detect issues early before they progress further through the pipeline.</p><p>Security Scan Stage</p><p>To incorporate DevSecOps practices, Trivy scans the project for known vulnerabilities. Integrating security checks into the CI/CD pipeline enables vulnerabilities to be identified early in the software development lifecycle.</p><p>Docker Build &amp; Publish Stage</p><p>After the application successfully passes the previous stages, Docker builds a container image using a multi-stage Dockerfile. The completed image is then published to the GitLab Container Registry, making it available for deployment to containerized environments.</p><p>GitLab Container Registry</p><p>GitLab&#39;s built-in Container Registry securely stores versioned Docker images. Because it is fully integrated with GitLab CI/CD, authentication is handled using predefined CI/CD variables, eliminating the need to expose registry credentials within the pipeline configuration.</p><p>Benefits of This Architecture</p><p>This architecture provides several advantages:</p><p>Automated software delivery from code commit to container image creation.</p><p>Consistent and repeatable builds across environments.</p><p>Early detection of build failures, test failures, and security vulnerabilities.</p><p>Secure credential management using GitLab CI/CD Variables.</p><p>Improved collaboration through feature branches and Merge Requests.</p><p>A production-oriented DevOps workflow that aligns with modern CI/CD and DevSecOps best practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*SxEvzkDoQ9638L3K5lWqfg.jpeg" /></figure><p>Step 1: Creating Your First GitLab CI/CD Pipeline</p><p>With the project architecture in place, it&#39;s time to create our first GitLab CI/CD pipeline.</p><p>GitLab uses a special configuration file named .gitlab-ci.yml to define every stage, job, and command that should be executed whenever a pipeline is triggered. This file resides in the root directory of the project and serves as the blueprint for the entire CI/CD workflow.</p><p>Our initial objective is simple: create a basic pipeline that verifies GitLab CI/CD is correctly configured and capable of executing jobs automatically.</p><p>Creating the .gitlab-ci.yml File</p><p>In the root directory of your project, create a new file named:</p><p>.gitlab-ci.yml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWaAjkoR4qOy-KKDNqRVvw.png" /><figcaption>Figure 1: Creating the initial .gitlab-ci.yml file that defines the GitLab CI/CD pipeline.</figcaption></figure><p>GitLab automatically detects this file whenever code is pushed to the repository. If the file is present and contains valid YAML syntax, GitLab creates and executes a new pipeline.</p><p>Defining the Pipeline Stages</p><p>The first section of the configuration defines the pipeline stages.</p><p>stages: - build - test</p><p>In this example, the pipeline consists of two stages:</p><p>Build – Compiles the application.</p><p>Test – Executes automated tests after the build stage completes successfully.</p><p>GitLab executes stages sequentially. The test stage will not begin until the build stage has finished successfully.</p><p>Creating the Build Job</p><p>Next, define a job that belongs to the build stage.</p><p>build_job: stage: build script: - echo &quot;Building the application...&quot; - mvn clean package</p><p>This job performs two actions:</p><p>Displays a message in the pipeline log.</p><p>Uses Apache Maven to compile the project and generate the application artifact.</p><p>Creating the Test Job</p><p>Now define the testing job.</p><p>test_job: stage: test script: - echo &quot;Running application tests...&quot; - mvn test</p><p>This job runs only after the build stage completes successfully.</p><p>Separating build and test into different jobs makes the pipeline easier to maintain, troubleshoot, and extend as additional stages are introduced later in the project.</p><p>Committing and Pushing the Changes</p><p>After saving the .gitlab-ci.yml file, commit and push the changes to your GitLab repository.</p><p>git add . git commit -m &quot;Create first GitLab CI/CD pipeline&quot; git push origin main</p><p>Pushing the changes automatically triggers the pipeline because GitLab continuously monitors the repository for new commits.</p><p>Verifying the Pipeline</p><p>Navigate to your GitLab project and open:</p><p>Build → Pipelines</p><p>You should see a newly created pipeline executing the Build and Test jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQp2qkfQ2XVftRo5k0fdIw.png" /><figcaption>Figure 2: The first successful GitLab CI/CD pipeline after pushing the project to the repository.</figcaption></figure><p>If both jobs complete successfully, your first GitLab CI/CD pipeline is now operational.</p><p>This milestone confirms that GitLab is correctly reading the .gitlab-ci.yml file, executing pipeline stages in sequence, and automating the build and testing process.</p><p>Step 2: Managing Secure Configuration with GitLab CI/CD Variables</p><p>As CI/CD pipelines become more sophisticated, hardcoding configuration values such as credentials, API keys, tokens, or environment-specific settings directly into the pipeline is a poor security practice. GitLab addresses this challenge by providing CI/CD Variables, which allow sensitive and reusable values to be stored securely outside the pipeline configuration.</p><p>In this step, we&#39;ll configure custom variables, explore GitLab&#39;s predefined variables, and update our pipeline to use them.</p><p>What Are GitLab CI/CD Variables?</p><p>GitLab CI/CD Variables are key-value pairs that can be accessed by jobs during pipeline execution. They help you:</p><p>Store sensitive information securely.</p><p>Avoid hardcoding values in .gitlab-ci.yml.</p><p>Reuse configuration across multiple jobs.</p><p>Simplify pipeline maintenance.</p><p>Improve security by masking confidential data.</p><p>GitLab provides two categories of variables:</p><p>Predefined Variables – Automatically created by GitLab and available during pipeline execution.</p><p>Custom Variables – Created by the project owner to store application-specific values.</p><p>Creating Custom Variables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YbQI1YUqrKp7_BHOYJP_g.png" /><figcaption>Figure 3: Configuring secure CI/CD variables in the GitLab project settings.</figcaption></figure><p>To create a custom variable:</p><p>Open your GitLab project.</p><p>Navigate to Settings → CI/CD.</p><p>Expand the Variables section.</p><p>Click Add Variable.</p><p>Enter the variable name and value.</p><p>Save the configuration.</p><p>For this project, we created variables such as:</p><p>JAVA_OPTS</p><p>MY_SECRET</p><p>These variables can now be referenced securely within the pipeline without exposing their values in the repository.</p><p>Using Variables in the Pipeline</p><p>Once defined, variables can be referenced directly inside the .gitlab-ci.yml file.</p><p>For example:</p><p>script: - echo &quot;$JAVA_OPTS&quot;</p><p>GitLab automatically substitutes the variable value during pipeline execution.</p><p>This approach keeps the pipeline configuration clean while ensuring sensitive values remain protected.</p><p>Exploring GitLab Predefined Variables</p><p>In addition to custom variables, GitLab automatically provides a rich collection of predefined variables during every pipeline execution.</p><p>Some commonly used examples include:</p><p>CI_PROJECT_NAME</p><p>CI_PROJECT_PATH</p><p>CI_COMMIT_BRANCH</p><p>CI_COMMIT_SHA</p><p>CI_PIPELINE_ID</p><p>CI_JOB_NAME</p><p>These variables provide useful metadata about the current project, commit, branch, job, and pipeline, making it easy to create dynamic and reusable CI/CD workflows.</p><p>Verifying the Pipeline</p><p>After adding the variables and updating the pipeline configuration:</p><p>Commit the changes.</p><p>Push them to the GitLab repository.</p><p>Navigate to Build → Pipelines.</p><p>Open the latest pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6t1oRtO5PnwchR-A3oX7eQ.png" /><figcaption>Figure 4: Successful pipeline execution after integrating GitLab CI/CD variables.</figcaption></figure><p>Review the job logs to confirm the variables are being used correctly.</p><p>A successful pipeline verifies that both custom and predefined variables have been configured correctly and are available during job execution.</p><p>Why CI/CD Variables Matter</p><p>Managing configuration through GitLab CI/CD Variables offers several advantages:</p><p>Improves security by keeping sensitive information out of source control.</p><p>Makes pipelines easier to maintain.</p><p>Promotes configuration reuse across multiple jobs and environments.</p><p>Supports production-ready DevOps practices.</p><p>Enables secure integration with external services such as Docker registries, cloud providers, and deployment platforms.</p><p>As pipelines grow more complex, CI/CD Variables become an essential building block for creating secure, flexible, and maintainable automation workflows.</p><p>Step 3: Implementing Conditional Pipelines with Rules and Merge Requests</p><p>As CI/CD pipelines evolve, not every job should run for every commit. For example, you may want a deployment job to run only when changes are merged into the main branch, or you may want to skip certain jobs when working on feature branches.</p><p>GitLab addresses this requirement through the rules: keyword, which enables conditional job execution based on predefined conditions such as the branch name, pipeline source, or commit details.</p><p>In this step, we&#39;ll configure pipeline rules and implement a feature branch workflow using GitLab Merge Requests.</p><p>Understanding GitLab Rules</p><p>The rules: keyword allows GitLab to determine whether a job should run based on specified conditions.</p><p>Instead of executing every job for every pipeline, GitLab evaluates each rule in order and runs the job only when a matching condition is found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhRAytByHPE7oz-_-JVJAA.png" /><figcaption>Figure 5: Pipeline execution after implementing conditional job execution with GitLab Rules.</figcaption></figure><p>For example, the following configuration ensures that a job runs only when changes are pushed to the main branch:</p><p>rules: - if: &#39;$CI_COMMIT_BRANCH == &quot;main&quot;&#39;</p><p>This approach provides greater flexibility than older keywords such as only: and except: and is now considered the recommended method for controlling pipeline execution.</p><p>Why Use Rules?</p><p>Using rules: offers several advantages:</p><p>Reduces unnecessary pipeline executions.</p><p>Saves CI/CD runner resources.</p><p>Speeds up pipeline completion.</p><p>Supports different workflows for feature branches and production branches.</p><p>Provides fine-grained control over job execution.</p><p>These benefits become increasingly important as pipelines grow in complexity.</p><p>Working with Feature Branches</p><p>A common Git workflow is to create a dedicated feature branch for every new enhancement or bug fix.</p><p>For example:</p><p>git checkout -b feature-91</p><p>Development work is performed on the feature branch without affecting the main branch.</p><p>After making the required changes:</p><p>git add . git commit -m &quot;Implement pipeline rules&quot; git push origin feature-91</p><p>Pushing the feature branch uploads the changes to GitLab, where they can be reviewed before being merged.</p><p>Creating a Merge Request</p><p>Once development is complete, create a Merge Request in GitLab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJY9wZCYArw6gJ4hWZyb5A.png" /><figcaption>Figure 6: Creating a Merge Request to review and merge feature branch changes into the main branch.</figcaption></figure><p>A Merge Request allows team members to:</p><p>Review the code.</p><p>Discuss proposed changes.</p><p>Verify pipeline results.</p><p>Approve the implementation before merging.</p><p>This review process improves collaboration and helps maintain code quality.</p><p>After the Merge Request is approved, merge the feature branch into the main branch.</p><p>GitLab automatically triggers a new pipeline based on the rules defined in the .gitlab-ci.yml file.</p><p>Verifying the Workflow</p><p>After completing the Merge Request:</p><p>Confirm that the feature branch behaves according to the configured rules.</p><p>Verify that the pipeline executes successfully after merging into the main branch.</p><p>Review the pipeline graph to ensure all expected jobs have been triggered.</p><p>This confirms that the conditional pipeline logic is functioning as intended.</p><p>Key Takeaways</p><p>By implementing rules: and adopting a Merge Request workflow, you&#39;ve introduced several production-ready DevOps practices into your project:</p><p>Conditional pipeline execution.</p><p>Feature branch development.</p><p>Collaborative code review.</p><p>Controlled integration into the main branch.</p><p>More efficient use of CI/CD resources.</p><p>These practices are widely adopted in enterprise software development and form an essential part of modern GitLab CI/CD workflows.</p><p>Step 4: Implementing Artifacts, Job Dependencies, Security Scanning with Trivy, and Pipeline Notifications</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*Io6pGOy056P10lbfYL0y9w.jpeg" /></figure><p>As CI/CD pipelines become more advanced, efficiently managing build outputs, reducing pipeline execution time, and integrating security checks become increasingly important. GitLab provides several built-in features that help achieve these objectives, including artifacts, job dependencies, and pipeline notifications.</p><p>In this step, we&#39;ll enhance our pipeline by preserving build artifacts, optimizing job execution using the needs: keyword, integrating Trivy for automated vulnerability scanning, and configuring notifications for improved pipeline visibility.</p><p>Preserving Build Outputs with Artifacts</p><p>During the build stage, Apache Maven generates a deployable WAR file that is required by subsequent pipeline stages. Instead of rebuilding the application multiple times, GitLab allows us to preserve the generated files as artifacts.</p><p>Artifacts are files produced by one job that can be downloaded or consumed by later jobs within the same pipeline.</p><p>A typical artifact configuration looks like this:</p><p>artifacts: paths: - target/*.war</p><p>With this configuration, GitLab stores the generated WAR file after the build job completes, making it available to downstream jobs.</p><p>Benefits of Artifacts</p><p>Using artifacts provides several advantages:</p><p>Eliminates unnecessary rebuilds.</p><p>Improves pipeline efficiency.</p><p>Preserves important build outputs.</p><p>Simplifies debugging and troubleshooting.</p><p>Enables downstream jobs to reuse generated files.</p><p>Optimizing Pipeline Execution with needs:</p><p>By default, GitLab executes jobs stage by stage. While this approach is simple, it may increase the total pipeline execution time.</p><p>GitLab&#39;s needs: keyword allows a job to start immediately after its required dependency completes successfully, rather than waiting for every job in the previous stage to finish.</p><p>For example:</p><p>test_job: needs: - build_job</p><p>This dependency-based execution model creates a more efficient pipeline and reduces overall build time.</p><p>Why Use needs:?</p><p>Implementing needs: offers several benefits:</p><p>Faster pipeline execution.</p><p>Better utilization of GitLab runners.</p><p>Reduced waiting time between jobs.</p><p>Improved scalability for larger CI/CD pipelines.</p><p>Integrating Trivy for Automated Security Scanning</p><p>Security should be integrated early in the software development lifecycle rather than treated as a final deployment step. This principle is commonly known as Shift Left Security.</p><p>To implement this practice, we integrated Trivy, an open-source vulnerability scanner, into the GitLab CI/CD pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdEFCMcbjMmFRmbpPyX3Ww.png" /><figcaption>Figure 7: Adding a dedicated Trivy security scanning stage to strengthen the CI/CD pipeline.</figcaption></figure><p>The security scan stage analyzes project dependencies and identifies known vulnerabilities before the application progresses further through the pipeline.</p><p>By performing automated vulnerability scanning during Continuous Integration, development teams can detect security issues early, reducing the cost and effort required to remediate them later.</p><p>Configuring Pipeline Notifications</p><p>Monitoring pipeline status is essential for maintaining software quality and responding quickly to failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYkmOSBv7hNICCtVzePiNw.png" /><figcaption>Figure 8: Configuring a notification stage to improve pipeline monitoring and visibility.</figcaption></figure><p>To improve visibility, a notification stage was added to the pipeline. Notifications can be configured to alert team members whenever a pipeline succeeds or fails, enabling faster troubleshooting and more effective collaboration.</p><p>In production environments, these notifications are commonly integrated with platforms such as Slack, Microsoft Teams, or email services.</p><p>Troubleshooting the Trivy Security Scan</p><p>During implementation, the Trivy security scan encountered an external limitation while retrieving dependency metadata from Maven Central.</p><p>The pipeline reported an HTTP 429 (Too Many Requests) response, indicating that Maven Central had temporarily rate-limited requests originating from the shared GitLab runner.</p><p>This issue was not caused by an error in the pipeline configuration or Trivy itself. Instead, it was the result of temporary rate limiting imposed by the external Maven repository.</p><p>Understanding how to distinguish between configuration issues and external service limitations is an important DevOps troubleshooting skill.</p><p>Key Takeaways</p><p>By completing this step, we&#39;ve significantly enhanced the CI/CD pipeline by introducing modern DevSecOps capabilities.</p><p>The pipeline can now:</p><p>Preserve build outputs using GitLab Artifacts.</p><p>Optimize execution through job dependencies.</p><p>Perform automated vulnerability scanning with Trivy.</p><p>Improve operational visibility through pipeline notifications.</p><p>Detect security issues early in the software delivery lifecycle.</p><p>Apply production-oriented CI/CD and DevSecOps best practices.</p><p>Step 5: Building and Publishing Docker Images to the GitLab Container Registry</p><p>With the build, testing, and security stages successfully implemented, the final step is to package the application as a Docker image and publish it to the GitLab Container Registry.</p><p>Containerizing applications ensures consistency across development, testing, and production environments. Instead of deploying application files directly, we package the application and all its runtime dependencies into a portable Docker image that can run consistently on any Docker-compatible platform.</p><p>GitLab simplifies this process by providing a fully integrated Container Registry and predefined CI/CD variables for authentication, allowing Docker images to be built and published without exposing sensitive credentials.</p><p>Why Use the GitLab Container Registry?</p><p>The GitLab Container Registry is a built-in Docker image repository that is tightly integrated with GitLab projects.</p><p>Some of its advantages include:</p><p>Secure Docker image storage.</p><p>Native integration with GitLab CI/CD.</p><p>Authentication using predefined GitLab CI/CD variables.</p><p>Versioned Docker image tagging.</p><p>Simplified image management within the GitLab ecosystem.</p><p>Using the built-in registry eliminates the need for external container repositories during development while providing a seamless experience for storing and managing container images.</p><p>Building Docker Images with Docker-in-Docker (DinD)</p><p>GitLab shared runners do not run a Docker daemon by default. To enable Docker commands such as docker build and docker push, GitLab provides Docker-in-Docker (DinD) as a service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-hc4sX276tUN6A11MCc7A.png" /><figcaption>Figure 9: Configuring the Docker build and publish job within the GitLab CI/CD pipeline.</figcaption></figure><p>In this configuration:</p><p>The Docker CLI runs inside the CI/CD job container.</p><p>A separate Docker daemon runs as a service container.</p><p>The Docker CLI communicates with the Docker daemon to build and publish container images.</p><p>This architecture enables Docker operations while maintaining isolation between the job container and the Docker service.</p><p>Updating the Dockerfile</p><p>To support automated container builds, the application uses a multi-stage Dockerfile.</p><p>The first stage uses Maven to compile the Java application and generate the deployable WAR file.</p><p>The second stage uses an Apache Tomcat runtime image and copies the generated WAR file into the Tomcat web application directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnu_O4qg_FidgK9n_oLwAA.png" /><figcaption>Figure 10: Verifying the multi-stage Dockerfile used to build and package the Java web application.</figcaption></figure><p>This approach offers several advantages:</p><p>Smaller final Docker image.</p><p>Faster image downloads.</p><p>Improved security by excluding build tools from the runtime image.</p><p>Better maintainability through separation of build and runtime environments.</p><p>Authenticating with the GitLab Container Registry</p><p>Instead of hardcoding registry credentials, GitLab provides predefined CI/CD variables that securely authenticate the pipeline with the Container Registry.</p><p>During pipeline execution, Docker logs into the registry using these predefined variables before building and pushing the image.</p><p>This approach:</p><p>Protects sensitive credentials.</p><p>Eliminates manual authentication.</p><p>Supports secure, automated image publishing.</p><p>Building and Publishing the Docker Image</p><p>Once authentication is complete, the pipeline performs the following tasks:</p><p>Builds the Docker image using the project&#39;s multi-stage Dockerfile.</p><p>Tags the image using the current commit SHA.</p><p>Publishes the image to the GitLab Container Registry.</p><p>Using the commit SHA as the image tag provides traceability, making it easy to identify which source code revision produced a specific container image.</p><p>Verifying the Published Image</p><p>After the pipeline completes successfully, navigate to:</p><p>Deploy → Container Registry</p><p>Within the GitLab project.</p><p>The published Docker image should appear with its corresponding repository name and image tag.</p><p>From there, the image can be pulled and deployed to Docker hosts, Kubernetes clusters, or other container orchestration platforms.</p><p>Key Takeaways</p><p>By completing this final implementation step, you&#39;ve built a production-oriented CI/CD pipeline capable of:</p><p>Building a Java application with Apache Maven.</p><p>Executing automated tests.</p><p>Performing security scanning with Trivy.</p><p>Managing build artifacts efficiently.</p><p>Optimizing job execution with needs:.</p><p>Building Docker images using Docker-in-Docker (DinD).</p><p>Publishing versioned Docker images to the GitLab Container Registry.</p><p>Applying secure authentication through GitLab CI/CD predefined variables.</p><p>This end-to-end workflow demonstrates how GitLab&#39;s integrated DevOps platform can automate software delivery while incorporating modern CI/CD and DevSecOps best practices.</p><p>Troubleshooting</p><p>During the implementation of this project, several configuration and integration challenges were encountered. Identifying, understanding, and resolving these issues provided valuable insights into GitLab CI/CD, Docker, and DevSecOps practices.</p><p>1. Invalid YAML Configuration</p><p>One of the most common issues encountered during development was incorrect YAML syntax within the .gitlab-ci.yml file. Since GitLab validates the pipeline configuration before execution, even minor indentation errors or misplaced keywords prevented the pipeline from running successfully.</p><p>Resolution</p><p>Carefully reviewed the YAML indentation.</p><p>Verified the job hierarchy and keyword placement.</p><p>Committed and pushed the corrected configuration to trigger a new pipeline.</p><p>2. Pipeline Job Dependency Issues</p><p>As additional stages such as security scanning and Docker image publishing were introduced, some jobs failed to execute in the expected order due to incorrect dependency configuration.</p><p>Resolution</p><p>Configured job dependencies using the needs: keyword.</p><p>Verified that downstream jobs correctly consumed artifacts from previous stages.</p><p>Re-ran the pipeline to confirm the execution flow.</p><p>3. Docker Build Configuration</p><p>While integrating Docker image creation into the pipeline, the Dockerfile required modification to support GitLab CI/CD.</p><p>Instead of downloading the application source code during the image build process, the pipeline copies the project workspace into the Docker build context and uses a multi-stage Dockerfile to compile and package the application.</p><p>Resolution</p><p>Updated the Dockerfile to use a multi-stage build.</p><p>Copied the application source into the build stage.</p><p>Generated the WAR file with Maven.</p><p>Packaged the application into the Apache Tomcat runtime image.</p><p>4. Trivy Security Scan Rate Limiting</p><p>During the security scanning stage, Trivy occasionally failed while downloading dependency metadata from Maven Central.</p><p>The pipeline returned an HTTP 429 (Too Many Requests) response, indicating that Maven Central had temporarily rate-limited requests originating from the shared GitLab runner.</p><p>This was an external service limitation rather than a configuration error within GitLab CI/CD or Trivy.</p><p>Resolution</p><p>Verified that the Trivy configuration was correct.</p><p>Confirmed that the pipeline syntax and scanner configuration were functioning as expected.</p><p>Identified the issue as temporary rate limiting imposed by Maven Central on shared runner IP addresses.</p><p>Documented the limitation and recognized that using dependency caching or a private Maven repository can help reduce external requests in production environments.</p><p>Lessons from Troubleshooting</p><p>Every issue encountered during this project reinforced an important DevOps principle: successful CI/CD implementation involves more than writing pipeline code. It requires understanding pipeline execution, interpreting build logs, diagnosing failures, and distinguishing between configuration issues and external service limitations.</p><p>Developing these troubleshooting skills is essential for building reliable, production-ready CI/CD pipelines and is a key responsibility of modern DevOps engineers.</p><p>Key Takeaways</p><p>By completing this tutorial, you&#39;ve built more than just a CI/CD pipeline—you&#39;ve implemented a practical DevOps workflow that reflects many of the practices used in modern software engineering teams.</p><p>Here&#39;s a summary of the key concepts covered throughout the project:</p><p>Built a multi-stage GitLab CI/CD pipeline using the .gitlab-ci.yml configuration file.</p><p>Automated the build process for a Java application using Apache Maven.</p><p>Executed automated tests as part of the Continuous Integration workflow.</p><p>Managed sensitive configuration securely with GitLab CI/CD Variables.</p><p>Implemented conditional pipeline execution using the rules: keyword.</p><p>Adopted a feature branch workflow with GitLab Merge Requests for collaborative development.</p><p>Shared build outputs between jobs using GitLab Artifacts.</p><p>Optimized pipeline execution with the needs: keyword.</p><p>Integrated Trivy to perform automated vulnerability scanning as part of a DevSecOps workflow.</p><p>Built a Docker image using a multi-stage Dockerfile.</p><p>Published container images to the GitLab Container Registry.</p><p>Applied GitLab&#39;s predefined CI/CD variables for secure registry authentication.</p><p>Diagnosed and resolved real-world CI/CD issues, including YAML configuration errors, job dependency challenges, Docker integration, and external Maven Central rate limiting.</p><p>Why These Skills Matter</p><p>Modern DevOps engineers are expected to design, implement, and maintain secure, automated software delivery pipelines. This project demonstrates several of the core competencies that organizations look for, including:</p><p>Continuous Integration (CI)</p><p>Continuous Delivery (CD)</p><p>DevSecOps practices</p><p>Git workflow and collaborative development</p><p>Docker containerization</p><p>Secure credential management</p><p>CI/CD pipeline optimization</p><p>Automation and troubleshooting</p><p>These skills are applicable across organizations of all sizes and provide a strong foundation for more advanced topics such as Infrastructure as Code (Terraform), Configuration Management (Ansible), Kubernetes, and cloud-native deployment strategies.</p><p>Completing this project not only strengthens your understanding of GitLab CI/CD but also provides a practical portfolio project that showcases real-world DevOps implementation skills.</p><p>Conclusion</p><p>Building a CI/CD pipeline involves much more than automating a build process. It requires designing reliable workflows, securing sensitive information, optimizing pipeline execution, integrating security scanning, and packaging applications for consistent deployment.</p><p>In this tutorial, we successfully built an end-to-end GitLab CI/CD pipeline for a Java web application. Starting with a simple pipeline configuration, we progressively enhanced it by introducing GitLab CI/CD Variables, conditional execution with rules:, Merge Requests, artifacts, job dependencies using needs:, automated vulnerability scanning with Trivy, and Docker image publishing to the GitLab Container Registry.</p><p>Throughout the implementation, we also encountered real-world challenges, including YAML configuration issues and external Maven Central rate limiting during vulnerability scanning. Understanding how to diagnose and troubleshoot these scenarios is an essential DevOps skill and an important part of building production-ready CI/CD pipelines.</p><p>Although this project uses a Java application as the demonstration workload, the principles and techniques covered can be applied to many other programming languages and frameworks. The concepts of automation, security, containerization, and collaborative development remain the same across modern software delivery environments.</p><p>I hope this tutorial has helped you understand not only how to build a GitLab CI/CD pipeline but also why each stage plays an important role in creating secure, efficient, and maintainable software delivery workflows.</p><p>Thank you for reading. If you found this article helpful, consider following me on Medium for more hands-on DevOps tutorials covering GitLab CI/CD, GitHub Actions, Docker, Terraform, Ansible, Kubernetes, AWS, and other cloud-native technologies.</p><p>Happy learning, and see you in the next tutorial!</p><p>GitHub Repository</p><p>The complete source code, GitLab CI/CD pipeline configuration, Dockerfile, and project documentation used in this tutorial are available on GitHub.</p><p>Repository:</p><p>🔗 https://github.com/olajide-adedayo/gitlab-ci-cd-trivy-docker-container-registry</p><p>The repository includes:</p><p>Complete project source code</p><p>.gitlab-ci.yml pipeline configuration</p><p>Multi-stage Dockerfile</p><p>Comprehensive project README</p><p>Architecture overview</p><p>Project screenshots</p><p>Troubleshooting documentation</p><p>Lessons learned and best practices</p><p>If you found this tutorial helpful, consider:</p><p>⭐ Starring the repository</p><p>🍴 Forking the project to experiment with your own enhancements</p><p>💬 Sharing your feedback or suggestions</p><p>👏 Following me on Medium for more hands-on DevOps, DevSecOps, AWS, Docker, Terraform, Ansible, Kubernetes, GitHub Actions, and GitLab CI/CD tutorials</p><p>Thank you for taking the time to read this tutorial. I hope it helps you build a deeper understanding of modern CI/CD pipelines and inspires you to continue your DevOps learning journey.</p><p>About the Author</p><p>Hi, I&#39;m Olajide Adedayo, an AWS Cloud and DevOps Engineer with a passion for designing, automating, and optimizing modern software delivery pipelines.</p><p>I enjoy building hands-on projects that demonstrate real-world DevOps practices, including Continuous Integration and Continuous Delivery (CI/CD), Infrastructure as Code (IaC), containerization, cloud computing, configuration management, security automation, and monitoring.</p><p>Through my technical writing, I aim to simplify complex DevOps concepts into practical, step-by-step tutorials that help aspiring and experienced engineers strengthen their skills through real implementation projects.</p><p>Connect with Me</p><p>GitHub: https://github.com/olajide-adedayo</p><p>Medium: https://medium.com/@olajideadedayo230</p><p>LinkedIn:</p><p>Thank you for reading, and I hope this tutorial has been valuable. Feel free to connect with me, explore my projects, and follow my journey as I continue building and sharing practical DevOps solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d0de1b832f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerizing Java Applications with Docker and Publishing Images to Amazon ECR Using GitHub…]]></title>
            <link>https://medium.com/@olajideadedayo230/containerizing-java-applications-with-docker-and-publishing-images-to-amazon-ecr-using-github-28ed59c0cf9c?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/28ed59c0cf9c</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[amazon-ecr]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 17:17:20 GMT</pubDate>
            <atom:updated>2026-07-24T18:18:24.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4T9R7x1QYx1HfZUO6CsyvA.png" /></figure><p>Containerizing Java Applications with Docker and Publishing Images to Amazon ECR Using GitHub Actions</p><p>Learn how to build a production-oriented CI pipeline that automates Java application builds, security scanning with Trivy, Docker image creation, and secure image publishing to Amazon Elastic Container Registry (Amazon ECR) using GitHub Actions.</p><p>— -</p><p>Introduction</p><p>Modern software development relies heavily on automation to improve code quality, accelerate delivery, and reduce deployment risks. Rather than manually building applications, running tests, scanning for vulnerabilities, and publishing container images, development teams increasingly depend on Continuous Integration (CI) pipelines to perform these tasks automatically whenever code changes are introduced.</p><p>In this tutorial, you’ll learn how to build a production-oriented Continuous Integration (CI) pipeline using GitHub Actions for a Java application. The workflow automates application builds with Apache Maven, performs container vulnerability scanning using Trivy, builds a Docker image with a multi-stage Dockerfile, and securely publishes the image to Amazon Elastic Container Registry (Amazon ECR).</p><p>Throughout the implementation, security best practices are applied by using GitHub Environments, Secrets, and Variables to protect AWS credentials and configuration values. The result is a secure, automated, and production-ready workflow that demonstrates modern DevOps practices for containerized application delivery.</p><p>Whether you’re learning GitHub Actions, strengthening your DevOps skills, or building a cloud portfolio, this guide provides practical, hands-on experience that reflects real-world CI pipeline implementation.</p><p>— -</p><p>What You Will Build</p><p>In this tutorial, you will build a production-oriented Continuous Integration (CI) pipeline using GitHub Actions that automates the process of building, validating, securing, containerizing, and publishing a Java application.</p><p>By the end of this guide, you will have implemented a workflow capable of:</p><p>- Automatically triggering pipeline execution when code is pushed to the repository.<br>- Building the Java application using Apache Maven.<br>- Running automated application tests.<br>- Performing container vulnerability scanning with Trivy.<br>- Publishing security scan reports as workflow artifacts.<br>- Building a production-ready Docker image using a multi-stage Dockerfile.<br>- Authenticating securely with AWS using GitHub Environments, Secrets, and Variables.<br>- Publishing Docker images to Amazon Elastic Container Registry (Amazon ECR).<br>- Tagging Docker images using the Git commit SHA (“github.sha”) to enable immutable image versioning.<br>- Implementing a secure and automated CI pipeline that aligns with modern DevOps engineering best practices.</p><p>At the end of the implementation, every successful workflow execution produces a validated, security-scanned, and versioned Docker image that is automatically published to Amazon ECR and ready for deployment.</p><p>Solution Architecture</p><p>The solution implements a production-oriented Continuous Integration (CI) pipeline using GitHub Actions to automate the software delivery process for a Java application.</p><p>Whenever code is pushed to the GitHub repository, GitHub Actions automatically triggers the workflow. The application is built using Apache Maven, validated through automated tests, and scanned for security vulnerabilities using Trivy. If all stages complete successfully, a multi-stage Docker build creates a production-ready container image.</p><p>To ensure secure access to AWS resources, the workflow authenticates using GitHub Environments, Secrets, and Variables. The Docker image is then tagged with the Git commit SHA (“github.sha”) and published to Amazon Elastic Container Registry (Amazon ECR), providing an immutable and versioned container image ready for deployment.</p><p>This architecture follows modern DevOps best practices by integrating automation, security, containerization, and cloud-native image management into a single, repeatable Continuous Integration workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzME_7-dKthrUCJpz-L7Ug.png" /><figcaption>Figure 1: GitHub Actions CI Pipeline Architecture for Building, Scanning, Containerizing, and Publishing Java Applications to Amazon ECR.</figcaption></figure><p>Prerequisites</p><p>Before getting started, ensure you have the following knowledge, tools, and resources available:</p><p>Knowledge</p><p>- Basic understanding of Git and GitHub<br>- Basic familiarity with Java applications<br>- Fundamental knowledge of Docker containers<br>- Basic understanding of Continuous Integration (CI) concepts<br>- Familiarity with AWS services is beneficial but not mandatory</p><p>Tools</p><p>- Git<br>- GitHub Account<br>- GitHub Actions<br>- Docker<br>- Apache Maven<br>- Java 17<br>- AWS Account<br>- Amazon Elastic Container Registry (Amazon ECR)<br>- Visual Studio Code (or any preferred code editor)</p><p>AWS Requirements</p><p>Create the following AWS resources before starting:</p><p>- An Amazon Elastic Container Registry (Amazon ECR) repository<br>- An IAM user with permissions to push images to Amazon ECR<br>- AWS Access Key ID<br>- AWS Secret Access Key</p><p>GitHub Requirements</p><p>Configure the following in your GitHub repository:</p><p>- GitHub Environments<br>- GitHub Secrets<br>- GitHub Variables</p><p>Having these prerequisites in place will allow you to follow the implementation seamlessly while focusing on understanding the GitHub Actions workflow and CI pipeline automation.</p><p>Step 1: Creating the GitHub Actions Workflow</p><p>Objective</p><p>Create a GitHub Actions workflow that automatically executes a Continuous Integration (CI) pipeline whenever changes are pushed to the repository or when a pull request is created.</p><p>Why This Step Matters</p><p>GitHub Actions provides native CI/CD capabilities within GitHub, allowing development teams to automate repetitive tasks such as building applications, running tests, performing security scans, and publishing deployment artifacts.</p><p>Instead of manually executing these tasks after every code change, GitHub Actions automatically triggers the workflow based on predefined events. This improves consistency, reduces human error, and accelerates software delivery.</p><p>Workflow Triggers</p><p>The workflow in this project is configured to execute under the following conditions:</p><p>- Push Events — Automatically starts the pipeline whenever code is pushed to the configured branch.<br>- Pull Request Events — Validates proposed changes before they are merged into the main branch.<br>- Manual Execution (“workflow_dispatch”) — Allows the workflow to be started manually from the GitHub Actions interface whenever required.</p><p>These triggers ensure that every significant code change is automatically validated through the CI pipeline while also providing the flexibility to execute the workflow on demand.</p><p>Outcome</p><p>At the end of this step, the GitHub repository is equipped with an automated workflow that serves as the foundation for building, testing, securing, containerizing, and publishing the application throughout the remainder of the implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3ZMgo7H6FV9vHTM6swGEA.png" /><figcaption>Figure 2: Creating the “.github/workflows” directory for the GitHub Actions workflow.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXfd_jWqWAWanbD-DlMiVg.png" /><figcaption>Figure 3: Creating the “main.yml” workflow file that defines the GitHub Actions Continuous Integration (CI) pipeline.</figcaption></figure><p>Step 2: Configuring Workflow Triggers</p><p>Objective</p><p>Configure the GitHub Actions workflow to execute automatically in response to specific repository events and to support manual execution when required.</p><p>Why This Step Matters</p><p>Workflow triggers determine when a GitHub Actions pipeline should run. By defining appropriate events, development teams can automate validation processes, reduce manual effort, and ensure code quality throughout the software development lifecycle.</p><p>In this project, the workflow is configured to support three execution methods:</p><p>- Push Event (“push”) — Automatically starts the workflow whenever changes are pushed to the repository.<br>- Pull Request Event (“pull_request”) — Validates proposed code changes before they are merged into the main branch.<br>- Manual Trigger (“workflow_dispatch”) — Enables developers to manually execute the workflow directly from the GitHub Actions interface whenever necessary.</p><p>This combination provides both automation and flexibility, ensuring that application builds, testing, security scanning, and container image publishing can be performed consistently and on demand.</p><p>Outcome</p><p>At the end of this step, the GitHub Actions workflow is configured to respond automatically to key repository events while also supporting manual execution for testing, maintenance, and operational tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAIwqsQbw7UoNkdxxPYnZA.png" /><figcaption>Figure 4: Creating a pull request to validate code changes through the GitHub Actions workflow.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7NZzVrDlYBAvxDkVut3Jw.png" /><figcaption>Figure 5: GitHub Actions workflow automatically triggered in response to the pull request event.</figcaption></figure><p>Step 3: Configuring Repository Permissions, Workflow Artifacts, and Conditions</p><p>Objective</p><p>Enhance the GitHub Actions workflow by implementing secure repository permissions, artifact management, and conditional execution to improve security, traceability, and workflow efficiency.</p><p>Why This Step Matters</p><p>As CI pipelines become more advanced, it is important to control what the workflow can access, preserve important build outputs, and ensure that specific jobs execute only when predefined conditions are satisfied.</p><p>In this project, three important GitHub Actions capabilities were implemented:</p><p>Repository Permissions</p><p>Repository permissions were configured to ensure the workflow receives only the minimum level of access required to perform its tasks. Applying the principle of least privilege helps reduce security risks while protecting repository resources.</p><p>Workflow Artifacts</p><p>Workflow artifacts were configured to preserve important outputs generated during pipeline execution. These artifacts can be downloaded after each workflow run, making it easier to review build outputs, analyze security scan results, and troubleshoot failures when necessary.</p><p>Conditional Workflow Execution</p><p>Conditional expressions were used to control when specific jobs should execute. This ensures that sensitive operations, such as publishing Docker images, occur only after prerequisite jobs complete successfully and when the workflow is running under the appropriate conditions.</p><p>By combining permissions, artifacts, and conditional execution, the pipeline becomes more secure, maintainable, and aligned with production DevOps practices.</p><p>Outcome</p><p>At the end of this step, the GitHub Actions workflow incorporates secure access controls, artifact retention, and intelligent job execution, resulting in a more reliable and production-oriented Continuous Integration (CI) pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmoTC11dqvWycNB7wk8wdQ.png" /><figcaption>Figure 6: Configuring repository permissions for the GitHub Actions workflow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RnRzqZj48Df2sZ2XPw64fw.png" /><figcaption>Figure 7: Configuring workflow artifact upload to preserve build outputs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJv7wvK9DhiNauj4x1RhYg.png" /><figcaption>Figure 8: Configuring failure conditions to control workflow execution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkJ8_xGATGO4-KEtSNKqBg.png" /><figcaption>Figure 9: Configuring branch-based conditions for controlled job execution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NO7YklY3pG7Rdh9TBMVtjQ.png" /><figcaption>Figure 10: Successful implementation of repository permission, workflow artifacts, and conditional execution</figcaption></figure><p>Step 4: Integrating Security Scanning with Trivy</p><p>Objective</p><p>Integrate Trivy into the GitHub Actions workflow to automatically scan the application for security vulnerabilities before building and publishing the Docker image.</p><p>Why This Step Matters</p><p>Security is a fundamental aspect of modern DevOps practices. Rather than identifying vulnerabilities after deployment, organizations increasingly adopt a Shift Left Security approach, where security checks are incorporated early in the software development lifecycle.</p><p>In this project, Trivy is integrated into the GitHub Actions workflow to automatically perform vulnerability scanning during every pipeline execution. This ensures that potential security issues are detected before container images are published to Amazon Elastic Container Registry (Amazon ECR).</p><p>The scan results are also uploaded as workflow artifacts, allowing developers to review findings, investigate potential risks, and maintain an audit trail of each workflow execution.</p><p>Automating security scanning within the CI pipeline improves application security, reduces deployment risks, and supports the delivery of more secure container images.</p><p>Outcome</p><p>At the end of this step, the GitHub Actions workflow automatically performs vulnerability scanning, generates security reports, and publishes the scan results as workflow artifacts before the Docker image is built and pushed to Amazon ECR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZYCA74xgxewQDhV_d1VLg.png" /><figcaption>**Figure 11:** Creating the Trivy security scanning job in the GitHub Actions workflow.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQWakHRNhriSWrkxtM64hQ.png" /><figcaption>**Figure 12:** Configuring Trivy to automatically scan the application for security vulnerabilities during workflow execution.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_HtCHiqQKjeelc9muPkBg.png" /><figcaption>**Figure 13:** Configuring workflow artifacts to upload and retain Trivy security scan reports.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RVqlOxJagI47hCPZCeTtw.png" /><figcaption>**Figure 14:** Successful completion of the Trivy security scanning job with vulnerability scan results generated.</figcaption></figure><p>Step 5: Containerizing the Application with Docker</p><p>Objective</p><p>Create a multi-stage Dockerfile to package the Java application into a lightweight, production-ready Docker image.</p><p>Why This Step Matters</p><p>Containerization enables applications to run consistently across different environments by packaging the application together with its runtime and dependencies. Docker has become the industry standard for building, distributing, and running containerized applications.</p><p>In this project, a multi-stage Docker build is used to separate the application build process from the final runtime environment. The first stage compiles and packages the Java application using Apache Maven, while the second stage creates a lightweight runtime image containing only the files required to run the application.</p><p>This approach reduces image size, improves security by excluding unnecessary build tools, and produces a cleaner, production-ready container image.</p><p>After creating the Dockerfile, it is updated to ensure compatibility with the GitHub Actions workflow and the project’s Java version requirements, enabling successful automated builds within the CI pipeline.</p><p>Outcome</p><p>At the end of this step, the application is successfully containerized using a multi-stage Dockerfile, producing an optimized Docker image ready for automated publishing to Amazon Elastic Container Registry (Amazon ECR).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9R9xM8VQyM1T-zLTIaQA3w.png" /><figcaption>**Figure 15:** Multi-stage Dockerfile added to the project to containerize the Java application.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6yyIP9slvymLshOv6pljw.png" /><figcaption>**Figure 16:** Dockerfile updated to support automated builds within the GitHub Actions CI pipeline.</figcaption></figure><p>Step 6: Publishing Docker Images to Amazon Elastic Container Registry (Amazon ECR)</p><p>Objective</p><p>Configure GitHub Actions to securely authenticate with AWS and automatically publish Docker images to Amazon Elastic Container Registry (Amazon ECR).</p><p>Why This Step Matters</p><p>Building a Docker image is only part of a modern CI pipeline. To make the image available for deployment, it must be stored in a secure and reliable container registry.</p><p>Amazon Elastic Container Registry (Amazon ECR) is a fully managed AWS service that provides a secure repository for storing, managing, and distributing Docker container images. By integrating GitHub Actions with Amazon ECR, every successful workflow execution automatically produces a versioned container image that is immediately available for deployment.</p><p>To protect sensitive credentials, the workflow uses GitHub Environments, Secrets, and Variables instead of hardcoding AWS authentication details. An AWS Identity and Access Management (IAM) user with appropriate permissions is created specifically for the workflow, and its access keys are securely stored as GitHub Secrets.</p><p>During the workflow execution, GitHub Actions authenticates with Amazon ECR, builds the Docker image, tags it using the Git commit SHA (“github.sha”), and pushes the image to the Amazon ECR repository. This approach provides immutable image versioning, improves traceability, and aligns with production DevOps best practices.</p><p>Outcome</p><p>At the end of this step, every successful execution of the GitHub Actions workflow automatically builds, tags, and publishes a production-ready Docker image to Amazon Elastic Container Registry (Amazon ECR), making it available for downstream deployment processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfrDWFMmHCWjH7qUJBeTBA.png" /><figcaption>**Figure 17:** Amazon Elastic Container Registry (Amazon ECR) repository created to store Docker images.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OTx-sQIkQHuAKsEgpeeLg.png" /><figcaption>**Figure 18:** IAM user created with permissions required for GitHub Actions to publish Docker images to Amazon ECR.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNfDZySE_F9nB-Ps584upg.png" /><figcaption>**Figure 19:** AWS access keys generated for secure authentication between GitHub Actions and Amazon ECR.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J91npBHGSHA47IpYZXziWw.png" /><figcaption>**Figure 20:** GitHub Production Environment configured to protect deployment credentials.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eokbR6xckSsdC7hr9UCP-w.png" /><figcaption>**Figure 21:** AWS credentials securely stored as GitHub Environment Secrets.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZOTGF7VEHdo591uSCYxVg.png" /><figcaption>**Figure 22:** GitHub Environment Variable configured to define the AWS Region used by the workflow.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zT1Cq8UGdvkvmMK_X24ZRQ.png" /><figcaption>**Figure 23:** GitHub Actions workflow successfully completed the Docker build and Amazon ECR publishing process.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBaLX_6G__k0zf1e0E10WQ.png" /><figcaption>**Figure 24:** Docker image successfully published to Amazon Elastic Container Registry (Amazon ECR).</figcaption></figure><p>— -</p><p>Troubleshooting</p><p>During the implementation of this project, I encountered several real-world challenges that are common when building production-oriented CI pipelines. The following issues and resolutions may help you troubleshoot similar problems in your own environment.</p><p>1. Docker Build Failed Because the Base Image Was Unavailable</p><p>Issue</p><p>The Docker image build failed because the original “openjdk:11” base image referenced in the Dockerfile was no longer available.</p><p>Resolution</p><p>The Dockerfile was updated to use the actively maintained “eclipse-temurin:17” base image, which restored successful Docker image builds and aligned the build environment with the project’s Java version.</p><p>— -</p><p>2. Maven Compilation Failed with “invalid target release: 17”</p><p>Issue</p><p>The GitHub Actions workflow failed during the Maven build process with the following error:</p><p>“invalid target release: 17”</p><p>Resolution</p><p>The Docker build environment was using an older Java version than the project’s compiler configuration. Updating the Dockerfile to use Java 17 resolved the issue and ensured compatibility with the Maven build.</p><p>— -</p><p>3. Git Push Rejected Because the Remote Repository Was Ahead</p><p>Issue</p><p>Git rejected the push because the remote repository contained commits that were not available in the local repository.</p><p>Resolution</p><p>The latest changes were pulled from GitHub, the merge completed successfully, and the synchronized repository was pushed without further issues.</p><p>Each of these challenges provided valuable troubleshooting experience and reinforced the importance of understanding not only how to build CI pipelines, but also how to diagnose and resolve issues that arise during implementation.</p><p>— -</p><p>Key Takeaways</p><p>This project demonstrates how GitHub Actions can be used to build a secure, automated, and production-oriented Continuous Integration (CI) pipeline for Java applications.</p><p>Throughout the implementation, we covered several important DevOps concepts, including:</p><p>- Automating application builds with GitHub Actions and Apache Maven.<br>- Configuring workflow triggers for push, pull request, and manual execution.<br>- Applying the principle of least privilege through GitHub Environments, Secrets, and Variables.<br>- Integrating Trivy to perform automated container vulnerability scanning.<br>- Building production-ready Docker images using a multi-stage Dockerfile.<br>- Publishing Docker images securely to Amazon Elastic Container Registry (Amazon ECR).<br>- Troubleshooting real-world CI pipeline issues and applying practical solutions.</p><p>By combining automation, security, containerization, and AWS cloud services, this project reflects the workflow commonly used by modern DevOps teams to deliver reliable, repeatable, and secure software releases.</p><p>— -</p><p>Conclusion</p><p>Building a modern CI pipeline involves much more than simply automating application builds. It requires secure credential management, automated testing, vulnerability scanning, containerization, and reliable artifact publishing.</p><p>In this tutorial, we implemented each of these capabilities using GitHub Actions, Apache Maven, Docker, Trivy, and Amazon Elastic Container Registry (Amazon ECR), resulting in a production-oriented workflow that follows DevOps best practices.</p><p>I hope this guide helps you better understand how these technologies work together to automate software delivery. If you found this article helpful, consider exploring the complete project on GitHub, connecting with me on LinkedIn, and following me on Medium for more hands-on DevOps, AWS, and Cloud Engineering tutorials.</p><p>— -</p><p>About the Author</p><p>Hi, I’m Olajide Adedayo, an AWS Cloud and DevOps Engineer with a passion for designing secure, automated, and production-ready cloud solutions.</p><p>I enjoy building and documenting hands-on projects that demonstrate real-world DevOps practices, including Continuous Integration (CI), Continuous Delivery (CD), Infrastructure as Code (IaC), containerization, cloud computing, and automation on Amazon Web Services (AWS).</p><p>My goal is to share practical implementation experiences that help engineers, students, and technology professionals strengthen their cloud and DevOps skills through real-world projects and best practices.</p><p>Connect with Me</p><p>- GitHub: <a href="https://github.com/olajide-adedayo">https://github.com/olajide-adedayo</a>/action-profile<br>- LinkedIn: <a href="https://www.linkedin.com/in/olajide-adedayo-9126593b3/">https://www.linkedin.com/in/olajide-adedayo-9126593b3/</a></p><p>Thank you for reading! I hope this tutorial helps you build practical DevOps skills and inspires you to continue your cloud engineering journey. Stay tuned for more hands-on AWS and DevOps projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28ed59c0cf9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Jenkins Build Triggers: GitHub Webhooks, Poll SCM, Scheduled Builds, and Remote API…]]></title>
            <link>https://medium.com/@olajideadedayo230/mastering-jenkins-build-triggers-github-webhooks-poll-scm-scheduled-builds-and-remote-api-22c44d5a7638?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/22c44d5a7638</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 16:52:40 GMT</pubDate>
            <atom:updated>2026-07-19T16:52:40.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgIkXPJCSzDpPZV4Poc2Eg.jpeg" /></figure><p>Mastering Jenkins Build Triggers: GitHub Webhooks, Poll SCM, Scheduled Builds, and Remote API Automation</p><p>Automate Jenkins pipelines using event-driven, scheduled, polling, and remote build triggers with hands-on implementation on AWS.</p><p>Continuous Integration (CI) is most effective when builds are triggered automatically instead of relying on manual execution. Jenkins provides several build trigger mechanisms that allow pipelines to respond to source code changes, scheduled tasks, repository polling, and external API requests.</p><p>In this tutorial, you’ll learn how to configure and test four commonly used Jenkins build triggers:</p><p>- GitHub Webhooks</p><p>- Poll SCM</p><p>- Build Periodically</p><p>- Remote Build Trigger using the Jenkins Remote API</p><p>Throughout the guide, we’ll use a declarative Jenkins Pipeline hosted in a GitHub repository and a Jenkins server running on an Amazon EC2 instance. Each trigger mechanism will be configured, tested, and validated to demonstrate how Jenkins automates Continuous Integration workflows in real-world DevOps environments.</p><p>Whether you’re preparing for DevOps interviews, building your portfolio, or learning Jenkins automation, this hands-on tutorial will help you understand when and why each build trigger is used.</p><p>What You Will Learn</p><p>By the end of this tutorial, you will be able to:</p><p>- Configure GitHub Webhooks to trigger Jenkins builds automatically.</p><p>- Configure Poll SCM using Jenkins cron expressions.</p><p>- Schedule pipeline execution with Build Periodically.</p><p>- Configure Remote Build Trigger for external automation.</p><p>- Generate and use Jenkins API Tokens securely.</p><p>- Generate Jenkins CSRF Crumbs for authenticated API requests.</p><p>- Trigger Jenkins builds remotely using “curl”.</p><p>- Validate successful pipeline execution through Jenkins build history and console output.</p><ul><li>Understand the practical use cases for each Jenkins build trigger.</li></ul><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVwvDFzJZlriz5CIJR9hWA.png" /><figcaption>*Figure 1:* GitHub repository containing the declarative Jenkins Pipeline (Jenkinsfile) used throughout this tutorial.</figcaption></figure><p>Let’s get started…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvczwGe866QlTCmoRki1xA.jpeg" /></figure><p>— -</p><p>📖 Project Overview</p><p>In this project, we will configure and validate four different Jenkins build trigger mechanisms using a declarative Jenkins Pipeline stored in a GitHub repository.</p><p>The Jenkins server is hosted on an Amazon EC2 instance and securely integrated with GitHub using SSH authentication. Throughout this tutorial, each build trigger will be configured, tested, and validated to demonstrate how Jenkins automates Continuous Integration (CI) workflows in real-world DevOps environments.</p><p>The four build trigger mechanisms covered in this tutorial are:</p><p>- GitHub Webhooks — Automatically trigger a Jenkins pipeline whenever changes are pushed to the GitHub repository.</p><p>- Poll SCM — Periodically check the GitHub repository for source code changes using a cron schedule.</p><p>- Build Periodically — Schedule Jenkins to execute the pipeline automatically at predefined times.</p><p>- Remote Build Trigger — Trigger Jenkins builds securely through the Jenkins Remote API using an Authentication Token, API Token, CSRF Crumb, and “curl”.</p><p>By the end of this tutorial, you’ll understand the purpose of each build trigger, how to configure it, when to use it, and how it contributes to automating Continuous Integration pipelines.</p><p>— -</p><p>📋 Prerequisites</p><p>Before proceeding, ensure the following requirements are in place:</p><p>- An active AWS account.</p><p>- A running Jenkins server hosted on an Amazon EC2 instance.</p><p>- Git installed and configured.</p><p>- A GitHub repository containing the “Jenkinsfile”.</p><p>- SSH authentication configured between Jenkins and GitHub.</p><p>- Git Bash installed on your local machine.</p><p>- “curl” installed for interacting with the Jenkins Remote API.</p><p>- Jenkins Pipeline and Git plugins installed.</p><p>- Internet connectivity between GitHub and the Jenkins server.</p><p>Once your environment is ready, we’ll begin configuring and testing each Jenkins build trigger step by step.</p><p>— -</p><p>🚀 Step 1: Create the Jenkins Pipeline Project</p><p>With the project repository ready, the next step is to create a Pipeline project in Jenkins that will execute the declarative “Jenkinsfile” stored in the GitHub repository.</p><p>Unlike a Freestyle project, a Pipeline project allows the entire build process to be defined as code. This approach, commonly known as Pipeline as Code, makes CI pipelines easier to maintain, version, and reproduce across different environments.</p><p>To create the Pipeline project:</p><p>1. Sign in to the Jenkins dashboard.</p><p>2. Click New Item.</p><p>3. Enter the project name (for example, build-pipeline).</p><p>4. Select Pipeline as the project type.</p><p>5. Click OK to create the project.</p><p>After creating the Pipeline project, scroll to the Pipeline section and configure the following settings:</p><p>- Definition: Pipeline script from SCM</p><p>- SCM: Git</p><p>- Repository URL: Your GitHub repository URL</p><p>- Credentials: GitHub SSH credentials</p><p>- Branch Specifier: “*/main”</p><p>- Script Path: “Jenkinsfile”</p><p>These settings instruct Jenkins to retrieve the pipeline definition directly from the GitHub repository instead of storing it within Jenkins. As a result, every change made to the “Jenkinsfile” can be version-controlled and automatically used during future pipeline executions.</p><p>Once the configuration is complete, save the project before proceeding to configure the first build trigger.</p><p>— -</p><p>🔗 Step 2: Configure GitHub Webhook</p><p>One of the most efficient ways to trigger a Jenkins Pipeline is through GitHub Webhooks. Instead of Jenkins continuously checking the repository for changes, GitHub immediately notifies Jenkins whenever new code is pushed to the repository.</p><p>This event-driven approach reduces unnecessary polling, minimizes resource consumption, and enables near real-time Continuous Integration.</p><p>To configure the webhook:</p><p>1. Open your GitHub repository.</p><p>2. Navigate to Settings.</p><p>3. Select Webhooks.</p><p>4. Click Add webhook.</p><p>5. In the Payload URL, enter your Jenkins webhook endpoint:</p><p>http://&lt;JENKINS_PUBLIC_IP&gt;:8080/github-webhook/</p><p>6. Set the Content type to:</p><p>application/json</p><p>7. Leave the remaining settings at their default values.</p><p>8. Click Add webhook to save the configuration.</p><p>After the webhook is created, GitHub immediately begins sending notifications to Jenkins whenever changes are pushed to the repository.</p><p>To verify the configuration, open the webhook and review the Recent Deliveries section. A successful delivery confirms that GitHub can communicate with the Jenkins server and that the webhook has been configured correctly.</p><p>With the GitHub webhook in place, the next step is to configure Jenkins so it can respond to these webhook notifications and automatically execute the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ox03buTg3HB-2DjkswUlVg.png" /><figcaption>*Figure 2:* Configuring a GitHub Webhook to notify Jenkins whenever changes are pushed to the repository.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2LLbdfUiy1r9S9IXwjU0w.png" /><figcaption>*Figure 3:* Successful webhook delivery confirming communication between GitHub and Jenkins.</figcaption></figure><p>— -</p><p>⚙️ Step 3: Enable GitHub Hook Trigger in Jenkins</p><p>After configuring the GitHub webhook, Jenkins must be configured to respond to the incoming webhook notifications. Without this step, GitHub will successfully send the webhook, but Jenkins will ignore it and the pipeline will not start automatically.</p><p>To enable webhook-triggered builds:</p><p>1. Open the build-pipeline job in Jenkins.</p><p>2. Click Configure.</p><p>3. Scroll down to the Build Triggers section.</p><p>4. Enable GitHub hook trigger for GITScm polling.</p><p>5. Click Save to apply the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWQXO53lzidcxFK5s1uNLQ.png" /><figcaption>*Figure 4(a):* Enabling the *GitHub hook trigger for GITScm polling* in the Jenkins Pipeline configuration.</figcaption></figure><p>With this option enabled, Jenkins listens for webhook events sent by GitHub. Whenever a commit is pushed to the configured repository, GitHub immediately sends a notification to Jenkins, which then starts the pipeline automatically.</p><p>To validate the webhook configuration, create a small change in your local Git repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ptq0puddagU6ErGalNbxQg.png" /><figcaption>*Figure 4(b):* Creating a test file (testfile.txt) to verify that GitHub Webhooks trigger the Jenkins Pipeline automatically.</figcaption></figure><p>In this demonstration, a new file named “testfile.txt” was created to simulate a source code change.</p><p>After creating the file, verify the repository status using Git to confirm that the new file has been detected as an untracked change. Once confirmed, stage the file, create a Git commit with a descriptive commit message, and push the commit to the GitHub repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOW_XZZWPqdIQLhNqX0Azg.png" /><figcaption>*Figure 4(c):* Verifying the Git repository status before staging and committing the newly created file.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5Mn9BoPVIDd2Yo6NOZ9cw.png" /><figcaption>*Figure 4(d):* Successfully committing the test file to the local Git repository before pushing the changes to GitHub.</figcaption></figure><p>As soon as the push operation completes successfully, GitHub sends a webhook notification to Jenkins. Since the GitHub hook trigger for GITScm polling has already been enabled, Jenkins immediately receives the event and automatically starts a new pipeline execution without any manual intervention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTamgX_u5au8a-Vp6qpCEw.png" /><figcaption>*Figure 4(e):* Jenkins automatically triggering the pipeline after receiving the GitHub Webhook notification.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCQ-piThJE5OWQePzKKI3w.png" /><figcaption>*Figure 4(f):* Jenkins Console Output confirming the successful execution of the webhook-triggered pipeline.</figcaption></figure><p>This end-to-end workflow demonstrates how GitHub Webhooks provide real-time Continuous Integration by eliminating the need for repository polling.</p><p>This event-driven workflow is one of the most widely used Continuous Integration practices because it provides immediate feedback whenever new code is committed to the repository.</p><p>— -</p><p>🔄 Step 4: Configure Poll SCM</p><p>While GitHub Webhooks provide an event-driven approach to triggering builds, Jenkins also supports Poll SCM as an alternative mechanism for detecting source code changes.</p><p>With Poll SCM, Jenkins periodically checks the configured Git repository based on a cron schedule. If new commits are detected since the last successful build, Jenkins automatically starts the pipeline. If no changes are found, no build is triggered.</p><p>To configure Poll SCM:</p><p>1. Open the build-pipeline job in Jenkins.</p><p>2. Click Configure.</p><p>3. Scroll to the Build Triggers section.</p><p>4. Enable Poll SCM.</p><p>5. Enter the desired cron schedule. For demonstration purposes, the following schedule was used:</p><p>* * * * *</p><p>This instructs Jenkins to check the GitHub repository every minute for new commits.</p><p>6. Click Save to apply the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwVEyRxIEhl50lLA7uyohQ.png" /><figcaption>*Figure 5(a):* Configuring the *Poll SCM* build trigger using a cron schedule to periodically check the GitHub repository for source code changes.</figcaption></figure><p>After saving the configuration, make a small change to a file in your local repository, commit the change, and push it to GitHub.</p><p>Jenkins will check the repository according to the configured polling schedule. When it detects the new commit, it automatically starts the pipeline without requiring a webhook notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4lD2jPW-BsoIQ_NcCqz6Q.png" /><figcaption>*Figure 5(b):* Jenkins automatically triggering the pipeline after detecting new changes during the scheduled SCM polling process.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CAEtP35Q1dGRr2ge0ssUdQ.png" /><figcaption>*Figure 5(c):* Jenkins Console Output confirming the successful execution of the pipeline triggered through Poll SCM.</figcaption></figure><p>Although Poll SCM is useful in environments where webhooks cannot be configured, GitHub Webhooks are generally preferred because they trigger builds immediately after a commit instead of waiting for the next polling interval.</p><p>— -</p><p>⏰ Step 5: Configure Build Periodically</p><p>Jenkins also supports scheduled pipeline execution through the Build Periodically trigger. Unlike Poll SCM, which starts a build only when new source code changes are detected, Build Periodically executes the pipeline according to a predefined schedule regardless of repository activity.</p><p>This trigger is commonly used for recurring tasks such as scheduled testing, routine maintenance, health checks, report generation, and other automated jobs that need to run at specific intervals.</p><p>To configure Build Periodically:</p><p>1. Open the build-pipeline job in Jenkins.</p><p>2. Click Configure.</p><p>3. Navigate to the Build Triggers section.</p><p>4. Enable Build Periodically.</p><p>5. Specify the desired cron schedule.</p><p>For demonstration purposes, a simple schedule was configured to illustrate how Jenkins can automatically execute a pipeline at defined intervals.</p><p>6. Click Save to apply the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hm1ZEy1sC9A6RGqF5ys0Pw.png" /><figcaption>*Figure 6:* Configuring the *Build Periodically* trigger using a cron schedule to execute the Jenkins Pipeline automatically at predefined time intervals.</figcaption></figure><p>Once the scheduled time is reached, Jenkins automatically starts the pipeline without requiring a code commit, webhook notification, or manual intervention.</p><p>Build Periodically is particularly useful for automating repetitive operational tasks and complements other Jenkins build triggers by providing reliable time-based automation.</p><p>— -</p><p>🌐 Step 6: Configure Remote Build Trigger</p><p>Jenkins provides a Remote Build Trigger feature that allows pipelines to be started from external applications, scripts, or automation tools through the Jenkins Remote API. This capability is particularly useful when integrating Jenkins with third-party systems or custom automation workflows.</p><p>Unlike GitHub Webhooks, Poll SCM, or Build Periodically, a remote build request is initiated by an authenticated external client rather than by a repository event or a scheduled task.</p><p>To configure a Remote Build Trigger:</p><p>1. Open the build-pipeline job in Jenkins.</p><p>2. Click Configure.</p><p>3. Scroll to the Build Triggers section.</p><p>4. Enable Trigger builds remotely (e.g., from scripts).</p><p>5. Specify a unique Authentication Token for the job.</p><p>6. Click Save to apply the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WfH9y6iBq1Trk64Geg8gQ.png" /><figcaption>*Figure 7:* Enabling the *Remote Build Trigger* and configuring an authentication token to allow secure pipeline execution through the Jenkins Remote API.</figcaption></figure><p>The authentication token acts as an additional layer of security by ensuring that only authorized requests can trigger the pipeline remotely.</p><p>Although the job is now configured to accept remote build requests, additional authentication is still required. Jenkins uses API Tokens and CSRF protection to secure Remote API access. In the next steps, you’ll generate an API Token, retrieve a Jenkins CSRF Crumb, and use both to trigger the pipeline securely with “curl”.</p><p>— -</p><p>🔐 Step 7: Generate a Jenkins API Token</p><p>To securely authenticate Remote API requests, Jenkins uses API Tokens instead of user account passwords. This approach improves security by allowing automated tools and scripts to authenticate without exposing user credentials.</p><p>API Tokens are generated for individual Jenkins users and can be revoked or regenerated whenever necessary. This makes them the recommended authentication method for integrating Jenkins with external systems.</p><p>To generate an API Token:</p><p>1. Sign in to Jenkins.</p><p>2. Click your username in the upper-right corner of the dashboard.</p><p>3. Select Security.</p><p>4. Navigate to the API Token section.</p><p>5. Click Add new Token.</p><p>6. Enter a descriptive name for the token.</p><p>7. Choose an appropriate expiration period based on your organization’s security policy.</p><p>8. Generate the token and securely store its value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGdh6mVr4nFxxE0wcQbT5w.png" /><figcaption>*Figure 8:* Generating a Jenkins API Token for secure authentication when accessing the Jenkins Remote API.</figcaption></figure><p>The generated API Token will be used together with your Jenkins username when making authenticated requests to the Jenkins Remote API.</p><p>Security Tip: Treat API Tokens like passwords. Never hard-code them into scripts or expose them in public repositories. For production environments, store sensitive credentials securely using a secrets management solution or a CI/CD credential store.</p><p>— -</p><p>🛡️ Step 8: Generate a Jenkins CSRF Crumb</p><p>By default, Jenkins protects authenticated requests with Cross-Site Request Forgery (CSRF) protection. When CSRF protection is enabled, authenticated POST requests must include a valid CSRF Crumb; otherwise, Jenkins rejects the request with a 403 Forbidden response.</p><p>Before triggering the pipeline remotely, retrieve a CSRF Crumb using the Jenkins Remote API.</p><p>Run the following command from your terminal, replacing the placeholder values with your own Jenkins details:</p><p>curl -u “YOUR_JENKINS_USERNAME:YOUR_API_TOKEN” \</p><p>http://YOUR_JENKINS_SERVER:8080/crumbIssuer/api/xml?xpath=concat\(//crumbRequestField,&quot;:&quot;,//crumb\)</p><p>If the request is successful, Jenkins returns the crumb request header and its corresponding value. This information will be included in the next step when sending the remote build request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dduD9toXo5ftNIKTdjIjCw.png" /><figcaption>*Figure 9:* Successfully retrieving a Jenkins CSRF Crumb using the Jenkins Remote API and the curl command.</figcaption></figure><p>Generating a CSRF Crumb is an important security practice because it helps ensure that authenticated requests originate from trusted clients rather than malicious third-party websites.</p><p>With both the API Token and the CSRF Crumb available, the Jenkins server is now ready to accept secure remote build requests.</p><p>— -</p><p>🚀 Step 9: Trigger the Jenkins Pipeline Remotely Using “curl”</p><p>With the Remote Build Trigger configured, the API Token generated, and the CSRF Crumb successfully retrieved, the final step is to trigger the Jenkins Pipeline remotely.</p><p>This is accomplished by sending an authenticated HTTP POST request to the Jenkins Remote API using the “curl” command-line tool.</p><p>Run the following command, replacing the placeholder values with your own Jenkins configuration:</p><p>curl -X POST \</p><p>-u “YOUR_JENKINS_USERNAME:YOUR_API_TOKEN” \</p><p>-H “YOUR_CSRF_HEADER:YOUR_CSRF_CRUMB” \</p><p>“http://YOUR_JENKINS_SERVER:8080/job/build-pipeline/build?token=YOUR_AUTHENTICATION_TOKEN&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czk1Bw_iTKt1pS8zjoVKVg.png" /><figcaption>*Figure 10(a):* Triggering the Jenkins Pipeline remotely using the Jenkins Remote API with an Authentication Token, API Token, CSRF Crumb, and the curl command.</figcaption></figure><p>If the request is successful, Jenkins accepts the build request and immediately schedules a new pipeline execution.</p><p>To verify the result:</p><p>1. Open the Jenkins dashboard.</p><p>2. Navigate to the build-pipeline job.</p><p>3. Select Build History.</p><p>4. Open the latest build.</p><p>5. Review the Console Output to confirm that the pipeline executed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8ebMzPNUgrGIKKY5we8cg.png" /><figcaption>*Figure 10(b):* Jenkins Console Output confirming the successful execution of the pipeline triggered through the Jenkins Remote API.</figcaption></figure><p>This demonstrates how Jenkins can be integrated with external applications, automation scripts, and third-party tools to initiate builds programmatically. Remote Build Triggers are particularly valuable for enterprise automation workflows where Jenkins serves as part of a larger CI/CD ecosystem.</p><p>At this stage, you have successfully implemented and validated all four Jenkins build trigger mechanisms:</p><p>- GitHub Webhooks</p><p>- Poll SCM</p><p>- Build Periodically</p><ul><li>Remote Build Trigger</li></ul><p>— -</p><p>🔧 Troubleshooting &amp; Best Practices</p><p>During the implementation of this project, several common issues were encountered and resolved. Understanding these challenges and their solutions will help you troubleshoot similar problems in your own Jenkins environment.</p><p>Common Issues and Solutions</p><p>1. GitHub Webhook Failed</p><p>Possible Cause:</p><p>- Incorrect webhook URL.</p><p>- Jenkins server was not publicly accessible.</p><p>- Port 8080 was blocked by the firewall or security group.</p><p>Resolution:</p><p>- Verify that the webhook URL ends with:</p><p>/github-webhook/</p><p>- Confirm that the Jenkins server is reachable over the internet.</p><p>- Ensure the Jenkins server’s security group allows inbound traffic on port 8080.</p><p>— -</p><p>2. Pipeline Was Not Triggered After a Git Push</p><p>Possible Cause:</p><p>- The GitHub hook trigger for GITScm polling option was not enabled.</p><p>- Changes were not committed or pushed to the GitHub repository.</p><p>Resolution:</p><p>- Enable the GitHub webhook trigger in the Jenkins job configuration.</p><p>- Verify that the latest commit has been successfully pushed to GitHub.</p><p>— -</p><p>3. Poll SCM Did Not Detect Repository Changes</p><p>Possible Cause:</p><p>- Invalid cron expression.</p><p>- No new commits were available in the repository.</p><p>Resolution:</p><p>- Review the cron schedule.</p><p>- Make a new commit and push it to GitHub before waiting for the next polling interval.</p><p>— -</p><p>4. Remote Build Request Returned 403 Forbidden</p><p>Possible Cause:</p><p>- Missing or invalid CSRF Crumb.</p><p>- Invalid API Token.</p><p>- Incorrect Jenkins username.</p><p>Resolution:</p><p>- Generate a new CSRF Crumb.</p><p>- Verify the API Token.</p><p>- Confirm that the correct Jenkins username is used when authenticating the request.</p><p>— -</p><p>5. Remote Build Was Not Triggered</p><p>Possible Cause:</p><p>- Incorrect Authentication Token.</p><p>- Incorrect Remote API URL.</p><p>Resolution:</p><p>- Verify that the Authentication Token configured in the Jenkins job matches the token supplied in the request URL.</p><p>- Confirm that the job name and endpoint are correct.</p><p>— -</p><p>Best Practices</p><p>Throughout this implementation, several best practices were followed:</p><p>- Store pipeline definitions in a version-controlled “Jenkinsfile”.</p><p>- Prefer GitHub Webhooks over Poll SCM whenever webhook integration is available.</p><p>- Protect API Tokens and never expose them in public repositories.</p><p>- Use CSRF protection when interacting with the Jenkins Remote API.</p><p>- Verify webhook deliveries using GitHub’s Recent Deliveries page.</p><p>- Use descriptive Git commit messages to maintain a clear project history.</p><p>- Validate every build using the Jenkins Build History and Console Output before considering the implementation complete.</p><p>Following these practices helps improve the security, reliability, and maintainability of Jenkins-based Continuous Integration pipelines.</p><p>— -</p><p>📚 Key Takeaways</p><p>Congratulations! By following this tutorial, you have successfully implemented and validated four different Jenkins build trigger mechanisms used in modern Continuous Integration (CI) pipelines.</p><p>Here’s what you accomplished:</p><p>- Configured GitHub Webhooks to trigger Jenkins pipelines automatically whenever code is pushed to a GitHub repository.</p><p>- Configured Poll SCM to periodically check the repository for source code changes using a cron schedule.</p><p>- Configured Build Periodically to execute Jenkins pipelines automatically at scheduled intervals.</p><p>- Configured Remote Build Trigger to start Jenkins pipelines securely using the Jenkins Remote API.</p><p>- Generated and used a Jenkins API Token for secure authentication.</p><p>- Retrieved a Jenkins CSRF Crumb to protect authenticated API requests.</p><p>- Triggered Jenkins pipelines remotely using “curl”.</p><p>- Verified successful pipeline execution through Jenkins Build History and Console Output.</p><p>- Applied Git and GitHub best practices to manage source code and technical documentation.</p><p>These are practical DevOps skills that are widely used when building and maintaining CI/CD pipelines in production environments.</p><p>— -</p><p>🎯 Conclusion</p><p>Build triggers are a fundamental part of Jenkins automation because they determine when and how pipelines are executed. Understanding the strengths and use cases of each trigger mechanism enables DevOps engineers to design CI workflows that are efficient, reliable, and secure.</p><p>In this tutorial, we explored four different approaches to triggering Jenkins pipelines:</p><p>- GitHub Webhooks for real-time, event-driven automation.</p><p>- Poll SCM for environments where repository polling is required.</p><p>- Build Periodically for scheduled pipeline execution.</p><p>- Remote Build Trigger for integrating Jenkins with external applications and automation tools through the Jenkins Remote API.</p><p>Each trigger serves a different purpose, and selecting the appropriate one depends on your application’s requirements, infrastructure, and automation goals.</p><p>I hope this hands-on guide has helped you better understand Jenkins build automation and given you the confidence to implement these trigger mechanisms in your own projects.</p><p>If you found this tutorial helpful, consider following me on Medium for more practical articles on AWS, DevOps, Jenkins, Docker, Kubernetes, Terraform, and CI/CD as I continue documenting real-world projects from my DevOps learning journey.</p><p>Thank you for reading, and happy learning!</p><p>— -</p><p>🙌 Enjoyed This Tutorial?</p><p>If you found this tutorial helpful, please consider sharing it with others who are learning Jenkins, AWS, and DevOps. Your feedback, comments, and support motivate me to continue creating practical, real-world technical content.</p><p>Thank you for reading, and I hope this guide helps you build more reliable and automated CI/CD pipelines with Jenkins.</p><p>— -</p><p>👨‍💻 About the Author</p><p>Hi, I’m Olajide Adedayo, an AWS and DevOps Engineer passionate about designing, implementing, and documenting production-inspired cloud and DevOps solutions through hands-on projects.</p><p>My goal is to simplify complex DevOps concepts by sharing step-by-step tutorials based on real implementations using technologies such as AWS, Jenkins, Git, GitHub, Docker, Kubernetes, Terraform, Linux, and CI/CD.</p><p>I enjoy building scalable, secure, and automated infrastructure while sharing practical knowledge that helps aspiring and experienced professionals strengthen their cloud and DevOps skills.</p><p>🤝 Connect with Me</p><p>I’d love to connect with fellow cloud and DevOps professionals. You can find me on:</p><p>- 🌐 Medium: <a href="https://medium.com/@olajideadedayo230">https://medium.com/@olajideadedayo230</a></p><p>- 💻 GitHub: <a href="https://github.com/olajide-adedayo">https://github.com/olajide-adedayo</a></p><p>- 🔗 LinkedIn: <a href="https://www.linkedin.com/in/olajide-adedayo-9126593b3/">https://www.linkedin.com/in/olajide-adedayo-9126593b3/</a></p><p>Thank you for reading, and I look forward to connecting with you. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22c44d5a7638" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Jenkins Pipeline as Code: Integrating GitHub with Jenkins Using SSH Authentication (Step-by-Step…]]></title>
            <link>https://medium.com/@olajideadedayo230/jenkins-pipeline-as-code-integrating-github-with-jenkins-using-ssh-authentication-step-by-step-4ca537fbb7d9?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ca537fbb7d9</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 07:37:01 GMT</pubDate>
            <atom:updated>2026-07-18T07:37:01.842Z</atom:updated>
            <content:encoded><![CDATA[<p>🚀 Jenkins Pipeline as Code: Integrating GitHub with Jenkins Using SSH Authentication (Step-by-Step Guide)</p><p>Build a secure Jenkins Pipeline by integrating GitHub with SSH authentication, configuring Pipeline as Code using a Jenkinsfile, resolving Git host key verification issues, and successfully executing your first pipeline through a step-by-step hands-on implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oc5z7_ovD5fzxWssfr2RCQ.png" /><figcaption>Figure 1: Successful execution of the Jenkins Pipeline after securely integrating GitHub with Jenkins using SSH authentication and Pipeline as Code.</figcaption></figure><p>Introduction</p><p>As software development teams embrace DevOps practices, automation has become a fundamental requirement for delivering applications quickly, consistently, and reliably. One of the key principles of modern Continuous Integration (CI) is Pipeline as Code, where the entire build pipeline is defined and managed using source-controlled code instead of manual configuration.</p><p>In Jenkins, this is achieved through a Jenkinsfile — a text file stored alongside the application’s source code. By keeping the pipeline definition in a Git repository, teams can version, review, and maintain their CI workflows just like any other codebase. This approach improves collaboration, enhances reproducibility, and reduces configuration drift across environments.</p><p>In this hands-on tutorial, you will learn how to integrate Jenkins with a GitHub repository using SSH authentication and configure a Pipeline job that retrieves its build instructions directly from a version-controlled “Jenkinsfile”.</p><p>Throughout the implementation, you’ll also learn how to configure Jenkins credentials, resolve Git Host Key Verification issues, validate repository connectivity, and execute your first Pipeline successfully.</p><p>By the end of this guide, you will have built a secure and reusable Pipeline as Code workflow that follows industry best practices and serves as a strong foundation for more advanced CI/CD pipelines.</p><p>— -</p><p>🎯 What You Will Learn</p><p>By following this step-by-step tutorial, you will learn how to:</p><p>- Understand the concept and benefits of Pipeline as Code.</p><p>- Create a Declarative Jenkinsfile to define a Jenkins Pipeline.</p><p>- Configure a GitHub repository to store and version-control the pipeline definition.</p><p>- Integrate Jenkins with GitHub using SSH authentication.</p><p>- Create and configure SSH Username with Private Key credentials in Jenkins.</p><p>- Configure a Jenkins Pipeline job using Pipeline Script from SCM.</p><p>- Resolve Git Host Key Verification issues during repository validation.</p><p>- Execute a Jenkins Pipeline and verify a successful build through the Jenkins console output.</p><p>- Apply DevOps best practices for secure, version-controlled, and maintainable CI workflows.</p><p>Whether you’re a beginner exploring Jenkins or a DevOps engineer looking to strengthen your Continuous Integration skills, this tutorial provides practical, hands-on experience that you can apply to real-world projects.</p><p>— -</p><p>⚙️ Prerequisites</p><p>Before you begin this tutorial, ensure you have the following:</p><p>AWS Infrastructure</p><p>- A running Amazon EC2 instance with Jenkins installed and accessible through a web browser.</p><p>- Appropriate security group rules configured to allow access to the Jenkins web interface.</p><p>Development Environment</p><p>- Git installed on your local machine.</p><p>- Visual Studio Code (or any preferred code editor).</p><p>- An active GitHub account.</p><p>- An existing GitHub repository for storing the “Jenkinsfile”.</p><p>Jenkins Requirements</p><p>- Administrative access to Jenkins.</p><p>- Git plugin installed in Jenkins.</p><p>- SSH Username with Private Key credentials configured for GitHub authentication.</p><p>Basic Knowledge</p><p>A basic understanding of the following concepts will help you follow this guide more easily:</p><p>- Git and GitHub</p><p>- Linux command-line fundamentals</p><p>- Jenkins basics</p><p>- Continuous Integration (CI)</p><p>With these prerequisites in place, you’re ready to implement Pipeline as Code by integrating Jenkins with GitHub using SSH authentication.</p><p>— -</p><p>📖 Project Overview</p><p>In many organizations, Jenkins pipelines are initially created directly through the Jenkins web interface. While this approach is suitable for simple demonstrations, it becomes difficult to maintain, version, and reproduce as projects grow in complexity.</p><p>Pipeline as Code addresses this challenge by defining the entire pipeline in a Jenkinsfile, which is stored in a source code repository alongside the application code. This enables teams to apply version control, perform code reviews, track changes, and maintain consistent pipeline configurations across different environments.</p><p>In this project, a GitHub repository was created to store the “Jenkinsfile”, and Jenkins was configured to retrieve the pipeline definition directly from the repository using Pipeline Script from SCM. Secure communication between Jenkins and GitHub was established using SSH authentication with SSH Username with Private Key credentials.</p><p>The implementation concluded with Jenkins successfully cloning the repository, loading the “Jenkinsfile”, and executing the pipeline with a SUCCESS status, demonstrating a complete and secure Pipeline as Code workflow.</p><p>— -</p><p>🏗️ Solution Architecture</p><p>The project implements a secure Pipeline as Code workflow by integrating GitHub with Jenkins through SSH authentication. Instead of defining the pipeline directly within Jenkins, the pipeline is stored as a “Jenkinsfile” in a GitHub repository. Jenkins securely connects to GitHub, retrieves the pipeline definition, and executes the build.</p><p>Architecture Workflow</p><p>Developer</p><p>│</p><p>│ Creates and updates</p><p>▼</p><p>Jenkinsfile (Visual Studio Code)</p><p>│</p><p>│ Git Commit &amp; Push</p><p>▼</p><p>GitHub Repository</p><p>│</p><p>│ SSH Authentication</p><p>▼</p><p>Jenkins Pipeline (Pipeline Script from SCM)</p><p>│</p><p>│ Retrieves Jenkinsfile</p><p>▼</p><p>Pipeline Execution</p><p>│</p><p>│ Executes Pipeline Stages</p><p>▼</p><p>Build Success (SUCCESS)</p><p>Workflow Explanation</p><p>1. The developer creates or updates the “Jenkinsfile” locally using Visual Studio Code.</p><p>2. The “Jenkinsfile” is committed and pushed to a GitHub repository using Git.</p><p>3. Jenkins securely authenticates with GitHub using SSH Username with Private Key credentials.</p><p>4. The Pipeline job retrieves the “Jenkinsfile” from the GitHub repository using Pipeline Script from SCM.</p><p>5. Jenkins executes the pipeline stages defined in the “Jenkinsfile”.</p><p>6. The build completes successfully, confirming that the Pipeline as Code implementation is functioning correctly.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKmCr58RCMF9nE3SdLfjLg.png" /><figcaption>Figure 2: GitHub repository containing the version-controlled “Jenkinsfile” used by Jenkins Pipeline as Code.</figcaption></figure><p>— -</p><p>🛠️ Step-by-Step Implementation</p><p>This section walks through the complete implementation of Jenkins Pipeline as Code using GitHub and SSH authentication. Each step builds upon the previous one, resulting in a secure and fully functional Pipeline as Code workflow.</p><p>Step 1: Verify Your Existing SSH Public Key</p><p>Before integrating Jenkins with GitHub, verify that an SSH key pair already exists on your local machine. The public key will be added to your GitHub account to enable secure authentication without using a username and password.</p><p>On your local machine, display the public key by running:</p><p>cat ~/.ssh/id_ed25519.pub</p><p>If your environment uses RSA instead of ED25519, use:</p><p>cat ~/.ssh/id_rsa.pub</p><p>Copy the displayed public key. It will be added to your GitHub account in the next step.</p><p>This approach establishes secure, passwordless authentication between your local machine and GitHub, which is considered an industry best practice for Git operations.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onRriZuX3hCuR1PqQFcrHw.png" /><figcaption>Figure 3: Viewing the existing SSH public key that will be added to GitHub for secure authentication.</figcaption></figure><p>— -</p><p>Step 2: Configure GitHub SSH Keys</p><p>After copying your SSH public key, the next step is to add it to your GitHub account. This enables secure communication between your local machine and GitHub using SSH instead of HTTPS authentication.</p><p>To add your SSH key:</p><p>1. Sign in to your GitHub account.</p><p>2. Click your profile picture and select Settings.</p><p>3. In the left navigation pane, click SSH and GPG keys.</p><p>4. Click New SSH key.</p><p>5. Enter a descriptive title for the key.</p><p>6. Paste the copied SSH public key into the Key field.</p><p>7. Click Add SSH key.</p><p>8. Authenticate with your GitHub password or passkey if prompted.</p><p>Once the SSH key has been added successfully, GitHub will trust future SSH connections from your local machine, allowing you to securely clone, push, and pull repositories without repeatedly entering your credentials.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9teJXk_Idi22dOKTUroVJw.png" /><figcaption>Figure 4: Configuring an SSH public key in GitHub to enable secure SSH-based authentication.</figcaption></figure><p>— -</p><p>Step 3: Verify GitHub SSH Authentication</p><p>After adding the SSH public key to your GitHub account, verify that the SSH connection is working correctly before performing any Git operations.</p><p>Run the following command in your terminal:</p><p>ssh -T git@github.com</p><p>If the authentication is successful, GitHub will display a welcome message similar to:</p><p>Hi &lt;your-github-username&gt;! You’ve successfully authenticated, but GitHub does not provide shell access.</p><p>Receiving this message confirms that your local machine has been successfully authenticated with GitHub using SSH and is ready to securely clone, push, and pull repositories.</p><p>If you receive a host authenticity prompt during the first connection, type:</p><p>yes</p><p>to add GitHub’s host key to your list of known hosts.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yHIwqDtHUl_iG8loJCncw.png" /><figcaption>Figure 5: Successful SSH authentication with GitHub, confirming secure connectivity between the local machine and the GitHub account.</figcaption></figure><p>— -</p><p>Step 4: Clone the GitHub Repository Using SSH</p><p>With SSH authentication successfully configured, the next step is to clone the GitHub repository to your local machine using the SSH repository URL.</p><p>From your GitHub repository, click the Code button, select the SSH option, and copy the repository URL.</p><p>Run the following command to clone the repository:</p><p>git clone git@github.com:olajide-adedayo/jenkins-pipeline-as-code.git</p><p>After the cloning process completes, navigate into the project directory:</p><p>cd jenkins-pipeline-as-code</p><p>Cloning the repository using SSH ensures that future Git operations, such as pushing commits and pulling updates, are performed securely without requiring repeated username and password authentication.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEVYMTJRK0V4OYuyuCPD4g.png" /><figcaption>Figure 6: Cloning the GitHub repository locally using the SSH repository URL.</figcaption></figure><p>— -</p><p>Step 5: Create the Jenkinsfile</p><p>After cloning the repository, create a file named “Jenkinsfile” in the root directory of the project. This file defines the Jenkins Pipeline using Declarative Pipeline syntax and serves as the source-controlled pipeline configuration.</p><p>Open the repository in Visual Studio Code (or your preferred code editor) and create the “Jenkinsfile”.</p><p>Add the following pipeline definition:</p><p>pipeline {</p><p>agent any</p><p>stages {</p><p>stage(‘Build’) {</p><p>steps {</p><p>echo ‘This is a test message’</p><p>}</p><p>}</p><p>}</p><p>}</p><p>This simple pipeline consists of:</p><p>- “agent any” — Instructs Jenkins to run the pipeline on any available agent.</p><p>- “stage(‘Build’)” — Defines the Build stage of the pipeline.</p><p>- “echo” — Prints a message to the Jenkins console output, confirming that the pipeline executed successfully.</p><p>Although this is a basic example, it demonstrates the core principle of Pipeline as Code. As projects grow, additional stages such as testing, code quality analysis, artifact packaging, and deployment can be added to the “Jenkinsfile”.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4vFM6ku3GMRR6j9cBtZJg.png" /><figcaption>Figure 7: Creating the “Jenkinsfile” in Visual Studio Code using Declarative Pipeline syntax.</figcaption></figure><p>— -</p><p>Step 6: Stage and Commit the Jenkinsfile</p><p>After creating the “Jenkinsfile”, the next step is to stage and commit it to the local Git repository.</p><p>First, verify the repository status:</p><p>git status</p><p>You should see the newly created “Jenkinsfile” listed as an untracked file.</p><p>Next, stage the file:</p><p>git add Jenkinsfile</p><p>Verify the repository status again to confirm that the file has been staged successfully:</p><p>git status</p><p>Finally, create your first commit:</p><p>git commit -m “Add initial Jenkinsfile”</p><p>This commit records the initial Pipeline definition in the Git repository, making it available for version control and future collaboration.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0o8au6h82TVmZmYriYQJLQ.png" /><figcaption>Figure 8: Staging the “Jenkinsfile” in the local Git repository before creating the initial commit.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PidjrFIUtm_5hi9WBYKIfQ.png" /><figcaption>Figure 9: Successfully creating the first Git commit containing the “Jenkinsfile”.</figcaption></figure><p>— -</p><p>Step 7: Push the Jenkinsfile to GitHub</p><p>After committing the “Jenkinsfile” locally, push the commit to the remote GitHub repository.</p><p>Run the following command:</p><p>git push origin main</p><p>If the push is successful, GitHub will update the repository with the newly committed “Jenkinsfile”.</p><p>To verify the upload:</p><p>1. Open your GitHub repository in a web browser.</p><p>2. Refresh the repository page.</p><p>3. Confirm that the “Jenkinsfile” is displayed in the root directory of the repository.</p><p>At this point, the repository is ready to be integrated with Jenkins using Pipeline Script from SCM.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCFe94sWwMONhK130gda6g.png" /><figcaption>Figure 10: Successfully pushing the “Jenkinsfile” from the local repository to GitHub.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKmCr58RCMF9nE3SdLfjLg.png" /><figcaption>Figure 11: GitHub repository showing the committed “Jenkinsfile” in the repository root.</figcaption></figure><p>— -</p><p>Step 8: Verify the Jenkins Server</p><p>Before configuring the Pipeline job, ensure that your Jenkins server is running and accessible through a web browser.</p><p>In this project, Jenkins was hosted on an Amazon EC2 instance. After confirming that the EC2 instance was in the Running state, the Jenkins web interface was accessed using the server’s public IP address and port 8080.</p><p>If your Jenkins server is running successfully, the Jenkins dashboard should be accessible, allowing you to create and manage Pipeline jobs.</p><p>Verifying the server status before configuration helps prevent connectivity issues and ensures that the environment is ready for the remaining implementation steps.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlWO5RcPYSV9wiSaP9uvFA.png" /><figcaption>Figure 12: Amazon EC2 instance running the Jenkins server and ready for Pipeline configuration.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLQ_avB8haQhN7Cm9b52Mw.png" /><figcaption>Figure 13: Jenkins dashboard before creating the Pipeline job.</figcaption></figure><p>— -</p><p>Step 9: Create and Configure the Jenkins Pipeline Job</p><p>With the Jenkins server running successfully, the next step is to create a new Pipeline job.</p><p>To create the Pipeline job:</p><p>1. From the Jenkins dashboard, click New Item.</p><p>2. Enter a name for the Pipeline job.</p><p>3. Select Pipeline as the project type.</p><p>4. Click OK to create the job.</p><p>After creating the Pipeline job, scroll to the Pipeline section of the job configuration page.</p><p>Change the Definition from:</p><p>Pipeline script</p><p>to:</p><p>Pipeline script from SCM</p><p>Next, configure the following settings:</p><p>- SCM: Git</p><p>- Repository URL: Your GitHub SSH repository URL</p><p>- Credentials: SSH Username with Private Key</p><p>- Branch Specifier: “*/main”</p><p>- Script Path: “Jenkinsfile”</p><p>Using Pipeline Script from SCM enables Jenkins to retrieve the latest version of the “Jenkinsfile” directly from the GitHub repository whenever the pipeline is executed.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjB7XvTcV9h2azQozRUQsw.png" /><figcaption>Figure 14: Creating and configuring a Jenkins Pipeline job.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ew0oCySyC1F_QwxHZKwVA.png" /><figcaption>Figure 15: Configuring the Pipeline job to retrieve the “Jenkinsfile” using Pipeline Script from SCM.</figcaption></figure><p>— -</p><p>Step 10: Configure SSH Credentials in Jenkins</p><p>To allow Jenkins to securely access the GitHub repository, create an SSH Username with Private Key credential.</p><p>Follow these steps:</p><p>1. In Jenkins, navigate to Manage Jenkins → Credentials.</p><p>2. Select the appropriate credentials store.</p><p>3. Click Add Credentials.</p><p>4. For Kind, select SSH Username with private key.</p><p>5. Enter the following information:</p><p>- Username: “git”</p><p>- Private Key: Paste the private SSH key associated with the public key added to GitHub.</p><p>- ID: Enter a meaningful credential ID (for example, “git”).</p><p>- Description: Provide a descriptive name for the credential.</p><p>6. Click Create (or Save, depending on your Jenkins version).</p><p>After creating the credential, return to the Pipeline job configuration and select the newly created SSH credential from the Credentials drop-down list.</p><p>With the credential configured, Jenkins can securely authenticate with GitHub and retrieve the “Jenkinsfile” without requiring interactive authentication.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1J8c-2kg2uhZJIHdBuUTTQ.png" /><figcaption>Figure 16: Configuring an SSH Username with Private Key credential in Jenkins for secure GitHub authentication.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0MO8DjXkqcvcBxQdpnoIQ.png" /><figcaption>Figure 17: Successful Git SCM configuration using the GitHub SSH repository URL and Jenkins SSH credentials.</figcaption></figure><p>— -</p><p>Step 11: Execute the Pipeline and Verify the Build</p><p>With the Pipeline job fully configured, the final step is to execute the pipeline and verify that Jenkins can successfully retrieve the “Jenkinsfile” from GitHub and complete the build.</p><p>To start the pipeline:</p><p>1. Open the Jenkins Pipeline job.</p><p>2. Click Build Now.</p><p>3. Wait for the build to complete.</p><p>4. Click the completed build from the Build History.</p><p>5. Open Console Output to review the execution logs.</p><p>If the configuration is correct, Jenkins will:</p><p>- Authenticate with GitHub using the configured SSH credentials.</p><p>- Clone the GitHub repository.</p><p>- Retrieve the “Jenkinsfile” from the “main” branch.</p><p>- Execute each stage defined in the pipeline.</p><p>- Display the message:</p><p>This is a test message</p><p>The console output should end with:</p><p>Finished: SUCCESS</p><p>This confirms that the Jenkins Pipeline has executed successfully and that the Pipeline as Code implementation is functioning as expected.</p><p>— -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oc5z7_ovD5fzxWssfr2RCQ.png" /><figcaption>Figure 18: Successful execution of the Jenkins Pipeline after retrieving the “Jenkinsfile” from the GitHub repository.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRiG8H3slhsNhG_9BoPpVg.png" /><figcaption>Figure 19: Jenkins console output confirming successful pipeline execution with a final SUCCESS status.</figcaption></figure><p>— -</p><p>🔧 Troubleshooting</p><p>During the implementation of this project, a few configuration and integration challenges were encountered. The following table summarizes the issues, their root causes, and the solutions that resolved them.</p><p>Issue| Root Cause| Resolution</p><p>Jenkins failed to connect to the GitHub repository.| SSH authentication was not fully configured for the Pipeline job.| Created an SSH Username with Private Key credential in Jenkins and selected it in the Pipeline job configuration.</p><p>Host key verification failed during repository validation.| Jenkins had not established trust with GitHub’s SSH host key.| Configured Git Host Key Verification in Jenkins and validated the repository connection again.</p><p>Repository validation continued to fail after creating the SSH credential.| The correct Jenkins credential had not been selected in the Git SCM configuration.| Updated the Pipeline job to use the correct SSH Username with Private Key credential.</p><p>Jenkins could not retrieve the “Jenkinsfile” during the initial configuration.| The Git SCM configuration required verification before execution.| Confirmed the repository URL, branch (“main”), script path (“Jenkinsfile”), and Git SCM settings before running the Pipeline.</p><p>Lessons from Troubleshooting</p><p>These challenges reinforced the importance of validating each stage of the configuration process before executing a Pipeline. Most Jenkins integration issues are related to authentication, repository access, or SCM configuration. Understanding how to diagnose and resolve these problems is an essential DevOps skill that improves both reliability and operational efficiency.</p><p>— -</p><p>📚 Best Practices</p><p>Throughout this implementation, several DevOps best practices were applied to improve security, maintainability, and collaboration. Adopting these practices will help you build reliable and production-ready Jenkins Pipelines.</p><p>1. Store Pipeline Definitions in Source Control</p><p>Keep your “Jenkinsfile” in the same Git repository as your project. This enables version control, simplifies collaboration, and allows pipeline changes to be reviewed just like application code.</p><p>2. Use SSH Authentication</p><p>Prefer SSH authentication over HTTPS when integrating Jenkins with GitHub. SSH provides secure, passwordless authentication and is widely adopted in professional DevOps environments.</p><p>3. Manage Secrets Securely</p><p>Never store private keys, passwords, or access tokens directly in your “Jenkinsfile”. Instead, use Jenkins Credentials to securely manage sensitive information.</p><p>4. Validate Configuration Before Running Pipelines</p><p>Before triggering a build, verify the repository URL, branch name, credentials, and script path. Performing these checks helps prevent common configuration errors.</p><p>5. Review Console Output</p><p>Always examine the Jenkins console output after each build. It provides detailed execution logs that are essential for troubleshooting and verifying successful pipeline execution.</p><p>6. Document Your Implementation</p><p>Maintain clear documentation of your pipeline configuration, implementation steps, and troubleshooting outcomes. Well-documented projects are easier to maintain, share, and onboard new team members.</p><p>By following these best practices, you can build secure, maintainable, and reproducible Pipeline as Code workflows that align with modern DevOps principles.</p><p>— -</p><p>🎯 Key Takeaways</p><p>By completing this tutorial, you have successfully implemented a secure Pipeline as Code workflow using Jenkins and GitHub. More importantly, you have gained practical experience with the core concepts that underpin modern Continuous Integration (CI) practices.</p><p>Here are the key takeaways from this project:</p><p>- Pipeline as Code enables you to define, version, and maintain your CI pipeline using a “Jenkinsfile” stored in source control.</p><p>- GitHub serves as the central repository for managing pipeline definitions and tracking changes over time.</p><p>- SSH authentication provides a secure and reliable method for integrating Jenkins with GitHub.</p><p>- Jenkins Credentials help protect sensitive information by securely managing private keys and authentication details.</p><p>- Pipeline Script from SCM allows Jenkins to automatically retrieve and execute the latest version of the “Jenkinsfile” from the repository.</p><p>- Reviewing the Jenkins Console Output is essential for validating successful builds and troubleshooting pipeline failures.</p><p>- Following DevOps best practices — such as version control, secure credential management, and clear documentation — results in more reliable, maintainable, and scalable CI workflows.</p><p>These concepts form a strong foundation for building more advanced CI/CD pipelines that include automated testing, code quality analysis, artifact management, containerization, and application deployment.</p><p>— -</p><p>✅ Conclusion</p><p>In this tutorial, you learned how to implement Pipeline as Code by integrating Jenkins with GitHub using SSH authentication. Starting from SSH key configuration, you created a version-controlled “Jenkinsfile”, configured a Jenkins Pipeline job using Pipeline Script from SCM, established secure repository access through Jenkins Credentials, and successfully executed the pipeline.</p><p>Beyond the implementation itself, this project demonstrated several core DevOps principles, including automation, version control, secure credential management, and Continuous Integration (CI). These practices form the foundation for building reliable, maintainable, and scalable CI/CD pipelines in real-world environments.</p><p>While this tutorial focused on a simple Pipeline, the same approach can be extended to include automated testing, code quality analysis, artifact management, containerization, and deployment workflows as your DevOps expertise continues to grow.</p><p>I hope this guide has helped you better understand how Pipeline as Code works in Jenkins and provided a practical implementation that you can adapt to your own projects. Thank you for reading, and I wish you success on your DevOps learning journey.</p><p>— -</p><p>📂 Project Repository</p><p>The complete source code, project documentation, screenshots, and implementation details for this project are available on GitHub.</p><p>GitHub Repository:</p><p><a href="https://github.com/olajide-adedayo/jenkins-pipeline-as-code">https://github.com/olajide-adedayo/jenkins-pipeline-as-code</a></p><p>The repository includes:</p><p>- A comprehensive, recruiter-friendly “README.md”</p><p>- Architecture overview</p><p>- Implementation details</p><p>- Project screenshots</p><p>- Troubleshooting guide</p><p>- Lessons learned</p><p>- Skills demonstrated</p><p>— -</p><p>👨‍💻 About the Author</p><p>Olajide Adedayo is an AWS Cloud and DevOps Engineer with hands-on experience building cloud infrastructure, implementing Continuous Integration (CI), Pipeline as Code, containerization, and automation using industry-standard DevOps tools and AWS services.</p><p>He is passionate about documenting real-world projects, sharing practical knowledge with the DevOps community, and continuously expanding his expertise through hands-on learning.</p><p>Connect with Me</p><p>- GitHub: <a href="https://github.com/olajide-adedayo">https://github.com/olajide-adedayo</a></p><p>- LinkedIn: <a href="https://www.linkedin.com/in/olajide-adedayo-9126593b3/">https://www.linkedin.com/in/olajide-adedayo-9126593b3/</a></p><p>- Medium: <a href="https://medium.com/@olajideadedayo230">https://medium.com/@olajideadedayo230</a></p><p>— -</p><p>📢 Call to Action</p><p>If you found this tutorial helpful, I would appreciate your support by:</p><p>- 👏 Clapping for this article.</p><p>- 💬 Sharing your thoughts or questions in the comments.</p><p>- 🔖 Following me on Medium for more hands-on AWS Cloud and DevOps tutorials.</p><p>- ⭐ Starring the GitHub repository if you found the project useful.</p><p>- 🤝 Connecting with me on LinkedIn to grow our professional network.</p><p>Thank you for reading, and I look forward to sharing more practical DevOps projects and tutorials with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ca537fbb7d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerizing a Java Application with Docker and Publishing Images to Amazon ECR Using Jenkins…]]></title>
            <link>https://medium.com/@olajideadedayo230/containerizing-a-java-application-with-docker-and-publishing-images-to-amazon-ecr-using-jenkins-3ead22fca896?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ead22fca896</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[amazon-ecr]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 14:37:47 GMT</pubDate>
            <atom:updated>2026-08-05T04:32:47.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGSJ8N9nRdkIYlNtMFIZQA.jpeg" /></figure><p>Containerizing a Java Application with Docker and Publishing Images to Amazon ECR Using Jenkins Pipeline</p><p>Introduction</p><p>Continuous Integration (CI) is one of the fundamental practices in modern DevOps, enabling development teams to automate software builds, testing, code quality analysis, artifact management, containerization, and deployment preparation. By automating these processes, organizations can deliver software faster, improve reliability, and detect issues early in the development lifecycle.</p><p>In this hands-on tutorial, you will learn how to build an end-to-end Continuous Integration (CI) pipeline that automates the complete build workflow of a Java application using Jenkins Pipeline. Along the way, you will integrate several widely adopted DevOps tools and AWS services, including Apache Maven, SonarQube, Nexus Repository Manager, Docker, Amazon Elastic Container Registry (Amazon ECR), Slack, and Amazon Web Services (AWS).</p><p>Rather than focusing only on the final result, this guide explains each step in detail so that beginners and aspiring DevOps Engineers can understand not only how to implement the solution, but also why each tool is used within the CI pipeline.</p><p>By the end of this tutorial, you will have successfully built a production-style CI pipeline capable of:</p><p>- Automatically retrieving source code from GitHub.</p><p>- Compiling and packaging a Java application with Maven.</p><p>- Running automated unit and integration tests.</p><p>- Performing static code analysis using SonarQube.</p><p>- Publishing versioned application artifacts to Nexus Repository Manager.</p><p>- Building an optimized Docker image using a multi-stage Dockerfile.</p><p>- Publishing Docker images to Amazon Elastic Container Registry (Amazon ECR).</p><p>- Sending automated build notifications to Slack.</p><p>Whether you are preparing for your first DevOps role, strengthening your AWS Cloud skills, or building a professional portfolio, this tutorial provides practical, real-world experience that mirrors the Continuous Integration workflows used by many engineering teams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeCQl7WP6CQuuzX1dPp3DQ.png" /></figure><p>What You’ll Learn</p><p>By following this tutorial from start to finish, you will gain practical experience in building and understanding a modern Continuous Integration (CI) pipeline using industry-standard DevOps tools and AWS services.</p><p>At the end of this tutorial, you will be able to:</p><p>- Build and configure a Jenkins Declarative Pipeline for a Java application.</p><p>- Automate application builds using Apache Maven.</p><p>- Execute automated unit and integration tests within the CI pipeline.</p><p>- Integrate SonarQube to perform static code quality analysis.</p><p>- Publish versioned application artifacts to Nexus Repository Manager.</p><p>- Build optimized Docker images using a multi-stage Dockerfile.</p><p>- Authenticate Jenkins with Amazon Elastic Container Registry (Amazon ECR).</p><p>- Push versioned Docker images to Amazon ECR automatically.</p><p>- Configure Slack to receive real-time CI pipeline notifications.</p><p>- Troubleshoot common CI pipeline and integration issues across Jenkins, Docker, SonarQube, Nexus Repository Manager, Amazon ECR, and AWS.</p><p>By completing this project, you will not only understand how each tool works individually but also how they integrate to form a reliable, automated Continuous Integration workflow used in real-world DevOps environments.</p><p>Project Overview</p><p>In this project, we will build an automated Continuous Integration (CI) pipeline for a Java web application using Jenkins Pipeline and a collection of widely adopted DevOps tools.</p><p>The pipeline begins by retrieving the application source code from GitHub. Jenkins then compiles and packages the application using Apache Maven, executes automated unit and integration tests, and performs static code analysis with SonarQube to evaluate code quality.</p><p>After a successful build and code quality analysis, the generated WAR artifact is published to Nexus Repository Manager for centralized artifact storage and version management.</p><p>Next, Jenkins builds a Docker image using a multi-stage Dockerfile. The image is tagged with both the Jenkins build number and the “latest” tag before being pushed to Amazon Elastic Container Registry (Amazon ECR).</p><p>Finally, Slack is integrated into the pipeline to send automated notifications, allowing team members to monitor the outcome of every pipeline execution in real time.</p><p>By the end of this tutorial, you will have implemented an end-to-end CI pipeline that demonstrates how multiple DevOps tools and AWS services work together to automate software delivery.</p><p>Pipeline Workflow</p><p>The complete workflow implemented in this tutorial follows the sequence below:</p><p>1. GitHub Source Code Checkout</p><p>2. Build Java Application with Apache Maven</p><p>3. Execute Unit Tests</p><p>4. Execute Integration Tests</p><p>5. Perform SonarQube Static Code Analysis</p><p>6. Publish WAR Artifact to Nexus Repository Manager</p><p>7. Build Docker Image Using a Multi-stage Dockerfile</p><p>8. Push Docker Image to Amazon Elastic Container Registry (Amazon ECR)</p><p>9. Send Build Status Notification to Slack</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQTKh9h54acAoBHDTp05Ww.png" /><figcaption>Figure 1: Successful execution of the Jenkins Declarative Pipeline showing all pipeline stages completed successfully, from source code checkout and application build to Docker image publication in Amazon Elastic Container Registry (Amazon ECR) and automated Slack notification.</figcaption></figure><p>Prerequisites</p><p>Before implementing this project, ensure you have the following prerequisites in place:</p><p>Technical Knowledge</p><p>A basic understanding of the following concepts will help you follow this tutorial more effectively:</p><p>- Linux command-line basics</p><p>- Git and GitHub fundamentals</p><p>- Java application development (basic understanding)</p><p>- Docker fundamentals</p><p>- AWS core services such as Amazon EC2, IAM, and Amazon ECR</p><p>Accounts Required</p><p>You should have active accounts for the following platforms:</p><p>- AWS Account</p><p>- GitHub Account</p><p>- Slack Workspace</p><p>Software Requirements</p><p>Install the following software on your local machine before starting the project:</p><p>- Git</p><p>- Visual Studio Code (or your preferred code editor)</p><p>- AWS CLI</p><p>- Docker Desktop (optional for local testing)</p><p>AWS Resources</p><p>This tutorial uses the following AWS services:</p><p>- Amazon EC2</p><p>- Amazon Elastic Container Registry (Amazon ECR)</p><p>- AWS Identity and Access Management (IAM)</p><p>Jenkins Server Requirements</p><p>The Jenkins server should be configured with:</p><p>- Java Development Kit (JDK 17)</p><p>- Apache Maven 3.9.14</p><p>- Docker</p><p>- AWS CLI</p><p>- Git</p><p>Estimated Completion Time</p><p>Depending on your familiarity with AWS and Jenkins, you should expect to complete this tutorial in approximately 2 to 4 hours, including configuration, validation, troubleshooting, and verification.</p><p>Solution Architecture</p><p>Before we begin the implementation, it is important to understand how the various DevOps tools and AWS services interact within the Continuous Integration (CI) pipeline.</p><p>The workflow starts when Jenkins retrieves the Java application source code from GitHub. Jenkins then builds the application using Apache Maven, executes unit and integration tests, and performs static code analysis with SonarQube.</p><p>Once the application passes the required build and testing stages, the generated WAR artifact is published to Nexus Repository Manager for centralized artifact storage and version management.</p><p>Next, Jenkins builds a Docker image using a multi-stage Dockerfile. The Docker image is tagged with both the Jenkins build number and the “latest” tag before being pushed to Amazon Elastic Container Registry (Amazon ECR).</p><p>Finally, Jenkins sends an automated notification to Slack, allowing team members to monitor the success or failure of every pipeline execution.</p><p>The architecture implemented in this tutorial is illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZypVTSuCr19atMnzp9QOQ.jpeg" /></figure><p>This architecture demonstrates how multiple DevOps tools work together to automate the software build lifecycle while ensuring code quality, artifact management, containerization, and team collaboration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9d0aHTLWo_9v5bXLSDlq9Q.png" /><figcaption>Figure 2.1: Amazon EC2 Service Home, the AWS service used to provision and manage the virtual servers required for the Continuous Integration (CI) pipeline.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycW9txi0QIqHtfvB0mn-Fw.png" /><figcaption>Figure 2.2: Amazon EC2 dashboard showing the infrastructure supporting the CI pipeline, including the Jenkins server, Maven build agent, SonarQube server, and Nexus Repository Manager, all running successfully.</figcaption></figure><p>AWS Infrastructure Setup</p><p>The first step in implementing this project is to provision the AWS infrastructure that will host the various components of the Continuous Integration (CI) pipeline.</p><p>In this tutorial, Amazon EC2 instances are used to host the Jenkins server, Maven build agent, SonarQube server, and Nexus Repository Manager. Each server is responsible for a specific task within the pipeline, creating a modular architecture that closely resembles real-world DevOps environments.</p><p>The infrastructure consists of the following servers:</p><p>Server| Purpose</p><p>Jenkins Server| Orchestrates the entire CI pipeline, coordinates build stages, and integrates with the other services.</p><p>Maven Build Agent| Executes Maven build jobs delegated by the Jenkins controller, enabling distributed builds.</p><p>SonarQube Server| Performs static code analysis to evaluate code quality and identify potential issues.</p><p>Nexus Repository Manager| Stores and manages versioned Maven artifacts generated during the build process.</p><p>Before installing any software, ensure that all EC2 instances are:</p><p>- Running successfully.</p><p>- Reachable via SSH.</p><p>- Configured with the required security group rules.</p><p>- Able to communicate with one another over the necessary ports.</p><p>Proper infrastructure planning is essential because every stage of the CI pipeline depends on reliable communication between these servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdpJIY1uVrJzw5X6Y4dw6w.png" /><figcaption>Figure 3: Amazon EC2 instances provisioned for the project, showing the Jenkins server, Maven build agent, SonarQube server, and Nexus Repository Manager running successfully before the software configuration phase.</figcaption></figure><p>Creating the Amazon Elastic Container Registry (Amazon ECR) Repository</p><p>Amazon Elastic Container Registry (Amazon ECR) is a fully managed container image registry provided by AWS. It enables you to securely store, manage, and distribute Docker images that can later be deployed to container orchestration platforms such as Amazon ECS, Amazon EKS, or self-managed Kubernetes clusters.</p><p>In this project, Amazon ECR is used to store the Docker image generated by the Jenkins Pipeline after the Java application has been successfully built, tested, analyzed, and containerized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DoiUnoQdZeI2KB7G6REdTA.jpeg" /></figure><p>Why Amazon ECR?</p><p>Amazon ECR provides several advantages for containerized applications running on AWS:</p><p>- Fully managed and highly available container image registry.</p><p>- Native integration with AWS Identity and Access Management (IAM).</p><p>- Secure image storage with private repositories.</p><p>- Easy integration with Jenkins and other CI/CD tools.</p><p>- Image versioning using tags such as build numbers and “latest”.</p><p>- Simplified authentication using the AWS CLI.</p><p>Creating the Repository</p><p>1. Sign in to the AWS Management Console.</p><p>2. Navigate to Amazon Elastic Container Registry (Amazon ECR).</p><p>3. Select Create repository.</p><p>4. Choose Private as the repository visibility.</p><p>5. Enter your preferred repository name.</p><p>6. Leave the remaining settings at their default values unless your project requires custom configurations.</p><p>7. Select Create repository.</p><p>After the repository has been created successfully, Jenkins will use it later in the pipeline to publish Docker images automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EkXzgFDK-boGYnJFE6NZoA.png" /><figcaption>Figure 4: Amazon Elastic Container Registry (Amazon ECR) Create repository page showing the configuration used before creating the private container image repository.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41gLYR7-t8hO_gV1V_oQNg.png" /><figcaption>Figure 5: Amazon Elastic Container Registry (Amazon ECR) repository successfully created and ready to receive Docker images generated by the Jenkins Pipeline.</figcaption></figure><p>Launching the Jenkins Server</p><p>Jenkins serves as the automation server that orchestrates the entire Continuous Integration (CI) pipeline. It is responsible for coordinating every stage of the build process, including source code retrieval, application compilation, testing, code quality analysis, artifact publication, Docker image creation, image publishing to Amazon Elastic Container Registry (Amazon ECR), and Slack notifications.</p><p>In this project, Jenkins is deployed on an Amazon EC2 instance, providing a dedicated environment for managing and executing the CI pipeline.</p><p>Steps to Launch the Jenkins Server</p><p>1. Sign in to the AWS Management Console.</p><p>2. Navigate to Amazon EC2.</p><p>3. Select Launch Instance.</p><p>4. Configure the instance with the appropriate:</p><p>- Name</p><p>- Amazon Machine Image (AMI)</p><p>- Instance type</p><p>- Key pair</p><p>- Network settings</p><p>- Storage</p><p>5. Review the configuration.</p><p>6. Select Launch Instance.</p><p>7. Wait until the instance reaches the Running state before connecting through SSH.</p><p>Once the Jenkins server is running, we will connect to the instance and begin installing the software required to build the CI pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36g8QPQ-kNNW7aHoTW1roA.png" /><figcaption>Figure 6.1: Amazon EC2 Launch Instance page showing the Jenkins server name and the selected Amazon Linux 2023 Amazon Machine Image (AMI).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4OUNAOe2gMhwpEdiR8HCg.png" /><figcaption>Figure 6.2: Amazon EC2 Launch Instance page showing the selected instance type and key pair used to provision and securely access the Jenkins server.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SMLOigiO9j4qS7VFjmSBA.png" /><figcaption>Figure 6.3: Amazon EC2 Launch Instance page showing the network settings and security group configuration for the Jenkins server.</figcaption></figure><p>Connecting to the Jenkins Server Using SSH</p><p>After successfully launching the Jenkins server, the next step is to establish a secure connection to the Amazon EC2 instance.</p><p>AWS provides Secure Shell (SSH) as the standard method for remotely accessing Linux-based EC2 instances. SSH enables administrators and DevOps engineers to install software, configure services, execute commands, and manage servers securely through the command line.</p><p>Why SSH?</p><p>SSH is widely used because it provides:</p><p>- Encrypted communication between your local computer and the remote server.</p><p>- Secure authentication using an EC2 key pair.</p><p>- Full administrative access to configure the Jenkins server.</p><p>- A reliable method for managing Linux servers without requiring a graphical interface.</p><p>Connecting to the Jenkins Server</p><p>Use the following command to connect to the Jenkins server:</p><p>ssh -i &lt;your-key-pair.pem&gt; ec2-user@&lt;jenkins-public-ip&gt;</p><p>Replace:</p><p>- “&lt;your-key-pair.pem&gt;” with the name of your downloaded EC2 private key.</p><p>- “&lt;jenkins-public-ip&gt;” with the public IP address or public DNS name of your Jenkins EC2 instance.</p><p>If the connection is successful, you should see the Amazon Linux command prompt, indicating that you are now logged into the Jenkins server and ready to begin the software installation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zaSVOdJKsJdOb_1gy68wQ.png" /><figcaption>Figure 7.1: Successful SSH connection to the Jenkins server with the Jenkins service verified as active (running), confirming that the server is operational and ready for CI pipeline configuration.</figcaption></figure><p>Installing Java Development Kit (JDK)</p><p>Jenkins is a Java-based automation server, which means Java must be installed before Jenkins can be deployed and started successfully.</p><p>For this project, the Jenkins server uses Amazon Linux 2023, and the Java Development Kit (JDK) is installed using the “dnf” package manager.</p><p>Why Install Java First?</p><p>Java provides the runtime environment required for Jenkins to execute. Without a supported JDK, the Jenkins service cannot start.</p><p>Update the System Packages</p><p>Before installing any software, update the system packages to ensure you are working with the latest available package versions.</p><p>sudo dnf update -y</p><p>Install Java</p><p>Install Amazon Corretto 17, which is supported by Jenkins.</p><p>sudo dnf install java-17-amazon-corretto -y</p><p>Verify the Installation</p><p>After the installation completes, verify that Java is installed successfully by checking its version.</p><p>java -version</p><p>If the installation is successful, the command will display the installed Java version along with the Amazon Corretto runtime information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFks4gDJVm88AokIW5TmAA.png" /><figcaption>Figure 8.1: Verification of the OpenJDK 21 installation on the Jenkins server using the “java -version” command, confirming that the Java runtime required by Jenkins is installed successfully.</figcaption></figure><p>Installing Jenkins</p><p>With Java installed successfully, the next step is to install Jenkins on the Amazon EC2 instance.</p><p>Jenkins is an open-source automation server that enables Continuous Integration (CI) by automating repetitive software development tasks such as building applications, executing tests, integrating code quality analysis, publishing artifacts, building Docker images, and sending notifications.</p><p>On Amazon Linux 2023, Jenkins is installed by adding the official Jenkins repository and then installing the Jenkins package using the “dnf” package manager.</p><p>Add the Jenkins Repository</p><p>sudo wget -O /etc/yum.repos.d/jenkins.repo <a href="https://pkg.jenkins.io/redhat-stable/jenkins.repo">https://pkg.jenkins.io/redhat-stable/jenkins.repo</a></p><p>Import the Jenkins Repository Key</p><p>sudo rpm — import <a href="https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key">https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key</a></p><p>Install Jenkins</p><p>sudo dnf install jenkins -y</p><p>After the installation completes, Jenkins is installed but not yet accessible through a web browser. In the next section, we will start the Jenkins service, configure it to start automatically after a reboot, and verify that it is running correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPeMvPOL6JiVCDbCB2uTxg.png" /><figcaption>Figure 9.1: Jenkins home directory (“/var/lib/jenkins”) showing the generated files and directories created after a successful installation and initial startup.</figcaption></figure><p>Accessing the Jenkins Web Interface</p><p>With the Jenkins service running successfully, the next step is to access the Jenkins web interface and complete the initial configuration.</p><p>By default, Jenkins listens on TCP port 8080. Before accessing the web interface, ensure that the Jenkins EC2 instance’s security group allows inbound traffic on port 8080 from your trusted IP address or network.</p><p>Open your preferred web browser and navigate to:</p><p>http://&lt;jenkins-public-ip&gt;:8080</p><p>Replace “&lt;jenkins-public-ip&gt;” with the public IP address or public DNS name of your Jenkins EC2 instance.</p><p>If the configuration is correct, the Jenkins Unlock Jenkins page will be displayed, prompting you to enter the initial administrator password generated during installation.</p><p>Retrieving the Initial Administrator Password</p><p>Jenkins stores the initial administrator password in a file on the server. Retrieve it by running the following command:</p><p>sudo cat /var/lib/jenkins/secrets/initialAdminPassword</p><p>Copy the displayed password and paste it into the Administrator password field on the Unlock Jenkins page.</p><p>After entering the password, select Continue to proceed with the initial Jenkins setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxxpBkFgrdqoUnUhAE3qLA.png" /><figcaption>Figure 11.1: Jenkins Unlock Jenkins page requesting the initial administrator password before the web-based configuration can begin.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0f4PRMfcE3tnTbtKAQpdw.png" /><figcaption>Figure 11.2: Jenkins login page displayed after completing the initial setup, allowing administrators to authenticate and access the Jenkins automation server.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yyd3182BXg6sYNReDFuPZQ.png" /><figcaption>Figure 11.3: Jenkins Dashboard after a successful login, providing the central interface for creating jobs, managing pipelines, configuring plugins, and administering the Continuous Integration (CI) environment.</figcaption></figure><p>Transition to Pipeline Configuration</p><p>At this stage, Jenkins has been installed successfully and is accessible through the web interface.</p><p>The remaining Jenkins administrative tasks — including installing plugins, configuring Global Tool Configuration, managing credentials, and creating the initial Continuous Integration (CI) pipeline — were completed as part of the foundational CI environment.</p><p>With the Jenkins platform fully configured, the remainder of this tutorial focuses on extending the existing CI pipeline to support Docker containerization and publishing Docker images to Amazon Elastic Container Registry (Amazon ECR) using a Jenkins Pipeline.</p><p>This approach reflects a real-world DevOps workflow, where organizations typically establish a stable CI platform before introducing containerization and cloud-based image registries.</p><p>Installing Docker on the Jenkins Server</p><p>To enable Jenkins to build and publish Docker images, Docker must be installed on the Jenkins server. Docker provides a lightweight containerization platform that packages applications together with their dependencies into portable, consistent, and reproducible container images.</p><p>By installing Docker on the Jenkins server, the pipeline can automatically build Docker images, tag them appropriately, and push them to Amazon Elastic Container Registry (Amazon ECR) without manual intervention.</p><p>Installing Docker</p><p>On Amazon Linux 2023, Docker can be installed using the “dnf” package manager.</p><p>sudo dnf install docker -y</p><p>After the installation completes, start the Docker service and configure it to start automatically whenever the server boots.</p><p>sudo systemctl start docker</p><p>sudo systemctl enable docker</p><p>To allow the Jenkins user to execute Docker commands without requiring “sudo”, add the Jenkins user to the Docker group.</p><p>sudo usermod -aG docker jenkins</p><p>Apply the updated group membership by restarting the Jenkins service.</p><p>sudo systemctl restart jenkins</p><p>Finally, verify that Docker has been installed successfully by checking its version.</p><p>docker — version</p><p>A successful installation displays the installed Docker Engine version, confirming that the Jenkins server is ready to build container images as part of the CI pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_9qL-MdAmePbQkgle_VnQ.png" /><figcaption>Figure 12.1: Verification of the Docker installation on the Jenkins server using the “docker — version” command, confirming that the server is ready to build container images.</figcaption></figure><p>Configuring Docker Permissions for the Jenkins User</p><p>Although Docker has been installed successfully, Jenkins cannot execute Docker commands immediately after installation. This is because the Jenkins service runs under a dedicated Linux user account (“jenkins”), which does not have permission to access the Docker daemon by default.</p><p>If this permission is not granted, Jenkins pipeline jobs that attempt to build or push Docker images will fail with a permission denied error when communicating with the Docker socket.</p><p>Add the Jenkins User to the Docker Group</p><p>Run the following command to add the Jenkins user to the Docker group:</p><p>sudo usermod -aG docker jenkins</p><p>The “-aG” option appends the Jenkins user to the Docker group without removing any existing group memberships.</p><p>Restart the Jenkins Service</p><p>After updating the group membership, restart the Jenkins service so the new permissions take effect.</p><p>sudo systemctl restart jenkins</p><p>Once the Jenkins service has restarted successfully, it can execute Docker commands as part of the CI pipeline without requiring elevated privileges.</p><p>«Best Practice: Grant only the minimum permissions required for Jenkins to perform its tasks. Following the principle of least privilege helps improve the security of your CI environment.»</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5LsyFI_WZgQIvgvAGyq7A.png" /><figcaption>Figure 13.1: Verification that the “jenkins” user has been added to the “docker” group, allowing Jenkins to execute Docker commands required for building and publishing container images during the CI pipeline.</figcaption></figure><p>Authenticating Jenkins with Amazon Elastic Container Registry (Amazon ECR)</p><p>Before Jenkins can push Docker images to Amazon Elastic Container Registry (Amazon ECR), it must first authenticate with AWS.</p><p>Amazon ECR uses AWS Identity and Access Management (IAM) to control access to private container repositories. Rather than using a traditional username and password, Jenkins authenticates securely using the AWS Command Line Interface (AWS CLI) to obtain a temporary authentication token.</p><p>This approach is more secure because the authentication token is short-lived and generated only when required by the pipeline.</p><p>Verify the AWS CLI Installation</p><p>Confirm that the AWS CLI is installed on the Jenkins server by running:</p><p>aws — version</p><p>A successful installation displays the installed AWS CLI version.</p><p>Authenticate Docker with Amazon ECR</p><p>Run the following command to authenticate Docker with your Amazon ECR registry:</p><p>aws ecr get-login-password — region &lt;aws-region&gt; | docker login — username AWS — password-stdin &lt;aws-account-id&gt;.dkr.ecr.&lt;aws-region&gt;.amazonaws.com</p><p>Replace:</p><p>- “&lt;aws-region&gt;” with the AWS Region where your Amazon ECR repository was created.</p><p>- “&lt;aws-account-id&gt;” with your AWS account ID.</p><p>If the authentication is successful, Docker returns the following message:</p><p>Login Succeeded</p><p>This confirms that the Jenkins server is now authorized to push Docker images to your private Amazon ECR repository.</p><p>Creating a Multi-Stage Dockerfile</p><p>After configuring the Jenkins environment, the next step is to containerize the Java application using Docker.</p><p>A Dockerfile is a text file that contains the instructions required to build a Docker image. In this project, a multi-stage Dockerfile is used to produce a smaller and more efficient production image by separating the application build process from the runtime environment.</p><p>Why Use a Multi-Stage Dockerfile?</p><p>A multi-stage Dockerfile provides several advantages:</p><p>- Reduces the final Docker image size.</p><p>- Excludes unnecessary build dependencies from the production image.</p><p>- Improves application security by minimizing the attack surface.</p><p>- Produces faster image downloads and deployments.</p><p>- Follows containerization best practices adopted in modern DevOps environments.</p><p>During the Jenkins Pipeline execution, Docker reads the Dockerfile, builds the application image, tags it appropriately, and prepares it for publication to Amazon Elastic Container Registry (Amazon ECR).</p><p>The Dockerfile used in this project follows industry best practices for containerizing Java applications and serves as the foundation for the automated image build process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCOPf7imkCYIxIHG1azQ4A.png" /><figcaption>Figure 15.1: Multi-stage Dockerfile used to build the Java application with Maven and package it into a lightweight Apache Tomcat runtime image, following containerization best practices for production deployments.</figcaption></figure><p>Understanding the Jenkins Pipeline</p><p>With the Dockerfile in place, the next step is to automate the build, containerization, and image publishing process using a Jenkins Declarative Pipeline.</p><p>A Jenkins Pipeline defines the sequence of automated tasks required to build the application from source code, create a Docker image, authenticate with Amazon Elastic Container Registry (Amazon ECR), and publish the image to a private container repository.</p><p>In this project, the pipeline eliminates repetitive manual tasks by orchestrating each stage in a consistent and repeatable manner. Every code change follows the same automated workflow, helping to improve reliability, reduce deployment errors, and accelerate software delivery.</p><p>The pipeline also integrates with supporting DevOps tools such as Maven for application builds, Nexus Repository Manager for artifact storage, Docker for containerization, Amazon ECR for image management, and Slack for build notifications.</p><p>This automation demonstrates a practical Continuous Integration (CI) workflow commonly adopted in modern DevOps environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxneXFc5ZjpS_ufzQQ9xww.png" /><figcaption>Figure 16.1: Jenkins Declarative Pipeline stages responsible for building the Docker image, tagging it with the Jenkins build number, and publishing both the versioned and “latest” image tags to Amazon Elastic Container Registry (Amazon ECR).</figcaption></figure><p>Jenkins Pipeline Workflow</p><p>With both the Dockerfile and Jenkinsfile in place, Jenkins can automate the complete containerization workflow from source code retrieval to publishing Docker images in Amazon Elastic Container Registry (Amazon ECR).</p><p>The pipeline implemented in this project performs the following high-level stages:</p><p>1. Retrieves the application source code from the Git repository.</p><p>2. Compiles and packages the Java application using Apache Maven.</p><p>3. Builds a Docker image using the multi-stage Dockerfile.</p><p>4. Authenticates with Amazon Elastic Container Registry (Amazon ECR).</p><p>5. Tags the Docker image using the Jenkins build number and the “latest” tag.</p><p>6. Pushes both image tags to the private Amazon ECR repository.</p><p>7. Executes post-build actions to report the pipeline status.</p><p>Automating these activities through a Jenkins Declarative Pipeline ensures consistency, repeatability, and reliability while eliminating manual deployment tasks. This approach aligns with modern DevOps practices for Continuous Integration (CI) and containerized application delivery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQTKh9h54acAoBHDTp05Ww.png" /><figcaption>Figure 17.1: Successful Jenkins Pipeline execution showing the automated stages responsible for building the application, containerizing it with Docker, authenticating with Amazon Elastic Container Registry (Amazon ECR), and publishing the Docker image.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3zgqkmy4TqH0NVqs2Rwlw.png" /><figcaption>Figure 17.2: Jenkins build console output displaying the detailed execution log of the pipeline, including application build, Docker image creation, Amazon ECR authentication, image tagging, and image publishing operations.</figcaption></figure><p>Docker Image Tagging Strategy</p><p>A consistent image tagging strategy is essential for managing container images throughout the software delivery lifecycle.</p><p>In this project, the Jenkins Pipeline publishes two tags for every successful build:</p><p>- Build Number Tag — A unique tag generated from the Jenkins build number (for example, “15”, “16”, or “17”). This provides traceability by allowing each Docker image to be associated with a specific pipeline execution.</p><p>- Latest Tag — A rolling tag that always references the most recently built and published image. This simplifies deployments in environments where the newest stable image should be used automatically.</p><p>Publishing both tags combines version traceability with operational convenience. If an issue is discovered in a newly deployed image, teams can quickly identify and redeploy a previous build using its unique build number tag.</p><p>This image versioning strategy is widely adopted in modern DevOps practices because it supports reproducible deployments, simplifies rollback procedures, and improves software release management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpYgGA5qwjJ26tSPZu6MPQ.png" /><figcaption>Figure 19.1: Docker image tags stored in Amazon Elastic Container Registry (Amazon ECR), illustrating the use of both the Jenkins build number and the “latest” tag to support image versioning, traceability, and deployment consistency.</figcaption></figure><p>Implementation Summary</p><p>This project demonstrates the successful implementation of an automated Continuous Integration (CI) workflow for a Java web application using Jenkins, Docker, and Amazon Elastic Container Registry (Amazon ECR).</p><p>Beginning with a fully configured Jenkins environment, the pipeline retrieves the application source code from GitHub, compiles the application with Apache Maven, builds a production-ready Docker image using a multi-stage Dockerfile, authenticates with Amazon ECR, and publishes the container image to a private repository.</p><p>By automating these activities, the pipeline eliminates repetitive manual processes, improves build consistency, and produces versioned Docker images that are ready for deployment to container orchestration platforms such as Amazon ECS, Amazon EKS, or Kubernetes.</p><p>Beyond the technical implementation, this project reinforces essential DevOps practices, including Infrastructure as Code, Continuous Integration, containerization, image versioning, secure registry authentication, and build automation. These practices form the foundation of modern cloud-native software delivery.</p><p>«Refer to Figure 1 for the complete solution architecture illustrating the end-to-end workflow, from source code retrieval in GitHub through the Jenkins CI Pipeline, Docker image creation, and publication to Amazon Elastic Container Registry (Amazon ECR).»</p><p>Troubleshooting</p><p>During the implementation of this project, several configuration and integration challenges were encountered and resolved. The following are some of the common issues and their solutions.</p><p>1. Docker Permission Denied</p><p>Issue</p><p>Jenkins was unable to execute Docker commands because the Jenkins user did not have permission to access the Docker daemon.</p><p>Resolution</p><p>Added the “jenkins” user to the Docker group and restarted the Jenkins service.</p><p>sudo usermod -aG docker jenkins</p><p>sudo systemctl restart jenkins</p><p>— -</p><p>2. Amazon ECR Authentication Failure</p><p>Issue</p><p>Docker could not authenticate with Amazon Elastic Container Registry (Amazon ECR) due to missing or invalid AWS credentials.</p><p>Resolution</p><p>Verified the AWS CLI configuration and authenticated Docker using the Amazon ECR login command with valid AWS credentials.</p><p>— -</p><p>3. Docker Image Build Failures</p><p>Issue</p><p>The Docker image build process failed due to configuration or dependency-related issues within the Dockerfile.</p><p>Resolution</p><p>Reviewed the Dockerfile configuration, corrected build instructions, and rebuilt the image after validating each stage of the multi-stage build.</p><p>— -</p><p>4. Jenkins Pipeline Execution Errors</p><p>Issue</p><p>Pipeline execution failed because of syntax errors, incorrect environment variables, or invalid pipeline configuration.</p><p>Resolution</p><p>Reviewed the Jenkinsfile, corrected the pipeline syntax, validated environment variables, and re-executed the pipeline successfully.</p><p>— -</p><p>Systematically troubleshooting each issue helped ensure a stable, repeatable, and production-ready Continuous Integration (CI) workflow.</p><p>Lessons Learned</p><p>Completing this project provided valuable hands-on experience in designing and implementing a modern Continuous Integration (CI) workflow using Jenkins, Docker, and Amazon Elastic Container Registry (Amazon ECR).</p><p>Some of the key lessons learned include:</p><p>- Building production-ready Docker images using a multi-stage Dockerfile.</p><p>- Automating application builds and container image creation with Jenkins Declarative Pipelines.</p><p>- Publishing versioned Docker images to Amazon Elastic Container Registry (Amazon ECR).</p><p>- Managing Docker permissions securely for Jenkins by using Linux groups.</p><p>- Understanding the importance of image tagging for version control, traceability, and rollback.</p><p>- Applying DevOps best practices to improve automation, consistency, and deployment reliability.</p><p>- Strengthening troubleshooting skills by identifying and resolving common CI pipeline integration issues.</p><p>- Reinforcing the value of Infrastructure as Code, automation, and repeatable build processes in modern cloud-native environments.</p><p>This project significantly enhanced my practical DevOps skills and strengthened my understanding of containerization, build automation, and cloud-based artifact management using AWS services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhSh36TgM4S5ysdrEUbMPA.jpeg" /></figure><p>Conclusion</p><p>In this tutorial, we successfully built an automated Continuous Integration (CI) workflow that containerizes a Java web application and publishes Docker images to Amazon Elastic Container Registry (Amazon ECR) using a Jenkins Declarative Pipeline.</p><p>Starting with the Jenkins server setup, we configured Docker, prepared the build environment, created a multi-stage Dockerfile, automated the build process with Jenkins, authenticated with Amazon ECR, and published versioned Docker images to a private container registry.</p><p>By completing this project, you have gained practical experience with several core DevOps technologies, including Jenkins, Docker, Apache Maven, GitHub, AWS CLI, and Amazon Elastic Container Registry (Amazon ECR). More importantly, you have learned how these tools work together to automate software delivery in a modern cloud environment.</p><p>The concepts and implementation covered in this tutorial provide a strong foundation for more advanced CI/CD workflows, including automated deployments to Amazon ECS, Amazon EKS, Kubernetes, and other container orchestration platforms.</p><p>Thank you for following this tutorial. I hope it serves as a practical reference for your DevOps learning journey, interview preparation, and future cloud-native projects.</p><p>About the Author</p><p>Hi, I’m Olajide Adedayo, an AWS Cloud &amp; DevOps Engineer passionate about building practical, cloud-native solutions using AWS and modern DevOps practices.</p><p>I enjoy designing and implementing hands-on projects involving Continuous Integration (CI), Continuous Delivery (CD), Infrastructure as Code (IaC), containerization, automation, and cloud technologies. Through my technical writing, I aim to simplify complex concepts and help aspiring Cloud and DevOps Engineers gain real-world implementation experience.</p><p>If you found this tutorial helpful, I’d be happy to connect and share more practical content on AWS Cloud and DevOps.</p><p>Connect with me:</p><p>- LinkedIn: <a href="https://www.linkedin.com/in/olajide-adedayo-9126593b3/">https://www.linkedin.com/in/olajide-adedayo-9126593b3/</a></p><p>- GitHub: <a href="https://github.com/olajide-adedayo">https://github.com/olajide-adedayo</a></p><p>Thank you for reading, and I wish you success on your Cloud and DevOps journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ead22fca896" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jenkins-Based Continuous Integration (CI) Pipeline with Distributed Build Architecture on AWS]]></title>
            <link>https://medium.com/@olajideadedayo230/jenkins-based-continuous-integration-ci-pipeline-with-distributed-build-architecture-on-aws-bd25e17616e0?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd25e17616e0</guid>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 21:33:51 GMT</pubDate>
            <atom:updated>2026-08-05T08:15:06.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VUWHyM_iM7mm5SMEYPkrQ.png" /></figure><p>Jenkins-Based Continuous Integration (CI) Pipeline with Distributed Build Architecture on AWS</p><p>Introduction</p><p>Modern software development is fast-paced and highly collaborative. In many organizations, multiple developers work on the same application simultaneously, contributing new features, fixing bugs, and pushing code changes to a shared source code repository multiple times each day. While this collaborative approach accelerates software development, it also introduces challenges when integrating frequent code changes into a single, stable application.</p><p>Traditionally, software delivery relied heavily on manual processes. After developers completed their work, the application had to be manually built, tested, packaged, and prepared for deployment. These activities often involved multiple teams handing work over to one another, creating delays, communication gaps, and opportunities for human error. As projects grew larger and development teams expanded, this manual approach frequently resulted in merge conflicts, integration issues, delayed feedback, slower release cycles, and reduced software quality.</p><p>Continuous Integration (CI) was introduced to solve these challenges by automating the process of integrating, building, and testing application code. Whenever developers commit their changes to a shared source code repository such as GitHub, a Continuous Integration platform automatically retrieves the latest code, compiles the application, executes automated tests, and immediately reports the build status. Instead of discovering problems weeks later, development teams receive rapid feedback, allowing issues to be identified and resolved much earlier in the software development lifecycle.</p><p>Continuous Integration works alongside Continuous Delivery (CD), another essential DevOps practice. While CI focuses on validating application code through automated build and testing processes, Continuous Delivery extends the workflow by packaging the validated application and preparing it for deployment into testing, staging, or production environments. Together, CI and CD enable organizations to release software more frequently, more reliably, and with significantly fewer defects.</p><p>Several platforms support CI/CD automation, including Jenkins, GitHub Actions, GitLab CI, and ArgoCD. Among these, Jenkins remains one of the most widely adopted automation servers because it provides a highly configurable environment for understanding the core principles of Continuous Integration. Its extensive plugin ecosystem, distributed build capabilities, and seamless integration with tools such as Git, Maven, Docker, Kubernetes, and cloud platforms make it an excellent choice for implementing enterprise-grade CI pipelines.</p><p>In this project, we implement a Jenkins-Based Continuous Integration (CI) Pipeline with Distributed Build Architecture on AWS. The solution uses AWS EC2, Ubuntu Linux, Git, GitHub, OpenJDK 21, and Apache Maven to automate the build lifecycle of a Java web application. Instead of executing build jobs directly on the Jenkins Controller, the workload is delegated to a dedicated Jenkins Agent (MAVEN-BUILDER) through secure SSH communication. This distributed architecture improves scalability, optimizes resource utilization, and closely reflects how Continuous Integration pipelines are implemented in real-world enterprise DevOps environments.</p><p>Throughout this article, every concept, configuration, command, validation step, troubleshooting procedure, and best practice will be explained in detail. By the end of this project, you will have a clear understanding of how a Jenkins-based Continuous Integration pipeline operates and how distributed build architecture can be used to create a scalable, production-oriented CI environment on AWS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gup4N-rB0hnFLQswNFTMIw.png" /></figure><p>Project Overview</p><p>Continuous Integration (CI) is one of the fundamental practices in modern DevOps, enabling development teams to integrate code changes frequently while automatically validating every integration through build and testing processes. Instead of relying on manual build activities that are time-consuming and prone to human error, CI automates repetitive tasks, allowing teams to detect and resolve issues much earlier in the software development lifecycle.</p><p>This project demonstrates the implementation of a Jenkins-Based Continuous Integration (CI) Pipeline with Distributed Build Architecture on AWS. The solution automates the build lifecycle of a Java-based web application by integrating GitHub as the source code repository, Apache Maven as the build automation tool, and Jenkins as the Continuous Integration platform.</p><p>The infrastructure is deployed on Amazon Web Services (AWS) using Ubuntu Linux EC2 instances. Jenkins is installed and configured on a dedicated Controller server, while build execution is delegated to a separate Jenkins Agent named MAVEN-BUILDER. The Controller communicates securely with the Agent over SSH, allowing build workloads to be executed on the Agent instead of consuming resources on the Controller. This distributed build architecture closely mirrors enterprise DevOps environments, where multiple build agents are used to improve scalability, performance, and resource utilization.</p><p>The pipeline begins when the application source code is retrieved from the project&#39;s GitHub repository. Jenkins then initiates the Maven build process, resolves project dependencies from Maven Central Repository, compiles the application, executes automated unit tests, packages the application into a deployable WAR file, and archives the generated artifact for future deployment or download. In this project, the Maven build is executed using the command:</p><p>mvn clean install</p><p>Upon successful execution, Maven generates the following deployable artifact:</p><p>target/vprofile-v2.war</p><p>To support this implementation, the Jenkins environment is configured with OpenJDK 21, Apache Maven 3.9.x, Git, and the required Jenkins plugins. The Jenkins Controller manages job scheduling, source code integration, and build orchestration, while the MAVEN-BUILDER Agent is responsible for compiling the application, running automated tests, and generating the WAR artifact.</p><p>Beyond demonstrating a functional CI pipeline, this project also addresses practical operational challenges commonly encountered in real-world environments. During the implementation, issues such as SSH credential configuration, agent connectivity, Java version compatibility, build execution on the wrong node, and Maven dependency download delays were identified and resolved. These troubleshooting activities reinforce essential DevOps skills in Jenkins administration, AWS infrastructure management, Linux system administration, and Continuous Integration pipeline debugging.</p><p>By completing this project, you will gain practical experience implementing a scalable Jenkins-based Continuous Integration environment that reflects industry practices and provides a strong foundation for more advanced CI/CD workflows involving code quality analysis, artifact repositories, automated deployments, and enterprise pipeline automation.</p><p>Learning Objectives</p><p>By completing this project, you will gain practical experience designing and implementing a Jenkins-based Continuous Integration (CI) pipeline using a distributed build architecture on AWS. You will understand not only how the solution is built, but also why each component is required and how they work together to automate the software build process.</p><p>At the end of this project, you will be able to:</p><p>Understand the core concepts of Continuous Integration (CI) and its role within the DevOps lifecycle.</p><p>Explain the difference between Continuous Integration (CI) and Continuous Delivery (CD).</p><p>Understand why organizations adopt CI pipelines to reduce manual effort, accelerate software delivery, and improve code quality.</p><p>Install and configure Jenkins on an AWS EC2 Ubuntu server.</p><p>Understand why OpenJDK 21 is required to run Jenkins and build Java applications.</p><p>Configure Jenkins to use essential development tools, including Git and Apache Maven.</p><p>Understand the architecture and responsibilities of a Jenkins Controller and Jenkins Agent.</p><p>Configure a dedicated Jenkins build agent (MAVEN-BUILDER) for distributed build execution using SSH.</p><p>Integrate Jenkins with a GitHub repository for automated source code retrieval.</p><p>Execute a Maven build using the mvn clean install command.</p><p>Understand the Maven build lifecycle, including dependency resolution, compilation, testing, packaging, and installation.</p><p>Generate a deployable WAR artifact (vprofile-v2.war) and archive it within Jenkins.</p><p>Verify successful build execution using the Jenkins dashboard, build history, and console output.</p><p>Troubleshoot common Continuous Integration issues, including SSH connectivity, credential configuration, Java installation problems, build execution on the wrong node, and Maven dependency resolution.</p><p>Apply real-world DevOps practices by implementing a scalable Jenkins distributed build architecture similar to those used in enterprise environments.</p><p>By the end of this project, you will have built a production-inspired Continuous Integration environment that establishes a strong foundation for more advanced DevOps workflows, including Pipeline as Code, static code analysis with SonarQube, artifact management with Nexus Repository Manager, and fully automated CI/CD pipelines.</p><p>Prerequisites</p><p>Before implementing the Jenkins-Based Continuous Integration (CI) Pipeline with Distributed Build Architecture on AWS, ensure that the following requirements are available. These prerequisites provide the foundation for successfully completing the project and following each implementation step without interruption.</p><p>AWS Account</p><p>You should have an active AWS account with sufficient permissions to provision and manage Amazon EC2 instances. Throughout this project, AWS EC2 is used to host both the Jenkins Controller and the Jenkins Build Agent.</p><p>Basic Linux Knowledge</p><p>A basic understanding of Linux command-line operations is recommended. During the project, you will connect to Ubuntu EC2 instances using SSH and execute administrative commands to install, verify, and manage Jenkins and other required software.</p><p>SSH Key Pair</p><p>Create an AWS EC2 key pair that will be used to securely connect to your Ubuntu servers. In this project, the key pair is also used to establish secure communication between the Jenkins Controller and the Jenkins Build Agent.</p><p>Internet Connectivity</p><p>Ensure that your local computer has a stable internet connection. Internet access is required to connect to the AWS Management Console, access the Jenkins web interface, download software packages, and retrieve project dependencies from Maven Central Repository.</p><p>Web Browser</p><p>A modern web browser such as Google Chrome, Microsoft Edge, Mozilla Firefox, or Safari is required to access both the AWS Management Console and the Jenkins web interface.</p><p>GitHub Repository Access</p><p>The source code for the Java web application is stored in a GitHub repository. Jenkins will retrieve the application source code directly from GitHub during the build process.</p><p>Repository URL:</p><p>https://github.com/HKHcoder/vprofile-project.git</p><p>Java Development Kit (JDK)</p><p>Since Jenkins is a Java-based automation server and the application being built is a Java web application, OpenJDK 21 is required. The JDK provides both the Java Runtime Environment (JRE) needed to run Jenkins and the development tools required to compile and build Java applications using Maven.</p><p>Apache Maven</p><p>Apache Maven is the build automation tool used throughout this project. Maven manages project dependencies, compiles the application source code, executes automated tests, packages the application into a deployable WAR file, and installs the generated artifact as part of the build lifecycle.</p><p>Git</p><p>Git is required for source code version control. Jenkins uses Git to clone the latest version of the application from the GitHub repository whenever a build is executed.</p><p>Jenkins</p><p>Jenkins serves as the Continuous Integration (CI) platform that orchestrates the entire build workflow. It integrates with GitHub, coordinates build execution, manages build agents, archives generated artifacts, and provides centralized monitoring through its web-based dashboard.</p><p>Recommended Skills</p><p>Although this article explains every step in detail, having a basic understanding of the following concepts will make it easier to follow along:</p><p>Continuous Integration (CI) fundamentals</p><p>Version Control with Git</p><p>Basic Java application structure</p><p>Linux terminal navigation</p><p>AWS EC2 fundamentals</p><p>Maven build lifecycle</p><p>SSH connectivity</p><p>Technology Stack</p><p>The successful implementation of this Continuous Integration (CI) pipeline relies on a combination of industry-standard DevOps tools and AWS cloud services. Each component plays a specific role in automating the software build process and supporting the distributed Jenkins architecture implemented in this project.</p><p>TechnologyVersionPurposeJenkinsLatest Stable ReleaseContinuous Integration (CI) automation server used to orchestrate the build workflow, manage jobs, and coordinate build execution.Amazon EC2Cloud ServiceHosts the Jenkins Controller and Jenkins Build Agent on Ubuntu Linux virtual servers.Ubuntu Linux24.04 LTSOperating system used for both the Jenkins Controller and Jenkins Build Agent.OpenJDK21Required to run Jenkins and compile the Java-based application during the Maven build process.Apache Maven3.9.xBuild automation and dependency management tool used to compile, test, package, and install the application.GitLatest Stable ReleaseDistributed version control system used by Jenkins to retrieve the application source code from GitHub.GitHubCloud ServiceCentralized source code repository hosting the VProfile application used throughout this project.SSHSecure ShellProvides secure communication between the Jenkins Controller and the Jenkins Build Agent for distributed build execution.Maven Central RepositoryCloud RepositoryPublic repository from which Maven downloads all required project dependencies during the build process.Java Web ApplicationVProfile ProjectSample enterprise Java application used to demonstrate the Continuous Integration pipeline.WAR (Web Application Archive)Build ArtifactDeployable application package generated by Maven after a successful build.</p><p>How These Technologies Work Together</p><p>The project begins with the application source code stored in a GitHub repository. Jenkins retrieves the latest version of the code using Git whenever a build is initiated.</p><p>The Jenkins Controller coordinates the entire build process but delegates the actual build execution to a dedicated Jenkins Build Agent (MAVEN-BUILDER) over a secure SSH connection. This distributed architecture prevents the Controller from becoming overloaded and provides a scalable approach for handling build workloads.</p><p>On the Build Agent, Apache Maven resolves all required project dependencies from the Maven Central Repository, compiles the application source code using OpenJDK 21, executes automated unit tests, packages the application into a WAR file, and installs the generated artifact as part of the Maven build lifecycle.</p><p>After the build completes successfully, Jenkins records the build status, archives the generated WAR artifact, and makes the build information available through the Jenkins dashboard for verification and future reference.</p><p>Together, these technologies form a complete Continuous Integration solution that automates source code retrieval, build execution, testing, artifact generation, and build reporting while following industry-standard DevOps practices.</p><p>Architecture Overview</p><p>This project implements a Jenkins Distributed Build Architecture on Amazon Web Services (AWS) to automate the Continuous Integration (CI) process for a Java-based web application. Instead of executing build jobs directly on the Jenkins Controller, the project offloads build execution to a dedicated Jenkins Build Agent. This architecture improves scalability, optimizes resource utilization, and reflects how Continuous Integration pipelines are commonly implemented in enterprise DevOps environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwuTA_mNvb5ojVNddHdpGQ.png" /></figure><p>The architecture consists of two primary servers deployed as Amazon EC2 instances:</p><p>Jenkins Controller</p><p>Jenkins Build Agent (MAVEN-BUILDER)</p><p>Each server has a clearly defined responsibility, ensuring that management tasks and build execution are separated.</p><p>Jenkins Controller</p><p>The Jenkins Controller serves as the central management server for the entire Continuous Integration environment. It is responsible for coordinating build activities rather than performing the actual build process.</p><p>In this project, the Jenkins Controller performs the following responsibilities:</p><p>Managing Jenkins jobs.</p><p>Integrating with the GitHub source code repository.</p><p>Scheduling and orchestrating build execution.</p><p>Managing Jenkins plugins and global configurations.</p><p>Managing connected Jenkins Agents.</p><p>Collecting build results and console output.</p><p>Archiving generated build artifacts.</p><p>Displaying build history and execution status through the Jenkins dashboard.</p><p>Jenkins Build Agent (MAVEN-BUILDER)</p><p>The Jenkins Build Agent is a dedicated Ubuntu EC2 instance responsible for executing the actual build workload assigned by the Jenkins Controller.</p><p>The Build Agent is configured with:</p><p>OpenJDK 21</p><p>Apache Maven 3.9.x</p><p>Git</p><p>Remote workspace located at:</p><p>/opt/jenkins</p><p>The Agent connects securely to the Jenkins Controller using SSH and is configured with the node label:</p><p>MAVEN-BUILDER</p><p>To ensure that all build jobs execute on the Build Agent, Jenkins is configured to restrict build execution to the MAVEN-BUILDER node, preventing build workloads from consuming resources on the Controller.</p><p>During pipeline execution, the Build Agent performs the following tasks:</p><p>Retrieves the project source code from GitHub.</p><p>Resolves project dependencies from Maven Central Repository.</p><p>Compiles the application source code.</p><p>Executes automated unit tests.</p><p>Packages the application into a deployable WAR file.</p><p>Returns the build results to the Jenkins Controller.</p><p>Architecture Workflow</p><p>The following workflow illustrates how the different components interact throughout the Continuous Integration process:</p><p>GitHub Repository │ │ ▼ Jenkins Controller (AWS EC2) │ Schedules and Manages Builds │ SSH Connection │ ▼ Jenkins Build Agent (AWS EC2 - MAVEN-BUILDER) │ ▼ Maven Build Execution │ ▼ Compile → Test → Package → Install │ ▼ WAR Artifact (vprofile-v2.war) │ ▼ Build Status &amp; Artifact Archived in Jenkins</p><p>This workflow demonstrates how Jenkins coordinates the build process while delegating resource-intensive tasks to the Build Agent, allowing the Controller to remain available for managing additional jobs and agents.</p><p>Benefits of the Distributed Build Architecture</p><p>Implementing a distributed Jenkins architecture provides several operational advantages over executing builds directly on the Controller.</p><p>Key benefits include:</p><p>Improved scalability by allowing additional build agents to be added as workload increases.</p><p>Better resource utilization by separating management tasks from build execution.</p><p>Faster build execution through dedicated build resources.</p><p>Reduced workload on the Jenkins Controller, improving overall system responsiveness.</p><p>Easier maintenance and troubleshooting due to the clear separation of responsibilities.</p><p>A production-inspired architecture that closely reflects enterprise Continuous Integration environments.</p><p>This architectural approach forms the foundation of the Continuous Integration pipeline implemented throughout this project and prepares the environment for integrating additional DevOps tools such as SonarQube, Nexus Repository Manager, and Pipeline as Code in later stages of the DevOps workflow.</p><p>GitHub Repository</p><p>│</p><p>▼</p><p>Jenkins Controller</p><p>(AWS EC2)</p><p>│</p><p>SSH Connection</p><p>│</p><p>▼</p><p>Jenkins Build Agent</p><p>(MAVEN-BUILDER)</p><p>│</p><p>▼</p><p>Maven Build Execution</p><p>│</p><p>▼</p><p>WAR Artifact Generation</p><p>│</p><p>▼</p><p>Jenkins Artifact Archive</p><p>Purpose: This architecture diagram provides a high-level overview of the distributed Continuous Integration (CI) pipeline. It illustrates how the GitHub repository, Jenkins Controller (AWS EC2), Jenkins Build Agent (MAVEN-BUILDER), Maven build process, and artifact generation work together before the implementation steps are presented.</p><p>Project Workflow</p><p>Before diving into the implementation, it is helpful to understand how the different components interact throughout the Continuous Integration (CI) process. Rather than viewing the project as a collection of individual tasks, think of it as a connected workflow where each stage prepares the application for the next stage.</p><p>In this project, Jenkins automates the build lifecycle of a Java web application by integrating with GitHub, executing Maven build tasks on a dedicated Jenkins Build Agent, and generating a deployable artifact. The entire workflow is coordinated by the Jenkins Controller, while the resource-intensive build operations are performed on the MAVEN-BUILDER Agent.</p><p>The workflow implemented in this project consists of the following stages:</p><p>Provision the Jenkins Infrastructure</p><p>Launch the required Amazon EC2 instances.</p><p>Install and configure Jenkins on the Controller server.</p><p>Prepare the Build Agent with the required software and dependencies.</p><p>Configure the Continuous Integration Environment</p><p>Configure Jenkins for administrative access.</p><p>Install and configure the required build tools.</p><p>Configure secure SSH communication between the Controller and the Build Agent.</p><p>Register the Build Agent as the MAVEN-BUILDER node.</p><p>Integrate Source Code Management</p><p>Connect Jenkins to the GitHub repository containing the application source code.</p><p>Configure Jenkins to retrieve the latest version of the project whenever a build is initiated.</p><p>Execute the Maven Build</p><p>Delegate the build to the MAVEN-BUILDER Agent.</p><p>Resolve project dependencies from Maven Central Repository.</p><p>Compile the application source code.</p><p>Execute automated unit tests.</p><p>Package the application into a deployable WAR file.</p><p>Install the generated artifact as part of the Maven build lifecycle.</p><p>Archive and Verify Build Results</p><p>Archive the generated WAR artifact in Jenkins.</p><p>Review the build summary and console output.</p><p>Confirm that the build completed successfully.</p><p>Verify that the build executed on the MAVEN-BUILDER Agent.</p><p>The overall Continuous Integration workflow can be summarized as follows:</p><p>Developer │ ▼ Push Code to GitHub │ ▼ Jenkins Controller │ ▼ Delegate Build to MAVEN-BUILDER │ ▼ Git Clone │ ▼ Maven Dependency Resolution │ ▼ Compile Source Code │ ▼ Run Unit Tests │ ▼ Package Application (WAR) │ ▼ Archive Artifact │ ▼ Build Status Available in Jenkins</p><p>By following this workflow, the Continuous Integration pipeline automatically validates application code, produces a deployable artifact, and provides immediate feedback on the success or failure of the build process. This automation reduces manual effort, improves consistency, and establishes a scalable foundation for more advanced DevOps practices such as static code analysis, artifact repository management, and Continuous Delivery.</p><p>Step 1: Provisioning the Jenkins Server on Amazon EC2</p><p>The first phase of this project was to provision a dedicated Jenkins server on Amazon Elastic Compute Cloud (Amazon EC2). This server serves as the central automation platform responsible for orchestrating Continuous Integration (CI) tasks such as source code retrieval, application builds, automated testing, and artifact generation.</p><p>Rather than using a local virtual machine, Jenkins was deployed on an AWS EC2 instance to simulate a real-world cloud environment commonly used by DevOps teams. This approach provides better accessibility, scalability, and closely mirrors production infrastructure.</p><p>For this implementation, I launched an EC2 instance with the following configuration:</p><p>Operating System: Amazon Linux 2023</p><p>Amazon Machine Image (AMI): Amazon Linux 2023 (Kernel 6.1)</p><p>Instance Type: t3.small</p><p>Key Pair: olajide-key</p><p>Storage: 8 GiB General Purpose SSD (gp3)</p><p>Security Group: jenkins-sg</p><p>Region: US East (N. Virginia) – us-east-1</p><p>The security group was configured to allow inbound traffic on the required ports:</p><p>TCP 22 (SSH): Secure remote administration of the EC2 instance.</p><p>TCP 8080 (Jenkins): Access to the Jenkins web interface from a browser.</p><p>After configuring the instance details, networking, storage, and security settings, the EC2 instance was launched successfully. The generated olajide-key.pem private key was securely stored on the local machine and later used to establish SSH connectivity to the Jenkins server.</p><p>Screenshots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DuKxykb7ku7PvFdjmlsA5g.png" /></figure><p>Figure 1: AWS EC2 Console Home (01-aws-ec2-service-home.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHHfeqNAfa329E2elALPxQ.png" /></figure><p>Figure 2: EC2 Instances Dashboard (02-aws-ec2-dashboard.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVsSY3HS3_9rEBnBrWOouQ.png" /></figure><p>Figure 3: Launch Instance – Name and Amazon Linux 2023 AMI (03-aws-ec2-name-and-ami-configuration.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4R1DeBDC6oBRzUOfgNp8A.png" /></figure><p>Figure 4: Instance Type and Key Pair Selection (04-aws-instance-type-key-pair.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXsiil6W7L8uT1jvBBGB9w.png" /></figure><p>Figure 5: Stored olajide-key.pem on the Local Machine (05-olajide-key-pem-file.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olVaZFYkVigexbBuZqCMDQ.png" /></figure><p>Figure 6: Network Configuration (06-aws-network-settings-overview.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoowQeTEL93w_GYeLFWcLg.png" /></figure><p>Figure 7: Security Group Configuration (07-aws-security-group-rules.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsvAMuPmbQDiL8PpRuIfWg.png" /></figure><p>Figure 8: Storage Configuration (08-aws-storage-configuration.png)</p><p>Key Takeaway: Proper EC2 provisioning and secure network configuration form the foundation of a reliable Jenkins environment. Selecting an appropriate instance type, protecting the SSH private key, and exposing only the required ports are essential security and operational best practices for hosting Jenkins on AWS.</p><p>Step 2: Connecting to the Jenkins Server via SSH and Verifying the Installation</p><p>After successfully launching the EC2 instance, the next step was to establish a secure connection to the server using SSH (Secure Shell). SSH provides encrypted remote access, allowing administrators to install software, manage system configurations, and perform maintenance tasks from a local machine.</p><p>Using the previously generated olajide-key.pem private key, I connected to the Amazon Linux 2023 EC2 instance from my Windows PowerShell terminal. Once the connection was established, I verified that the server was accessible and ready for the Jenkins installation.</p><p>With SSH access confirmed, I proceeded to validate the Jenkins environment by checking the status of the Jenkins service. Verifying that the service is active (running) is an important step because it confirms that Jenkins has started successfully and is ready to accept web requests on port 8080.</p><p>Next, I verified the installed Java version. Since Jenkins is a Java-based automation server, a supported Java Runtime Environment (JRE/JDK) must be available before Jenkins can operate correctly. In this implementation, Amazon Corretto OpenJDK 21 was installed and successfully detected on the server.</p><p>To further familiarize myself with the Jenkins installation, I also inspected the Jenkins home directory. This directory stores critical Jenkins data, including job configurations, plugins, build history, credentials, logs, and other application metadata. Understanding its location is useful for troubleshooting, backups, and future administration tasks.</p><p>Screenshots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZchNM3v-VOAdyQ3kZVGdA.png" /></figure><p>Figure 9: SSH Connection to the Jenkins Server (09-jenkins-ssh-login.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dByWanlF4Dc09zTbWVP_Lg.png" /></figure><p>Figure 10: Jenkins Service Status – Active (Running) (10-jenkins-service-active-running.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFks4gDJVm88AokIW5TmAA.png" /></figure><p>Figure 11: OpenJDK 21 Installation Verification (11-openjdk-21-installation-verification.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPeMvPOL6JiVCDbCB2uTxg.png" /></figure><p>Figure 12: Jenkins Home Directory (12-jenkins-home-directory.png)</p><p>Key Commands Used</p><p>ssh -i olajide-key.pem ec2-user@&lt;EC2-PUBLIC-IP&gt; sudo systemctl status jenkins java -version ls -ld /var/lib/jenkins</p><p>Key Takeaway: Before accessing the Jenkins web interface, always verify that SSH connectivity is working, the Jenkins service is running, and Java is correctly installed. These simple validation steps help identify configuration issues early and provide a solid foundation for the remaining stages of the CI pipeline setup.</p><p>Step 3: Accessing the Jenkins Web Interface and Completing the Initial Setup</p><p>With the Jenkins service running successfully, the next step was to access the Jenkins web interface through a web browser. Jenkins listens on port 8080 by default, so the application was accessed using the public IP address of the EC2 instance followed by port 8080.</p><p>During the first launch, Jenkins displayed the Unlock Jenkins page. This security measure prevents unauthorized access during the initial setup process by requiring an administrator password generated during the installation.</p><p>After providing the initial administrator password, the Jenkins setup wizard guided the installation of the recommended plugins. These plugins extend Jenkins with additional functionality, enabling integration with popular DevOps tools such as Git, Maven, Pipeline, and many others. Once the plugins were installed, I created the first administrator account to secure the Jenkins instance and personalize future access.</p><p>After authentication, the Jenkins Dashboard became available. The dashboard serves as the central management interface where administrators can create and manage jobs, configure build tools, install plugins, monitor build history, manage distributed build agents, and administer the Jenkins environment.</p><p>At this stage, the Jenkins installation was fully operational and ready to support Continuous Integration (CI) workflows.</p><p>Screenshots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxxpBkFgrdqoUnUhAE3qLA.png" /></figure><p>Figure 13: Jenkins Unlock Page (13-jenkins-unlock-page.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0f4PRMfcE3tnTbtKAQpdw.png" /></figure><p>Figure 14: Jenkins Login Page (14-jenkins-login-page.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yyd3182BXg6sYNReDFuPZQ.png" /></figure><p>Figure 15: Jenkins Dashboard Home (15-jenkins-dashboard-home.png)</p><p>Note: During the initial setup, Jenkins prompts for the installation of the recommended plugins and the creation of the first administrator account. These one-time configuration steps establish the foundation for a secure and fully functional Jenkins environment.</p><p>Key Takeaway: The Jenkins Dashboard is the command center for CI/CD automation. From this interface, DevOps engineers create build jobs, configure tools, manage plugins, administer build agents, and monitor the health of software delivery pipelines.</p><p>Step 4: Understanding Jenkins Jobs – Freestyle vs Pipeline as Code</p><p>Before building a Continuous Integration (CI) pipeline, it is important to understand how Jenkins organizes automation tasks. In Jenkins, every automated process is executed through a Job. A job defines the sequence of actions Jenkins performs, such as checking out source code, compiling an application, running automated tests, packaging artifacts, and deploying software.</p><p>Jenkins provides several job types, but the two most commonly used are Freestyle Projects and Pipeline as Code.</p><p>A Freestyle Project is configured entirely through the Jenkins graphical user interface (GUI). Users create a job by completing forms and selecting configuration options such as source code management, build steps, triggers, and post-build actions. This approach is straightforward and ideal for learning Jenkins fundamentals because it allows beginners to understand each stage of the build process without writing pipeline code.</p><p>However, as projects grow in complexity, GUI-based jobs become difficult to maintain, duplicate, and version-control. For this reason, modern DevOps practices favor Pipeline as Code, where the entire build and deployment workflow is defined in a text file called a Jenkinsfile. Because the pipeline is stored alongside the application source code, it can be version-controlled, reviewed, and reused across multiple environments, making it more scalable and maintainable.</p><p>Although this project ultimately implements Pipeline-based automation, the journey begins with a Freestyle project to establish a solid understanding of Jenkins job execution, workspace management, build history, and artifact handling. These foundational concepts make it much easier to understand more advanced CI/CD pipelines later in the project.</p><p>Screenshot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHjAg50fImOWHYaMmA3QCg.png" /></figure><p>Figure 16: Jenkins New Item Page Showing Available Job Types (20-jenkins-new-item-freestyle-project.png)</p><p>Freestyle vs Pipeline as Code</p><p>FeatureFreestyle ProjectPipeline as CodeConfigurationGraphical User Interface (GUI)Jenkinsfile (Code)Version ControlNot built-inFully version-controlledReusabilityLimitedHighScalabilitySuitable for simple jobsSuitable for enterprise CI/CD pipelinesRecommended UseLearning and small automation tasksProduction-ready CI/CD workflows</p><p>Key Takeaway: Freestyle projects provide an excellent introduction to Jenkins automation, while Pipeline as Code represents the industry standard for building scalable, repeatable, and maintainable CI/CD pipelines. Understanding both approaches is an essential skill for every DevOps engineer.</p><p>Step 5: Configuring Build Tools in Jenkins</p><p>With Jenkins successfully installed and accessible through the web interface, the next step was to configure the build tools required to automate the application build process.</p><p>Jenkins does not execute build tasks on its own. Instead, it integrates with external tools such as Git, Java Development Kit (JDK), and Apache Maven through plugins and tool configurations. These tools enable Jenkins to retrieve source code, compile Java applications, resolve project dependencies, and package applications into deployable artifacts.</p><p>To configure these tools, I navigated to Manage Jenkins → Tools, where Jenkins provides centralized management for build tool installations.</p><p>Configuring the Java Development Kit (JDK)</p><p>Since the VProfile application is a Java-based application, configuring the JDK was the first priority. My Jenkins environment was configured with two versions of Amazon Corretto:</p><p>JDK 17</p><p>JDK 21</p><p>Both installations were configured manually by specifying their respective JAVA_HOME directories on the Jenkins server. Maintaining multiple JDK versions allows Jenkins to build projects with different Java version requirements while providing flexibility for future upgrades.</p><p>Configuring Git</p><p>Git was configured to use the default system installation located at:</p><p>/usr/bin/git</p><p>This configuration enables Jenkins to communicate with remote Git repositories, clone source code, and fetch project updates during every build.</p><p>Configuring Apache Maven</p><p>Apache Maven was configured using Jenkins&#39; automatic installation feature.</p><p>The Maven tool was registered with the following configuration:</p><p>Tool Name: Maven 3.9.14</p><p>Installation Method: Install automatically</p><p>Installer: Install from Apache</p><p>Version: 3.9.14</p><p>By managing Maven directly within Jenkins, build jobs can automatically download and use the correct Maven version without requiring additional manual installation on the controller.</p><p>Why Plugins Matter</p><p>Jenkins relies on plugins to extend its capabilities. While Git, Maven, and the JDK are installed on the operating system, Jenkins requires the corresponding plugins to recognize and use these tools within build jobs.</p><p>In simple terms:</p><p>The operating system provides the tool.</p><p>The Jenkins plugin provides the integration.</p><p>Both components are required for successful build automation.</p><p>Screenshots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXbP9fihxMnlFfHzf8eBzg.png" /></figure><p>Figure 17: Manage Jenkins (16-jenkins-manage-jenkins.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SP3xwyPUBSowtDYb6Gmxsw.png" /></figure><p>Figure 18: JDK Installations (17-jenkins-jdk-installations.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDrMYv8mhn4ptAnE1JEaig.png" /></figure><p>Figure 19: Git Installation (18-jenkins-git-installation.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZ64ncLHMTf99v8EV3W7_Q.png" /></figure><p>Figure 20: Maven Installation (19-jenkins-maven-installation.png)</p><p>Key Takeaway: A successful Jenkins build depends on more than installing Jenkins itself. Properly configuring Git, the JDK, and Maven ensures that Jenkins can retrieve source code, compile Java applications, and produce reliable build artifacts. This centralized tool configuration also promotes consistency and reproducibility across all build jobs.</p><p>Step 6: Creating the First Jenkins Freestyle Job</p><p>After configuring the required build tools, the next step was to create the first Jenkins job. A Jenkins job defines the sequence of tasks that Jenkins executes to automate a software development process. These tasks may include retrieving source code from a Git repository, compiling the application, running tests, packaging the application, and publishing build artifacts.</p><p>To create the job, I selected New Item from the Jenkins Dashboard, entered a meaningful job name, selected Freestyle Project, and clicked OK. Although modern CI/CD pipelines are typically implemented using Pipeline as Code, a Freestyle project provides an excellent starting point for understanding the core concepts of Jenkins job configuration and execution.</p><p>Unlike the instructor&#39;s introductory demonstration, which focused on executing basic Linux shell commands, this project applied the same concepts to a practical Maven-based Continuous Integration workflow. The job was configured to retrieve the VProfile application source code from GitHub and prepare it for automated builds.</p><p>Within the job configuration, Jenkins provides several important sections:</p><p>Description – Documents the purpose of the job.</p><p>Source Code Management (SCM) – Specifies the Git repository containing the application source code.</p><p>Build Triggers – Defines how and when the job should run, such as manually, on a schedule, or after source code changes.</p><p>Build Environment – Provides additional options to customize the build environment.</p><p>Build Steps – Specifies the commands or build tools Jenkins should execute. In this project, Apache Maven was used to automate the application build process.</p><p>Post-build Actions – Defines activities that occur after the build completes, such as archiving artifacts or sending notifications.</p><p>Learning from Build Failures</p><p>During the initial configuration, the first build failed because the Git repository URL had not been configured correctly. Jenkins displayed the following error in the console output:</p><p>FATAL: Git repository URL is empty. Checkout requires a valid repository URL.</p><p>Rather than being a setback, this failure demonstrated one of Jenkins&#39; most valuable features—its detailed console output. By reviewing the build logs, I quickly identified the root cause, corrected the repository configuration, and reran the build successfully.</p><p>This experience reinforced an important DevOps principle: build failures are valuable feedback mechanisms that help identify configuration issues early in the software delivery process.</p><p>Screenshots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHjAg50fImOWHYaMmA3QCg.png" /></figure><p>Figure 21: Creating a New Freestyle Project (20-jenkins-new-item-freestyle-project.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofyZB3dOM0mOwFUkpSCrnQ.png" /></figure><p>Figure 22: First Maven Jenkins Job (04-jenkins-first-maven-job.png)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tU0PL46eQr8tI6r120wEg.png" /></figure><p>Figure 23: Initial Build Failure and Console Output (05-first-build-failure-console-output.png)</p><p>Key Takeaway: Creating a Jenkins job is more than clicking through a configuration wizard. It defines the automation workflow that Jenkins executes repeatedly and consistently. Even when builds fail, Jenkins provides detailed diagnostic information that enables engineers to troubleshoot issues efficiently and continuously improve their CI pipeline.</p><p>Step 7: Executing the First Successful Maven Build</p><p>After resolving the initial configuration issue, the Jenkins Freestyle job was updated with the correct Git repository details and the appropriate Maven build configuration. With these changes in place, Jenkins was able to successfully retrieve the application source code and execute the build process.</p><p>During execution, Jenkins performed the Continuous Integration workflow in a structured sequence:</p><p>Connected to the configured Git repository.</p><p>Checked out the latest version of the VProfile application source code.</p><p>Used the configured Apache Maven installation to resolve project dependencies.</p><p>Compiled the Java source code.</p><p>Packaged the application into a deployable WAR (Web Application Archive) file.</p><p>Recorded the build status and generated detailed execution logs.</p><p>One of the key strengths of Jenkins is its ability to provide complete visibility into every stage of the build. The Console Output displays each command executed, the progress of the Maven build, dependency downloads, compilation results, and the final build status. This detailed logging makes troubleshooting significantly easier whenever a build fails.</p><p>Another important concept introduced during this stage is the Jenkins Workspace. Each Jenkins job is allocated a dedicated workspace on the server where source code is checked out and build activities are performed. The workspace acts as a temporary working directory during the build process and contains the project files, generated artifacts, and build logs until they are cleaned or archived.</p><p>As the project grows, this workspace becomes the foundation for subsequent stages such as static code analysis with SonarQube, artifact publication to Nexus Repository, and deployment automation.</p><p>Build Verification</p><p>A successful Maven build confirms that:</p><p>Jenkins can communicate with the Git repository.</p><p>Git is correctly configured.</p><p>The configured JDK is functioning properly.</p><p>Apache Maven can resolve project dependencies.</p><p>The application source code compiles successfully.</p><p>Jenkins is ready for more advanced CI/CD integrations.</p><p>Key Takeaway: A successful build is more than a green status indicator. It validates that Jenkins, Git, Java, Maven, and the application source code are working together correctly, establishing a reliable foundation for the remaining stages of the CI/CD pipeline.</p><p>Step 8: Provisioning the Maven Build Agent on Amazon EC2</p><p>To implement a distributed build architecture, I provisioned a dedicated Amazon EC2 instance to serve as the Jenkins Maven Build Agent. Instead of executing build tasks on the Jenkins controller, this separate server was responsible for performing the Maven build operations, allowing the controller to focus on job orchestration and pipeline management.</p><p>The Maven Build Agent was launched with the following configuration:</p><p>Instance Name: maven-agent</p><p>Operating System: Ubuntu Server 24.04.4 LTS (Noble Numbat)</p><p>AMI: ubuntu-noble-24.04-amd64-server-20260610</p><p>Platform: Linux/UNIX</p><p>Instance Type: t3.small</p><p>AWS Region: US East (N. Virginia) (us-east-1)</p><p>Availability Zone: us-east-1b</p><p>Key Pair: olajide-key</p><p>Security Group: maven-agent-sg</p><p>A dedicated build agent provides a cleaner separation of responsibilities within the Continuous Integration environment. While the Jenkins controller manages job scheduling, configuration, and monitoring, the build agent executes the resource-intensive tasks such as source code compilation and application packaging.</p><p>This architecture closely reflects real-world enterprise DevOps environments, where build execution is distributed across multiple agents to improve scalability, performance, and maintainability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqmOOH-epQe5TbJE0ivtzw.png" /></figure><p>Figure 24: Maven Build Agent – Ubuntu Server Verification (21-maven-agent-ubuntu-hostname-verification.png)</p><p>Key Takeaway: Provisioning a dedicated Maven Build Agent separates build execution from the Jenkins controller, creating a scalable and maintainable Continuous Integration architecture that aligns with industry best practices.</p><p>Step 9: Preparing the Maven Build Agent</p><p>With the EC2 instance provisioned successfully, the next step was to prepare the Maven Build Agent with the tools required to execute Jenkins build jobs.</p><p>A standard Java application build requires three essential components:</p><p>Git – Retrieves the application source code from the GitHub repository.</p><p>OpenJDK – Provides the Java runtime and compiler required by Maven.</p><p>Apache Maven – Resolves project dependencies, compiles the application, executes the build lifecycle, and packages the application into a deployable WAR file.</p><p>The Ubuntu server was verified to be running OpenJDK 21.0.11 and Git 2.43.0. Rather than installing Maven manually on the operating system, I configured Apache Maven 3.9.14 through Jenkins Global Tool Configuration using the Install automatically option.</p><p>When a Jenkins job requires Maven, Jenkins automatically downloads and manages the configured version under its tools directory. This approach ensures consistent build environments and simplifies tool management across multiple build agents.</p><p>The Maven installation was successfully verified on the build agent, confirming that all required tools were available for distributed build execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ubqnG3vgv04lr7OgxOQog.png" /></figure><p>Figure 25: Maven Build Agent – Build Tools Verification (22-maven-agent-build-tools-verification.png)</p><p>Why This Approach Matters</p><p>Managing build tools through Jenkins provides several advantages:</p><p>Consistent tool versions across all Jenkins jobs.</p><p>Simplified administration without manually installing every tool on each server.</p><p>Easier maintenance and upgrades through Jenkins Global Tool Configuration.</p><p>Improved reproducibility of build environments across multiple agents.</p><p>At this stage, the Maven Build Agent was fully prepared and ready to receive build requests from the Jenkins controller.</p><p>Key Takeaway: Verifying the build environment before connecting the agent to Jenkins helps ensure reliable and repeatable build execution. By combining Git, OpenJDK, and Jenkins-managed Maven, the build agent becomes fully equipped to support enterprise Continuous Integration workflows.</p><p>Step 10: Configuring the Jenkins Controller to Communicate with the Maven Build Agent</p><p>After preparing the Maven Build Agent, the next step was to establish secure communication between the Jenkins controller and the remote build server. This enables Jenkins to delegate build execution to the agent instead of running resource-intensive tasks on the controller itself.</p><p>From the Jenkins dashboard, I navigated to Manage Jenkins → Nodes, where I created a new permanent agent named maven-agent.</p><p>The agent was configured with the following key settings:</p><p>Node Name: maven-agent</p><p>Node Type: Permanent Agent</p><p>Remote Root Directory: A dedicated workspace on the Ubuntu server</p><p>Labels: maven</p><p>Usage: Only build jobs with the matching label</p><p>Launch Method: Launch agents via SSH</p><p>Host: Public IP address of the Maven Build Agent</p><p>Credentials: SSH private key associated with the olajide-key key pair</p><p>Using the Launch agents via SSH method, the Jenkins controller securely connected to the Ubuntu EC2 instance over SSH. Once the connection was established, Jenkins automatically prepared the remote workspace and made the agent available for executing build jobs.</p><p>This configuration forms the foundation of a distributed Jenkins architecture. Instead of performing compilation on the controller, Jenkins dispatches build requests to the remote Maven agent, where the source code is checked out, compiled, and packaged.</p><p>By separating orchestration from build execution, the Continuous Integration environment becomes more scalable, easier to maintain, and better suited for production workloads.</p><p>Key Takeaway: Configuring a Jenkins agent over SSH enables the controller to distribute build workloads to dedicated build servers, improving performance while keeping the controller focused on job orchestration and pipeline management.</p><p>Step 11: Creating the First Jenkins Freestyle Job</p><p>With the Jenkins controller successfully connected to the Maven Build Agent, the next step was to create a Freestyle Project. Although Freestyle jobs are not the preferred approach for production CI/CD pipelines, they provide an excellent way to understand the fundamental concepts of Jenkins before moving to Pipeline as Code.</p><p>From the Jenkins dashboard, I selected New Item, entered the job name, and chose Freestyle project as the project type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHjAg50fImOWHYaMmA3QCg.png" /></figure><p>Figure 26: Creating a New Jenkins Freestyle Project (20-jenkins-new-item-freestyle-project.png)</p><p>The Freestyle job serves as an introduction to how Jenkins executes automated tasks. Within the job configuration, Jenkins provides several important sections, each serving a specific purpose:</p><p>Description – Documents the purpose of the job.</p><p>Source Code Management – Specifies where the application source code is retrieved.</p><p>Build Triggers – Defines when the job should run, either manually, on a schedule, or automatically after source code changes.</p><p>Build Environment – Configures environment-specific options before execution.</p><p>Build Steps – Executes commands such as compiling code, running tests, or packaging applications.</p><p>Post-build Actions – Performs tasks after a successful build, such as archiving artifacts or sending notifications.</p><p>For this introductory exercise, the objective was not to build the VProfile application, but rather to become familiar with the Jenkins job interface and understand how Jenkins executes commands before implementing a complete Continuous Integration workflow.</p><p>Key Takeaway: Freestyle projects provide an excellent learning environment for understanding Jenkins fundamentals, including job configuration, build execution, workspaces, and build history, before progressing to Pipeline as Code.</p><p>Step 12: Understanding Jenkins Workspace and Build Execution</p><p>Every Jenkins job executes within a dedicated workspace, which serves as the working directory for that specific job. When a build starts, Jenkins checks out the project source code into the workspace and performs all build-related activities there, including dependency resolution, compilation, testing, and artifact generation.</p><p>Each job has its own isolated workspace, preventing interference between different projects and ensuring a clean build environment.</p><p>When a build is triggered, Jenkins records detailed execution information in the Console Output. The console log provides complete visibility into every stage of the build process, including:</p><p>Job initialization</p><p>Source code checkout</p><p>Workspace location</p><p>Maven command execution</p><p>Build progress</p><p>Success or failure messages</p><p>This information is invaluable when troubleshooting build failures because it identifies the exact stage where an error occurred.</p><p>Another important concept is the distinction between the workspace and build artifacts. The workspace is a temporary working directory where Jenkins performs build operations, while artifacts are the final output of a successful build, such as a WAR file. These artifacts can be archived by Jenkins, making them available for future deployment or download even after the workspace has been cleaned.</p><p>Understanding how Jenkins manages workspaces and artifacts is fundamental to building reliable Continuous Integration pipelines, especially when builds are executed on remote agents in a distributed architecture.</p><p>Key Takeaway: The Jenkins workspace is the temporary environment where builds are executed, while archived artifacts represent the permanent output of a successful build. The Console Output bridges these two by providing complete visibility into the execution process.</p><p>Step 13: Executing the Distributed Maven Build</p><p>With the Jenkins controller and Maven Build Agent successfully configured, the Continuous Integration workflow was executed by triggering the Jenkins job. Instead of performing the build on the controller, Jenkins delegated the workload to the remote MAVEN-BUILDER agent through a secure SSH connection.</p><p>The build process consisted of the following stages:</p><p>Retrieving the latest source code from the GitHub repository.</p><p>Executing the Maven build lifecycle on the remote agent.</p><p>Resolving project dependencies.</p><p>Compiling the Java source code.</p><p>Packaging the application into a deployable WAR file.</p><p>Reporting the build status back to the Jenkins controller.</p><p>This demonstrated how Jenkins can centrally manage build execution while distributing resource-intensive tasks across dedicated build agents.</p><p>Step 14: Generating and Archiving the WAR Artifact</p><p>Upon successful completion of the Maven build, Jenkins generated a Web Application Archive (WAR) file containing the packaged VProfile application.</p><p>The generated artifact was archived within Jenkins, providing a permanent record of the successful build. Archiving build artifacts enables consistent deployments, simplifies troubleshooting, and ensures that validated application packages remain available for future release activities.</p><p>Step 15: End-to-End Continuous Integration Workflow</p><p>The completed Continuous Integration pipeline followed this execution flow:</p><p>GitHub Repository │ ▼ Jenkins Controller (AWS EC2) │ │ SSH Connection ▼ Jenkins Agent (AWS EC2 - MAVEN-BUILDER) │ ▼ Maven Build Execution │ ▼ WAR Artifact Generation │ ▼ Artifact Archiving in Jenkins</p><p>This architecture demonstrates how Jenkins orchestrates the build process while delegating execution to a dedicated build server, resulting in a scalable and maintainable Continuous Integration environment.</p><p>Challenges Encountered and Solutions</p><p>During the implementation of this project, several practical challenges were encountered and resolved:</p><p>Correctly configuring Jenkins Global Tool Configuration for JDK and Maven.</p><p>Establishing secure SSH communication between the Jenkins controller and the Maven Build Agent.</p><p>Troubleshooting build failures using Jenkins Console Output.</p><p>Updating AWS Security Group inbound rules after a change in the client&#39;s public IP address prevented SSH access to the Maven agent.</p><p>Verifying Jenkins-managed Maven installation on the remote build agent.</p><p>Resolving these issues strengthened my understanding of Jenkins administration, AWS networking, Linux server management, and distributed build architectures.</p><p>Key Lessons Learned</p><p>This project provided hands-on experience with several core DevOps concepts, including:</p><p>Installing and configuring Jenkins on AWS EC2.</p><p>Managing build tools through Jenkins Global Tool Configuration.</p><p>Implementing a distributed Jenkins architecture using a remote build agent.</p><p>Configuring secure SSH communication between Jenkins nodes.</p><p>Automating Java application builds with Apache Maven.</p><p>Generating and archiving deployable build artifacts.</p><p>Troubleshooting Continuous Integration pipelines using Jenkins Console Output and build logs.</p><p>These practical skills closely align with the responsibilities of a DevOps Engineer responsible for designing, maintaining, and optimizing enterprise Continuous Integration environments.Conclusion</p><p>In this project, I successfully designed and implemented a Jenkins-Based Continuous Integration (CI) Pipeline with Distributed Build Architecture on AWS. By separating the Jenkins controller from the Maven Build Agent, I created a scalable CI environment capable of executing automated Java application builds while maintaining centralized pipeline management.</p><p>Throughout the implementation, I configured Jenkins, integrated Git and Maven, established secure controller-to-agent communication over SSH, executed distributed Maven builds, and generated deployable WAR artifacts. The project also reinforced the importance of infrastructure automation, build consistency, artifact management, and effective troubleshooting.</p><p>This implementation serves as a solid foundation for more advanced DevOps workflows, including enterprise CI/CD pipelines, automated code quality analysis, artifact repository integration, and deployment automation, which are explored in the subsequent projects of this series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkbYofIf3nWtos0nBxgBmQ.png" /></figure><p>Conclusion</p><p>In this project, I successfully designed and implemented a Jenkins-Based Continuous Integration (CI) Pipeline with Distributed Build Architecture on AWS. By separating the Jenkins controller from the Maven Build Agent, I created a scalable CI environment capable of executing automated Java application builds while maintaining centralized pipeline management.</p><p>Throughout the implementation, I configured Jenkins, integrated Git and Maven, established secure controller-to-agent communication over SSH, executed distributed Maven builds, and generated deployable WAR artifacts. The project also reinforced the importance of infrastructure automation, build consistency, artifact management, and effective troubleshooting.</p><p>This implementation serves as a solid foundation for more advanced DevOps workflows, including enterprise CI/CD pipelines, automated code quality analysis, artifact repository integration, and deployment automation, which are explored in the subsequent projects of this series.</p><p>About the Author</p><p>Olajide Adedayo is an AWS Cloud and DevOps Engineer with hands-on experience in designing and implementing cloud infrastructure, CI/CD pipelines, containerization, DevSecOps, and infrastructure automation. He is passionate about building production-ready solutions, documenting real-world projects, and continuously expanding his expertise in modern cloud technologies.</p><p>He shares practical tutorials and implementation guides to help aspiring and experienced engineers strengthen their cloud and DevOps skills through real-world, portfolio-driven projects.</p><p>Connect with me:</p><p>- LinkedIn: <a href="https://www.linkedin.com/in/olajideadedayo/">https://www.linkedin.com/in/olajideadedayo/</a><br>- GitHub: <a href="https://github.com/olajide-adedayo">https://github.com/olajide-adedayo</a><br>- Medium: <a href="https://medium.com/@olajideadedayo230">https://medium.com/@olajideadedayo230</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd25e17616e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Enterprise Continuous Integration (CI) Pipeline on AWS Using Jenkins, Maven, SonarQube…]]></title>
            <link>https://medium.com/@olajideadedayo230/building-an-enterprise-continuous-integration-ci-pipeline-on-aws-using-jenkins-maven-sonarqube-1d08051691ef?source=rss-de7fc210865a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d08051691ef</guid>
            <dc:creator><![CDATA[Olajideadedayo]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 07:45:57 GMT</pubDate>
            <atom:updated>2026-07-03T07:45:57.942Z</atom:updated>
            <content:encoded><![CDATA[<p>Building an Enterprise Continuous Integration (CI) Pipeline on AWS Using Jenkins, Maven, SonarQube, Nexus Repository, and GitHub (Part 1)</p><p>Section 2 – Designing and Provisioning the AWS Infrastructure</p><p>Prerequisites: This section assumes you have an active AWS account with permission to create EC2 instances, Security Groups, and Key Pairs.</p><p>Why AWS?</p><p>Amazon Web Services (AWS) was selected because it is one of the most widely adopted cloud platforms in the industry. It provides reliable, scalable, and secure infrastructure suitable for both learning and enterprise workloads.</p><p>Using AWS for this project offers several advantages:</p><p>On-demand infrastructure provisioning</p><p>Pay-as-you-go pricing</p><p>High availability across multiple Availability Zones</p><p>Secure networking through VPCs and Security Groups</p><p>Easy integration with DevOps tools</p><p>Practical experience that aligns with industry expectations</p><p>Throughout this project, all services were deployed on Amazon EC2 instances within the same AWS region.</p><p>Infrastructure Design</p><p>Instead of deploying every component on a single server, the environment was divided into four dedicated servers.</p><p>ServerPurposeOperating SystemInstance TypeJenkins ControllerPipeline orchestrationAmazon Linux 2023t3.smallMaven Build AgentExecutes Maven buildsAmazon Linux 2023t3.smallSonarQube ServerCode quality analysisUbuntu 24.04 LTSt3.smallNexus Repository ServerArtifact repositoryAmazon Linux 2023t3.small</p><p>Separating these workloads follows enterprise best practices and makes troubleshooting significantly easier.</p><p>Why t3.small?</p><p>Each EC2 instance was launched using the t3.small instance type.</p><p>Typical specifications:</p><p>2 vCPUs</p><p>2 GB RAM</p><p>Burstable performance</p><p>Suitable for laboratory environments and small production workloads</p><p>Although SonarQube generally benefits from additional memory, this project demonstrates how to optimize a smaller instance by adding swap space later in the implementation.</p><p>Server Responsibilities</p><p>1. Jenkins Controller</p><p>Responsibilities include:</p><p>Hosting the Jenkins web interface</p><p>Managing CI jobs</p><p>Coordinating pipeline execution</p><p>Managing credentials</p><p>Communicating with GitHub, SonarQube, Nexus, and build agents</p><p>This server does not compile the application directly. Instead, it delegates build tasks to a remote Maven build agent.</p><p>2. Maven Build Agent</p><p>The build agent performs all resource-intensive build operations.</p><p>Responsibilities include:</p><p>Cloning source code</p><p>Running Maven</p><p>Executing unit tests</p><p>Running Checkstyle</p><p>Running SonarScanner</p><p>Packaging the application</p><p>Deploying artifacts to Nexus</p><p>Separating builds from the controller improves performance and reflects common enterprise deployment models.</p><p>3. SonarQube Server</p><p>The SonarQube server performs static code analysis.</p><p>Responsibilities include:</p><p>Receiving analysis reports</p><p>Calculating quality metrics</p><p>Detecting bugs</p><p>Detecting vulnerabilities</p><p>Measuring code duplication</p><p>Reporting maintainability</p><p>Displaying dashboards</p><p>The server stores its data in PostgreSQL and is exposed through Nginx acting as a reverse proxy.</p><p>4. Nexus Repository Manager</p><p>The Nexus server provides centralized artifact storage.</p><p>Responsibilities include:</p><p>Storing Maven artifacts</p><p>Version management</p><p>Repository hosting</p><p>Artifact retrieval for future deployments</p><p>Instead of storing generated binaries in GitHub, the build pipeline publishes them to Nexus Repository Manager.</p><p>Security Groups</p><p>Each EC2 instance was assigned its own Security Group.</p><p>This approach provides better isolation and follows the principle of least privilege.</p><p>Jenkins Security Group</p><p>Required inbound ports:</p><p>PortProtocolPurpose22TCPSSH administration8080TCPJenkins Web Interface</p><p>Maven Agent Security Group</p><p>Required inbound ports:</p><p>PortProtocolPurpose22TCPSSH access from Jenkins Controller</p><p>No web ports are required because the Maven Agent does not host a web application.</p><p>SonarQube Security Group</p><p>Required inbound ports:</p><p>PortProtocolPurpose22TCPSSH administration80TCPNginx Reverse Proxy9000TCPSonarQube Application (used during setup and testing)</p><p>In a production environment, it is recommended to expose only port 80 publicly and restrict direct access to port 9000.</p><p>Nexus Security Group</p><p>Required inbound ports:</p><p>PortProtocolPurpose22TCPSSH administration8081TCPNexus Repository Web Interface</p><p>SSH Key Pairs</p><p>AWS uses SSH key pairs instead of passwords for secure server access.</p><p>During this project, separate key pairs were used for different servers, including:</p><p>olajide-key</p><p>sonar-key</p><p>nexus-key</p><p>Using SSH key authentication provides stronger security than password-based login and is the standard approach for managing Linux EC2 instances.</p><p>Networking Considerations</p><p>All EC2 instances were deployed within the same AWS Virtual Private Cloud (VPC).</p><p>This allowed:</p><p>Secure communication between servers</p><p>SSH connectivity</p><p>Jenkins-to-Agent communication</p><p>SonarQube integration</p><p>Nexus artifact deployment</p><p>Although the services were reachable through public IP addresses during implementation, they also communicated within the same cloud network.</p><p>Verifying Instance Health</p><p>After launching each EC2 instance, AWS performs automated health checks.</p><p>Before installing any software, verify that every instance reports:</p><p>Instance State: Running Status Checks: 3/3 checks passed</p><p>Proceed with software installation only after all health checks have completed successfully.</p><p>Screenshot Reference</p><p>Capture the following screenshot before continuing:</p><p>Screenshot 01 – AWS EC2 Infrastructure</p><p>The screenshot should clearly display:</p><p>Jenkins Controller</p><p>Maven Build Agent</p><p>SonarQube Server</p><p>Nexus Repository Server</p><p>Instance state: Running</p><p>Status checks passed</p><p>This screenshot documents the completed cloud infrastructure before software installation begins.</p><p>Interview Insight</p><p>A common interview question is:</p><p>Why use separate Security Groups instead of assigning one Security Group to every server?</p><p>A strong answer is:</p><p>Separate Security Groups allow each server to expose only the network ports required for its specific role. This improves security, simplifies troubleshooting, and aligns with the principle of least privilege, which is a common security practice in enterprise cloud environments.</p><p>End of Part 1 (Section 2).</p><p>In the next section, we will begin preparing each server for software installation by discussing operating system selection, package management, initial server configuration, connectivity verification, and the rationale behind the installation sequence used throughout the project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d08051691ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>