NTI & iVolve Accelerator Complete 28 Labs Clean Code & Solved Prompts

DevOps Accelerator — Complete Labs & Solutions Guide

Clear, practical explanations written for developers and interns. Covers the real problem, visual workflow diagrams, exact slide questions, working configuration files, and colorful terminal commands for all 28 labs.

28 Hands-On Labs
6 Core Modules
100% Solved & Verified
Clickable Direct File Links
Showing 28 of 28 Labs
Lab 01 Build Tools

☕ Building and Packaging Java Application with Maven

Objective: Compile Java source code, run automated tests, and produce a standalone runnable JAR file using Maven.

Java 17Apache MavenJUnit 5JAR Packaging
📋 Lab Prompt & Requirements (Slide Task)
  • Install java and maven.
  • Clone source code https://github.com/Ibrahim-Adel15/CalculatorMavenApp.git
  • Run unit test.
  • Build app [ generate artifact in target/calculator.jar ].
  • Run app.
  • Verify app is working.

The Core Idea & Concepts

If you've ever compiled a Java file by typing javac Main.java in your terminal, you know it works for one file. But what happens in a real company where your project has 50 files and needs 15 outside libraries (like database drivers, JSON parsers, or testing tools)?

Without a build tool, you would have to search the internet, download 15 .jar files by hand, put them into a folder, and type a 200-character terminal command just to compile. If one library needs another library, you get stuck in what developers call "dependency hell".

This is where Maven comes in:

  • One Shopping List (pom.xml): You write down the name and version of the libraries you need. Maven goes to the central internet warehouse (Maven Central) and downloads them for you automatically.
  • Fixed Standard Folders: In every Maven project in the world, source code is in src/main/java, tests are in src/test/java, and build outputs go into target/. You never have to guess where files are.
  • The Build Lifecycle (Step-by-Step): Maven runs in predictable phases: it compiles your code, runs your tests with JUnit, and packages everything into an executable .jar file. If a test fails, Maven stops immediately so you never accidentally ship broken code.

Architecture & Workflow Flowchart

Input pom.xml + Code src/main/java
➔
Phase 1 mvn compile Java 17 Bytecode
➔
Phase 2 mvn test 5/5 JUnit Tests Pass
➔
Output calculator.jar target/ (3.7 KB)

Step-by-Step Solution & Commands

1. Install Java and Maven

We need Java 17 (the language runtime) and Maven (the build tool):

# Update package index and install OpenJDK 17 + Maven build tool:
#   sudo           : Elevate to superuser permissions
#   apt update     : Refresh local package index lists from remote mirrors
#   apt install    : Download and install specified software packages
#   -y             : Automatic 'yes' to prompts (runs non-interactively without pausing)
sudo apt update && sudo apt install -y openjdk-17-jdk maven

# Verify installed runtimes and version information
java -version
mvn -version
2. Clone the Application Code
# Clone source repository from remote GitHub URL:
#   git clone <url> : Downloads full Git history and working tree
#   cd <directory>  : Change working directory into the project root
git clone https://github.com/Ibrahim-Adel15/CalculatorMavenApp.git
cd CalculatorMavenApp
3. Run the Unit Tests

Run the automated tests to make sure the calculator math functions work properly before packaging:

# Execute unit test phase:
#   mvn test : Compiles src/test/java and runs Surefire test runner on CalculatorTest
mvn test
[INFO] Scanning for projects... [INFO] Running com.calculator.CalculatorTest [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
4. Package the App into a JAR

Compile the code and generate the final executable .jar file inside the target/ folder:

# Compile, test, and package application into target/calculator.jar:
#   mvn package : Executes default lifecycle phases (validate -> compile -> test -> package)
mvn package
[INFO] --- maven-jar-plugin:3.3.0:jar (default-jar) @ calculator --- [INFO] Building jar: .../target/calculator.jar [INFO] BUILD SUCCESS
5. Run and Verify

Run the generated JAR directly using the Java runtime. We pipe numbers so it runs automatically:

# Pass test input numbers (10 and 3) into the calculator program via standard input:
#   echo "10 3"    : Emits test numbers to standard output
#   |              : Linux pipe redirects stdout of echo into stdin of java process
#   java -jar      : Executes executable JAR archive using Main-Class defined in pom.xml
echo "10 3" | java -jar target/calculator.jar
Enter first number: Enter second number: a = 10.0, b = 3.0 Sum: 13.0 Subtract: 7.0 Multiply: 30.0 Divide: 3.3333333333333335

Tips

  • Skipping Tests in CI: You might see people use mvn package -DskipTests to build faster. In production CI/CD pipelines, never skip tests—that's how broken code slips into production.
  • Clean Builds: If you ever change code and the JAR doesn't seem to update, run mvn clean package. The clean command wipes out the old target/ folder so everything rebuilds fresh.
Lab 02 Build Tools

🐘 Building and Packaging Application with Gradle

Objective: Build the calculator application using Gradle to understand modern incremental builds, Gradle tasks, and HTML test reports.

Gradle 8Java/JVMBuild CacheFast Incremental Builds
📋 Lab Prompt & Requirements (Slide Task)
  • Install Gradle.
  • Clone source code https://github.com/Ibrahim-Adel15/CalculatorGradleApp.git
  • Run unit test.
  • Build app [ generate artifact in build/libs/calculator.jar ].
  • Run app.
  • Verify app is working.

The Core Idea & Concepts

Maven is great, but its XML files can get very long and messy. Also, Maven rebuilds everything from scratch each time. If your project takes 20 minutes to compile, waiting that long every time you change one line of code slows you down.

Gradle was created to solve this:

  • No Rigid XML: Gradle uses readable code (Groovy or Kotlin) in a file called build.gradle instead of XML.
  • Smart "Incremental" Builds: Gradle checks what changed since the last build. If you didn't touch a file, Gradle marks it as UP-TO-DATE and skips it. This makes builds up to 10x faster than Maven.
  • The Background Daemon: Gradle keeps a small worker process running in the background on your computer so it doesn't have to start up the JVM from zero every time you run a command.
  • Slide note: The slide title mentions Go with Gradle, but the lab uses Gradle to compile the Java calculator. Gradle can build Go, C++, or Android apps, but here we focus on comparing how Gradle builds the same Java app compared to Maven.

Architecture & Workflow Flowchart

Config build.gradle Task Graph
➔
Task gradle test HTML Report in build/
➔
Task gradle build Incremental Compile
➔
Output calculator.jar build/libs/ (2.2 KB)

Step-by-Step Solution & Commands

1. Install Gradle
# Update package list and install Gradle:
#   -y : Automatically answers yes to installation prompts for non-interactive execution
sudo apt update && sudo apt install -y gradle

# Check Gradle and JVM runtime version
gradle --version
2. Clone the Repository
# Clone Gradle calculator codebase and navigate into project directory
git clone https://github.com/Ibrahim-Adel15/CalculatorGradleApp.git
cd CalculatorGradleApp
3. Run Unit Tests & View HTML Report
# Run test task:
#   gradle test : Compiles test code and executes JUnit test suite
gradle test
> Task :compileJava UP-TO-DATE > Task :test BUILD SUCCESSFUL in 850ms

Unlike Maven which only outputs text to the console, Gradle generates a ready-to-view HTML dashboard at build/reports/tests/test/index.html.

4. Build the App
# Execute full application build:
#   gradle build : Runs compileJava, processResources, classes, jar, and test tasks
#   Output artifact: build/libs/calculator.jar (approx. 2.2 KB)
gradle build
> Task :jar > Task :build BUILD SUCCESSFUL in 1s

Artifact created: build/libs/calculator.jar (approx. 2.2 KB).

5. Run and Verify
# Verify standalone execution by piping input numbers into Java runtime:
#   echo "10 3"    : Inputs for calculation
#   java -jar      : Executes the packaged standalone JAR from build/libs
echo "10 3" | java -jar build/libs/calculator.jar
Enter first number: Enter second number: a = 10.0, b = 3.0 Sum: 13.0 Subtract: 7.0 Multiply: 30.0 Divide: 3.3333333333333335
Maven vs Gradle Quick Summary
FeatureMavenGradle
Configurationpom.xml (XML)build.gradle (Code)
Build SpeedRebuilds all stepsIncremental (skips unchanged files)
Output Locationtarget/calculator.jarbuild/libs/calculator.jar

Tips

  • Always use ./gradlew: In real projects, you will see a gradlew file. That is the "Gradle Wrapper". It ensures everyone on the team and all automated servers use the exact same version of Gradle without manual installation.
  • Where did the JAR go? Remember: Maven outputs to target/, while Gradle outputs to build/libs/.
Lab 03 Docker

🐳 Creating a Docker Image for a Java Application

Objective: Learn the two ways to put a Java app into Docker: building inside the container vs building on your host machine.

DockerJava 17Image LayersNon-Root User
📋 Lab Prompt & Requirements (Slide Task)
  • Clone the application code: https://github.com/Ibrahim-Adel15/CalculatorMavenApp.git
  • Part 1: Build Inside Docker
  • • Write a Dockerfile using a Maven image with Java 17.
  • • Create a working directory and a non-root user.
  • • Copy the source code and build the application using mvn package.
  • • Run the generated JAR file and expose port 8080.
  • • Build an image named app1 and note its size.
  • • Run container1, verify the application, then delete the container and image.
  • Part 2: Build Locally
  • • Build the application locally using Maven.
  • • Write a Dockerfile using a Java 17 runtime image.
  • • Create a working directory and a non-root user.
  • • Copy the generated JAR file into the image and expose port 8080.
  • • Build an image named app2 and note its size.
  • • Run container2, verify the application, then delete the container and image.
  • Bonus: Compare the image sizes and explain the differences between the two approaches.

The Core Idea & Concepts

Imagine you want to give your Java calculator to a friend to run on their computer. You have two choices:

  • Choice A (Build Inside Docker): You give your friend the raw source code and tell Docker to download Maven, compile the code, and run it.
    The Good: Your friend does not need Java or Maven installed on their laptop—Docker does everything.
    The Bad: The final Docker image is huge (534 MB) because it has to carry the compiler, Maven tools, source files, and temporary caches that you never need when just running the app.
  • Choice B (Build Locally): You compile the code on your own laptop first using mvn package to make a tiny 3.7 KB calculator.jar file. Then you give Docker just that JAR file and a lightweight Java runtime (JRE).
    The Good: The image is almost half the size (296 MB), starts faster, and is much more secure.
    The Bad: Whoever builds the image must have Maven and Java installed on their machine first.
  • Why Non-Root User? By default, Docker runs everything as the root user (the super administrator). If a hacker finds a bug in your app, they might take over the entire host machine. Creating a simple unprivileged user named app stops this.

Architecture & Workflow Flowchart

Part 1: Build Inside Docker
Source Code ➔ Maven Image (JDK) ➔ mvn package
Size: 534 MB (Heavy)
Carries Maven tools, source code, and cached dependencies.
Part 2: Build Locally
Pre-built JAR (3.7 KB) ➔ JRE Runtime Image ➔ java -jar
Size: 296 MB (Slim)
Contains only Java runtime and the compiled JAR file.

Step-by-Step Solution & Commands

Part 1: Build Inside Docker (app1)

Click below to inspect the actual Dockerfile in your workspace:

# Base image: Official Maven 3.9 image packaged with Eclipse Temurin OpenJDK 17
FROM maven:3.9-eclipse-temurin-17

# Create an unprivileged system user and group for security:
#   groupadd -r app   : -r creates a system group (low GID, no password aging)
#   useradd -rm -g app: -r creates a system user (low UID)
#                       -m forces creation of home directory (/home/app)
#                       -g app sets primary group to 'app'
RUN groupadd -r app && useradd -rm -g app app

# Set execution workspace inside the container
WORKDIR /app
RUN chown app:app /app

# Copy application source code into the container image:
#   --chown=app:app : Directly sets file ownership on copy, preventing an extra RUN chown layer
COPY --chown=app:app . .

# Drop root privileges and switch runtime context to non-root user
USER app

# Compile and package the Java application:
#   -B : Batch / Non-Interactive mode (silences progress bars and disables interactive prompts)
RUN mvn package -B

# Document network port listening inside container (informational metadata)
EXPOSE 8080

# Configure default container executable using preferred JSON Exec format:
#   java -jar target/calculator.jar : Launches the built executable JAR
ENTRYPOINT ["java", "-jar", "target/calculator.jar"]

Run these commands in terminal:

# Build image app1 from Dockerfile in current directory:
#   -t app1  : Tag/name the target image as 'app1'
#   .        : Build context (sends current directory files to Docker daemon)
docker build -t app1 .

# Check image size (approx. 534 MB due to Maven compiler + JDK tools):
docker images app1

# Run container1 non-interactively and verify calculation:
#   -i             : Interactive mode (keeps STDIN open so piped test numbers reach the app)
#   --name container1 : Assigns a human-readable name instead of a random UUID
#   echo "10 3"    : Feeds two numbers into the calculator program
echo "10 3" | docker run -i --name container1 app1

# Clean up container and image:
#   docker rm   : Removes stopped container metadata and write layer
#   docker rmi  : Deletes image from local Docker host cache
docker rm container1 && docker rmi app1
Part 2: Build Locally, Package Lean JRE (app2)

Build the JAR on your host first (mvn package in Lab 1), then copy target/calculator.jar into part2/.

# Base image: Lightweight Java Runtime Environment (JRE 17) only — avoids heavy JDK/compiler tools
FROM eclipse-temurin:17-jre

# Create dedicated non-root application user for least-privilege security:
#   -r       : Creates system group/user (low UID/GID)
#   -m       : Creates home directory (/home/app)
#   -g app   : Assigns primary group 'app'
RUN groupadd -r app && useradd -rm -g app app
WORKDIR /app

# Copy ONLY the pre-compiled JAR artifact from the host build:
#   --chown=app:app : Sets ownership directly on copy to avoid extra intermediate filesystem layers
COPY --chown=app:app calculator.jar .

USER app
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "calculator.jar"]
# Build image app2 from local JAR Dockerfile:
#   -t app2  : Tag/name the target image as 'app2'
#   .        : Current directory build context
docker build -t app2 .

# Check image size (approx. 296 MB — 45% smaller than app1):
docker images app2

# Run container2 and verify with input numbers:
#   -i             : Keeps STDIN open for piped standard input
#   --name container2 : Container instance name
echo "10 3" | docker run -i --name container2 app2

# Clean up container and image:
docker rm container2 && docker rmi app2
Bonus: Why the Size Difference Matters
ImageBase ImageSizeWhy It Matters
app1maven:3.9-eclipse-temurin-17534 MBHolds the compiler, Maven, source code, and cached downloads. Slower to pull and push over the internet.
app2eclipse-temurin:17-jre296 MBHolds only the Java runtime and the 3.7 KB JAR. Faster to deploy and smaller attack surface.

Tips

  • The Multi-Stage Teaser: Is there a way to get the best of both worlds (build with zero host tools like Part 1, but get a small 200MB image like Part 2)? Yes! It is called a Multi-stage build, which we will do in Lab 4.
  • Always use --chown when copying: If you write COPY . . and then do RUN chown -R app:app /app, Docker creates an extra hidden layer holding another copy of all files, doubling the image size! Writing COPY --chown=app:app . . sets permissions in one single layer.
Lab 04 Docker

⚡ Docker Image Optimization and Export/Load

Objective: Cut container image size in half using multi-stage builds and Alpine Linux, and learn how to move images between servers without a registry.

Multi-Stage BuildAlpine Linuxdocker savedocker load
📋 Lab Prompt & Requirements (Slide Task)
  • Clone the application code from https://github.com/Ibrahim-Adel15/ImageOptimization-.git.
  • Build an image from the existing Dockerfile with name image1.
  • Note the image size and run a container named container1 from image1.
  • Verify that the application is working, then stop and delete the container.
  • Write a multi-stage Dockerfile and configure the application to run as a non-root user.
  • Build the optimized image as image2 and compare its size with image1.
  • Run a container named container2 from image2 and verify that the application is working and running as a non-root user.
  • Stop and delete container2.
  • Save image2 as a TAR file named lab-image.tar.
  • Delete image2 from the local Docker host.
  • Load the image from image2.tar and verify that it has been restored.
  • Verify the loaded image is existing in the local Docker host.

The Core Idea & Concepts

In Lab 3 we saw that building inside Docker made a big 534 MB image, while building locally made a 296 MB image. But what if your production server or CI pipeline doesn't have Maven installed?

Multi-Stage Builds solve this problem completely:

  • Two Rooms in One House: In your Dockerfile, you can have two FROM lines.
    • Stage 1 (The Kitchen): Takes the heavy Maven image, compiles your code, and creates the JAR.
    • Stage 2 (The Dining Table): Starts with a super clean, tiny Alpine Linux JRE image. You reach into Stage 1, grab only the compiled JAR file, and throw away Stage 1 completely!
  • What is Alpine Linux? Normal Linux distributions like Ubuntu or Debian weigh 100+ MB before you even add an app. Alpine Linux is a stripped-down Linux that weighs only 5 MB.
  • Saving Images as Files (docker save / load): How do you move a Docker image to a secure server that has no internet access? You can't use Docker Hub. Instead, docker save packs the image into a .tar zip archive. You copy the file with a USB stick or SCP, and run docker load on the other machine.

Architecture & Workflow Flowchart

Stage 1 (Builder) maven:alpine Compiles code & makes JAR
➔ Copy JAR Only ➔
Stage 2 (Runner) eclipse-temurin:jre Non-root user (app)
➔
Optimized image2 (210 MB) 50% Smaller!

Step-by-Step Solution & Commands

1. Baseline: Single-Stage Build (image1)
# Clone repository and enter project directory:
git clone https://github.com/Ibrahim-Adel15/ImageOptimization-.git
cd ImageOptimization-

# Build the unoptimized single-stage baseline image:
#   -t image1 : Tag/name the target image as 'image1'
#   .         : Build context (current directory)
docker build -t image1 .
# Size check: 420 MB (carries build tools and intermediate cache)

# Run container1 in detached mode to verify Spring Boot HTTP endpoint:
#   -d             : Detached mode (runs container in background, outputs container ID)
#   --name container1 : Human-readable name instead of randomly generated string
#   -p 8080:8080   : Port forwarding (maps host port 8080 -> container internal port 8080)
docker run -d --name container1 -p 8080:8080 image1

# Send HTTP GET request to verify application is responding:
curl http://localhost:8080/
# Output: Hello from Dockerized Spring Boot!

# Stop and delete container to release port 8080:
#   docker stop : Sends SIGTERM (graceful shutdown) followed by SIGKILL
#   docker rm   : Removes container metadata and writable filesystem layer
docker stop container1 && docker rm container1
2. The Multi-Stage Optimized Dockerfile (image2)
# STAGE 1: Builder environment — named 'build' so subsequent stages can reference artifacts
#   AS build : Assigns an alias to this initial build stage
FROM maven:3.9.15-eclipse-temurin-17-alpine AS build
WORKDIR /app
COPY . .
#   -B : Batch mode (non-interactive, suppresses transfer progress output)
RUN mvn package -B

# STAGE 2: Clean, minimal production runtime
FROM eclipse-temurin:17-jre-alpine

# In Alpine (musl libc / busybox), create system group and user:
#   -S     : Create a system group / system user (low UID/GID < 1000)
#   -G app : Assign primary group 'app' to the user
RUN addgroup -S app && adduser -S app -G app
WORKDIR /app

# Copy ONLY the compiled JAR from Stage 1 into Stage 2:
#   --from=build    : Reach into the 'build' stage container filesystem
#   --chown=app:app : Set ownership directly to non-root user during copy
COPY --from=build --chown=app:app /app/target/demo-0.0.1-SNAPSHOT.jar app.jar

USER app
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
# Build the optimized multi-stage image using the custom Dockerfile:
#   -t image2              : Target image name
#   -f Dockerfile.optimized: Use custom Dockerfile path instead of default ./Dockerfile
#   .                      : Build context
docker build -t image2 -f Dockerfile.optimized .
# Size check: 210 MB (Down from 420 MB - exactly 50% cut!)

# Run container2 and verify:
#   -d           : Detached background execution
#   --name container2 : Container instance name
#   -p 8080:8080 : Map host port 8080 to container port 8080
docker run -d --name container2 -p 8080:8080 image2
curl http://localhost:8080/

# Verify that the container runs as unprivileged user 'app', NOT root:
#   docker exec  : Runs a new process inside an already running container
#   whoami       : Prints effective username inside the container
docker exec container2 whoami
# Output: app

# Clean up container:
docker stop container2 && docker rm container2
3. Export and Restore Image as TAR Archive
# Save image2 into a portable tar archive:
#   -o lab-image.tar : Output file destination path (creates tar archive of all image layers)
docker save image2 -o lab-image.tar
ls -lh lab-image.tar    # Approx. 201 MB

# Delete image2 from Docker host cache to test restoration:
#   docker rmi : Removes image tag and untagged parent layers from host cache
docker rmi image2
docker images image2    # (empty, confirmed gone)

# Load image back from the tar archive:
#   -i lab-image.tar : Input archive file path to unpack and register into Docker engine
docker load -i lab-image.tar
# Output: Loaded image: image2:latest

# Verify image is back and intact:
docker images image2

Tips

  • Alpine User Command Difference: On Ubuntu/Debian you type useradd. On Alpine Linux you must type adduser -S -G app app. If you type useradd on Alpine, Docker throws command not found.
  • Image Tarballs for Air-Gapped Environments: Banks and secure environments often have servers with zero internet access. docker save and docker load are standard tools for delivering software there.
Lab 05 Docker

🛡️ Docker Image Vulnerability Scanning with Trivy

Objective: Scan Docker images for security holes using Trivy, generate an HTML report, and fix all Critical and High vulnerabilities.

TrivyDevSecOpsSecurity AuditCVE Remediation
📋 Lab Prompt & Requirements (Slide Task)
  • Clone the application and Dockerfile from https://github.com/Ibrahim-Adel15/TrivyImage.git
  • Build a Docker image from the provided Dockerfile and tag it as trivy-lab:v1.
  • Install Trivy and verify the installation.
  • Scan the Docker image for vulnerabilities and review the scan results.
  • Scan the image to identify only HIGH and CRITICAL vulnerabilities.
  • Generate an HTML vulnerability report and review the identified security issues.
  • Bonus: Vulnerability Remediation
  • • Investigate the detected HIGH and CRITICAL vulnerabilities.
  • • Fix the identified issues by updating the vulnerable base image and application dependencies, where applicable.
  • • Rebuild the Docker image and tag it as ivolve-app:v2.
  • • Rescan the updated image and generate a new HTML report to verify the remediation.
  • • Ensure that no HIGH or CRITICAL vulnerabilities remain, where fixes are available.

The Core Idea & Concepts

When you write FROM node:18 in your Dockerfile, you aren't just downloading Node.js. You are downloading an entire operating system (like Debian) with hundreds of pre-installed system packages: bash, curl, OpenSSL, git, and python.

If that base image is a few years old, security researchers have already discovered bugs in those packages. Attackers use these bugs (called CVEs — Common Vulnerabilities and Exposures) to hack into your servers.

How Trivy helps:

  • The Scanner: Trivy inspects every package inside your image and checks it against a giant security database. It rates bugs as LOW, MEDIUM, HIGH, or CRITICAL.
  • How to Fix 2,000+ Vulnerabilities:
    1. Upgrade your base image: Moving from an old Debian image to a modern node:22-alpine cuts out 95% of security bugs because Alpine has far fewer packages installed.
    2. Upgrade outdated packages: Upgrade packages like Express to the latest patch release.
    3. Delete tools you don't need: Production containers only need to run your code with node app.js. They do not need npm or npx inside them anymore! Deleting npm removes its hidden bundled bugs too.

Architecture & Workflow Flowchart

v1 (Outdated Base)
node:18-bullseye + express 4.18.2
2,269 High & Critical CVEs!
Heavy Debian packages full of known security bugs.
v2 (Remediated)
node:22-alpine + express 4.21.2 + strip npm
0 High / 0 Critical CVEs!
Clean, lean, passes corporate security audit.

Step-by-Step Solution & Commands

1. Build the Vulnerable Image (v1)
# Clone repository and enter project directory:
git clone https://github.com/Ibrahim-Adel15/TrivyImage.git
cd TrivyImage

# Build initial image containing outdated Debian bullseye and old Express:
#   -t trivy-lab:v1 : Name and version tag for baseline vulnerable image
#   .               : Build context
docker build -t trivy-lab:v1 .
# Size: approx. 1 GB
2. Scan Image with Trivy
# Install Trivy security scanner repository and binary (Debian/Ubuntu):
#   -y                     : Automatic yes to installation prompts
#   wget -qO -             : -q quiet mode, -O - writes downloaded key directly to stdout
#   gpg --dearmor -o       : Converts ASCII armored PGP key to binary keyring format
#   tee                    : Reads from stdin and writes to apt source list file
sudo apt install -y wget apt-transport-https gnupg lsb-release
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | sudo gpg --dearmor -o /etc/apt/keyrings/trivy.gpg
echo "deb [signed-by=/etc/apt/keyrings/trivy.gpg] https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/trivy.list
sudo apt update && sudo apt install -y trivy

# Scan specifically for High and Critical severity vulnerabilities:
#   --severity HIGH,CRITICAL : Filters out low/medium noise to focus on urgent security exploits
trivy image --severity HIGH,CRITICAL trivy-lab:v1
trivy-lab:v1 (debian 11.7) ========================== Total: 2269 (HIGH: 2048, CRITICAL: 221)

Generate HTML report for the security audit:

# Render HTML vulnerability report for stakeholder audit:
#   --format template            : Specifies custom templated output
#   --template "@contrib/html.tpl": Uses Trivy's built-in HTML template renderer
#   -o report-v1.html            : Output file path for generated report
trivy image --format template --template "@contrib/html.tpl" -o report-v1.html trivy-lab:v1
3. The Fix: Remediation in TrivyImage-v2/

We make three key fixes:

  1. Switch to node:22-alpine.
  2. Bump Express to ^4.21.2 in package.json.
  3. Delete the npm binary after installation to remove internal bundled package issues.
# Base image: Minimal Alpine Linux with modern Node.js 22 runtime
FROM node:22-alpine
WORKDIR /app
COPY package.json ./

# Install production dependencies only, clean cache, and strip the npm CLI tool:
#   --omit=dev           : Ignores development dependencies (devDependencies)
#   cache clean --force  : Deletes downloaded package tarballs from npm cache
#   rm -rf ...           : Deletes npm and npx binaries (not needed in production containers)
RUN npm install --omit=dev     && npm cache clean --force     && rm -rf /usr/local/lib/node_modules /usr/local/bin/npm /usr/local/bin/npx

COPY app.js ./
EXPOSE 3000
CMD ["node", "app.js"]
# Build remediated image:
#   -t ivolve-app:v2 : Tags the clean image version 2
docker build -t ivolve-app:v2 .
# Size: 172 MB (down from 1 GB!)

# Enforce security gate in CI/CD pipelines:
#   --severity HIGH,CRITICAL : Focus on breaking security risks
#   --exit-code 1            : Forces Trivy to return non-zero exit code if matching CVEs are found
trivy image --severity HIGH,CRITICAL --exit-code 1 ivolve-app:v2
ivolve-app:v2 (alpine 3.20.0) ============================= Total: 0 (HIGH: 0, CRITICAL: 0) Clean exit code: 0! All Critical and High vulnerabilities eliminated.

Generate the clean verification report:

# Generate clean audit report demonstrating 0 High / 0 Critical CVEs:
#   -o report-v2.html : Destination HTML audit file
trivy image --format template --template "@contrib/html.tpl" -o report-v2.html ivolve-app:v2

Tips

  • Why did npm have vulnerabilities? Even in new Node images, the npm CLI tool itself contains older bundled dependencies. Since a running web container never uses npm at runtime, deleting npm after npm install is a trick that cleans up dozens of warnings.
  • Automating in CI: Add --exit-code 1 in your Jenkins pipeline. If a developer accidentally adds an insecure package, the pipeline will stop before pushing the image.
Lab 06 Docker

⚙️ Docker Environment Variables and Resource Management

Objective: Configure application settings through environment variables and prevent containers from crashing your server using CPU and RAM limits.

Resource LimitscgroupsEnvironment Variablesdocker stats
📋 Lab Prompt & Requirements (Slide Task)
  • Clone the application code from https://github.com/Ibrahim-Adel15/PythonApp.git.
  • Create a Dockerfile using the python:3.12-slim base image, install the application dependencies, and configure the application to run on port 5000.
  • Build ivolve1 Docker image.
  • Run a container with name container1, map port 5000, and configure the environment variables APP_NAME=iVolveApp1 and APP_ENV=stg.
  • Limit the container resources to 1 CPU and 256 MB of memory.
  • Verify that the application is working by accessing http://localhost:5000.
  • Verify the environment variables configured inside the container.
  • Monitor the container's CPU and memory usage using docker stats cont1.
  • Create env.txt file with APP_NAME=iVolveApp2 and APP_ENV=prod.
  • Run a container with name container2, map port 5000, and load the environment variables from env.txt.
  • Create a new Docker Image with the following environment variables hardcoded in the Dockerfile: APP_NAME=iVolveApp3 and APP_ENV=dev.
  • Run a container with name container2, map port 5000, and validate the environment variables from Dockerfile.

The Core Idea & Concepts

Two essential habits every DevOps engineer must learn:

  • 1. Never Hardcode Settings in Code: Your app needs to run in dev (development on your laptop), stg (staging for testing), and prod (production for real users). If you hardcode the database password or environment name inside the Python file, you have to rewrite the code every time you deploy. Instead, your code reads from Environment Variables at startup.
  • 2. Protect Your Server from Greedy Containers: By default, a Docker container can take 100% of your computer's CPU and 100% of your RAM. If someone writes a loop with a memory leak, the container will eat all memory and crash your whole operating system!
    • With --cpus 1 and --memory 256m, the Linux kernel puts a fence around the container. It can never use more than its fair share.

Architecture & Workflow Flowchart

Input Options -e CLI Flag or --env-file env.txt
➔
Resource Fence cgroups Limits 1 CPU + 256 MB RAM
➔
App Reads Python Flask Port 5000
➔
Observation docker stats Live 24 MB / 256 MB

Step-by-Step Solution & Commands

1. Create the Dockerfile
# Base image: Slim Debian Python 3.12 image to reduce footprint
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .

# Install dependencies:
#   --no-cache-dir : Avoids caching wheel/tar downloads, saving ~30 MB in image layer
RUN pip install --no-cache-dir -r requirements.txt

COPY app.py .
EXPOSE 5000
CMD ["python", "app.py"]
# Clone application source code and build Docker image:
#   -t ivolve1 : Assign tag/name 'ivolve1'
#   .          : Build context directory
git clone https://github.com/Ibrahim-Adel15/PythonApp.git
cd PythonApp
docker build -t ivolve1 .
2. Run with -e Flags and Resource Limits

We publish on port 5001 (in case 5000 is occupied on the host) and set CPU & RAM constraints:

# Run container1 with runtime environment variables and cgroup limits:
#   -d                 : Run container in background (detached mode)
#   --name container1  : Human-readable container identifier
#   -p 5001:5000       : Port mapping (host port 5001 -> container port 5000)
#   -e APP_NAME=...    : Injects runtime environment variable into process space
#   -e APP_ENV=stg     : Sets environment to 'stg' (staging)
#   --cpus 1           : Limits container to at most 1 CPU core usage
#   --memory 256m      : Sets hard RAM ceiling to 256 Megabytes (triggers OOM kill if exceeded)
docker run -d --name container1 -p 5001:5000   -e APP_NAME=iVolveApp1 -e APP_ENV=stg   --cpus 1 --memory 256m ivolve1

Verify responses, environment variables, and memory caps:

# Test application HTTP endpoint:
curl http://localhost:5001/
# Returns: {"application":"iVolveApp1","environment":"stg",...}

# Verify environment variables loaded inside running container:
#   docker exec        : Runs command inside running container
#   env | grep APP     : Filters environment variables matching 'APP'
docker exec container1 env | grep APP
# Output:
# APP_NAME=iVolveApp1
# APP_ENV=stg

# Inspect real-time CPU and RAM utilization:
#   --no-stream        : Takes a single snapshot rather than streaming live updates
docker stats --no-stream container1
# Output: container1 | CPU: 0.01% | MEM: 24MiB / 256MiB
3. Run with --env-file

Create an env.txt file:

APP_NAME=iVolveApp2
APP_ENV=prod
# Run container2 reading configuration key-value pairs from an external file:
#   --env-file env.txt : Parses lines in env.txt and exposes them as environment variables
#   -p 5002:5000       : Map to host port 5002
docker run -d --name container2 -p 5002:5000 --env-file env.txt ivolve1

# Verify output reflects production environment:
curl http://localhost:5002/
# Output: {"application":"iVolveApp2","environment":"prod",...}
4. Hardcode Defaults in Dockerfile (ENV)
# Build upon base ivolve1 image
FROM ivolve1

# Hardcode fallback environment variables in the image metadata:
#   ENV : Sets persistent environment variables visible during build and runtime
ENV APP_NAME=iVolveApp3
ENV APP_ENV=dev

CMD ["python", "app.py"]
# Build image ivolve3 using custom Dockerfile:
#   -f Dockerfile.env : Path to custom Dockerfile with hardcoded ENV
docker build -t ivolve3 -f Dockerfile.env .

# Run container3 without passing any -e flags:
docker run -d --name container3 -p 5003:5000 ivolve3

# Verify response picks up hardcoded defaults:
curl http://localhost:5003/
# Output: {"application":"iVolveApp3","environment":"dev",...}

Tips

  • What happens when memory is exceeded? If your container exceeds its 256 MB limit, Linux's Out-Of-Memory (OOM) killer terminates the container immediately with Exit Code 137. If your container dies randomly, check docker inspect for OOMKilled: true.
  • Security Warning: Never bake passwords or secret API keys into a Dockerfile using ENV. Anyone who pulls the image can read them with docker history. Use -e or orchestrator secrets instead.
Lab 07 Docker

🕸️ Multi-Network Microservices, Volumes, and Bind Mounts

Objective: Connect three microservices using two isolated Docker networks, named volumes for logs, and a host bind mount for persistent messages.

Docker NetworksBridge DriverNamed VolumesBind Mounts
📋 Lab Prompt & Requirements (Slide Task)
  • Clone the application code from https://github.com/Ibrahim-Adel15/MicroserviceApp.git.
  • Create Dockerfiles for the frontend, backend, and notification services, then build their images.
  • Create two bridge networks with separate subnets: frontend-backend and backend-notification.
  • Create two docker volumes for backend and notification logs.
  • Create host directory to persist backend application data and configure a bind mount to map it to the appropriate path inside the backend container.
  • Run the notification container on backend-notification.
  • Run the backend container on both networks, configure the notification service URL.
  • Run the frontend container on frontend-backend, publish port 8080, and configure the backend URL.
  • Access the web page and verify that messages can be created and retrieved.

The Core Idea & Concepts

If you put all your containers on one single network, any compromised container can talk to every other container. A user visiting your public website could potentially connect directly to your internal database or notification system.

The Solution: Network Segmentation & Dual-Homing

  • Two Separate Networks:
    • Network 1 (frontend-backend): Connects frontend to backend.
    • Network 2 (backend-notification): Connects backend to notification.
    • The backend joins both networks so it acts as a bridge. The frontend has no network route to notification at all!
  • Volume vs Bind Mount:
    • Named Volume: Managed by Docker in a safe internal location. Ideal for logs that you want Docker to manage.
    • Host Bind Mount: Links an exact folder on your laptop (e.g. ./backend-data) into the container. When the container writes messages.json, you can see and edit the file directly on your desktop.

Architecture & Workflow Flowchart

Public Frontend Port 8080
➔ [Net: 172.30.0.0/24] ➔
Bridge Backend On Both Networks
➔ [Net: 172.31.0.0/24] ➔
Internal Notification Hidden from Frontend

Step-by-Step Solution & Commands

1. Build the Three Images
# Clone microservice repository and build all three container images:
#   -t <name> <dir> : Names image and sets context to service subfolder
git clone https://github.com/Ibrahim-Adel15/MicroserviceApp.git
cd MicroserviceApp

docker build -t frontend frontend
docker build -t backend backend
docker build -t notification notification
2. Create Isolated Bridge Networks with Subnets
# Create private user-defined bridge networks with explicit CIDR IP blocks:
#   --driver bridge : Uses Docker's software bridge driver (enables automatic container name DNS)
#   --subnet        : Allocates a dedicated IP address range for container IP assignments
docker network create --driver bridge --subnet 172.30.0.0/24 frontend-backend
docker network create --driver bridge --subnet 172.31.0.0/24 backend-notification
3. Create Volumes and Host Bind Mount Directory
# Create named volumes managed by Docker engine for service logs:
#   docker volume create : Creates persistent storage area in /var/lib/docker/volumes/
docker volume create backend-logs
docker volume create notification-logs

# Create host directory for bind mount to inspect persistent message JSON on the host:
#   mkdir -p : Creates directory including parent directories without error if already exists
mkdir -p backend-data
4. Run Containers and Connect Networks
# 1. Notification (isolated on backend-notification network):
#   --network backend-notification : Attaches container to internal notification subnet
#   -v notification-logs:/app/logs : Mounts named volume to store notification logs
docker run -d --name notification --network backend-notification   -v notification-logs:/app/logs notification

# 2. Backend (starts on backend-notification, mounts logs volume and data bind mount):
#   -v backend-logs:/app/logs        : Mounts named volume for backend logs
#   -v $(pwd)/backend-data:/app/data : Host bind mount linking local directory into container
#   -e NOTIFICATION_URL=...          : Injects URL of notification service via Docker DNS
docker run -d --name backend --network backend-notification   -v backend-logs:/app/logs   -v $(pwd)/backend-data:/app/data   -e NOTIFICATION_URL=http://notification:5001/notify backend

# 3. Dual-homing: Connect backend container to the frontend network too!
#   docker network connect : Attaches a secondary network interface to an already running container
docker network connect frontend-backend backend

# 4. Frontend (only on frontend-backend network, exposed on 8080):
#   -p 8080:3000 : Exposes frontend to external users on host port 8080
#   -e BACKEND_URL=http://backend:5000 : Directs frontend API calls to backend container DNS
docker run -d --name frontend --network frontend-backend   -p 8080:3000 -e BACKEND_URL=http://backend:5000 frontend
5. Verify End-to-End Functionality
# Access frontend web page via HTTP GET:
curl http://localhost:8080/

# Submit a message through frontend via HTTP POST:
#   -X POST                : Specifies HTTP request method
#   -d "message=..."       : Sends URL-encoded form data payload in request body
curl -X POST -d "message=Hello from Lab 7" http://localhost:8080/send

# Check host bind mount — verify file written by container exists on host filesystem:
cat backend-data/messages.json
# Output: ["Hello from Lab 7"]

# Check logs in volumes to verify network IP segregation:
#   tail -1 : Displays the last line of the service log
docker exec backend tail -1 /app/logs/backend.log
# Shows requests coming from 172.30.0.x (frontend subnet)

docker exec notification tail -1 /app/logs/notification.log
# Shows requests coming from 172.31.0.x (backend subnet)

Tips

  • Automatic DNS: In custom Docker networks, containers can ping each other using their container names (e.g. backend:5000). Docker's embedded DNS server handles this automatically!
  • Clean Up: When finished, remove containers, networks, and volumes in one clean command:
    docker rm -f frontend backend notification && docker network rm frontend-backend backend-notification && docker volume rm backend-logs notification-logs
Lab 08 Docker

🐙 Containerized Node.js and MySQL Stack Using Docker Compose

Objective: Run a multi-container web application and MySQL database with one single command using Docker Compose, and publish the image to Docker Hub.

Docker ComposeMySQL 8.0Node.jsDocker Hub Push
📋 Lab Prompt & Requirements (Slide Task)
  • Clone the application requirement from https://github.com/Ibrahim-Adel15/iVolveApp.git.
  • The application requires a MySQL connection and a database named ivolve to start successfully.
  • Create docker-compose.yml with:
  • o App: Build from Dockerfile, map port 3000, configure database environment variables, and persist logs.
  • o Database: Use MySQL, configure required environment variables, and persist data using db_data.
  • o Network: Create a custom network named ivolve-net for service communication.
  • o Volumes: Persist application logs at /app/logs/ and database data at /var/lib/mysql.
  • Start the services and verify application functionality and connectivity to the DB.
  • Build and tag the application image with your Docker Hub username, then push it to your repository.

The Core Idea & Concepts

Typing four separate docker run commands with long network and volume flags every time you start your app is tedious and easy to mess up. In real teams, we use Docker Compose.

  • One Blueprint File (docker-compose.yml): You describe your entire architecture in one YAML file: what services to run (Node.js app + MySQL database), what ports to open, what database password to use, and where to store data.
  • One Command to Start: You run docker compose up -d. Docker downloads the database, builds your app, creates the private network, attaches the storage volumes, and starts everything in the correct order.
  • Publishing to Docker Hub: Once your app works, you tag the image with your Docker Hub username (docker tag ...) and push it to the cloud (docker push ...). This allows your Kubernetes cluster in the next labs to pull and run your image!

Architecture & Workflow Flowchart

Stack File docker-compose.yml App + MySQL
➔ docker compose up ➔
Network: ivolve-net App (3000) ⇄ DB (3306) Volumes: logs + db_data
➔ docker push ➔
Registry Docker Hub abdalrahmanx/ivolve-app:v1

Step-by-Step Solution & Commands

1. Inspect the Complete docker-compose.yml
services:
  app:
    build: .                # Builds Dockerfile from current directory
    ports:
      - "3000:3000"         # Host port 3000 -> Container port 3000
    environment:
      DB_HOST: db           # Resolves to MySQL container via Docker internal DNS
      DB_USER: ivolve
      DB_PASSWORD: ivolve123
      DB_NAME: ivolve
    volumes:
      - app_logs:/app/logs  # Named volume storing Node.js application logs
    depends_on:
      - db                  # Ensures db container starts before app
    networks:
      - ivolve-net          # Shared bridge network for service-to-service communication

  db:
    image: mysql:8.0        # Official MySQL 8.0 server image
    environment:
      MYSQL_ROOT_PASSWORD: root123
      MYSQL_DATABASE: ivolve # Automatically initializes schema on first boot
      MYSQL_USER: ivolve
      MYSQL_PASSWORD: ivolve123
    volumes:
      - db_data:/var/lib/mysql # Persistent storage for MySQL table files
    networks:
      - ivolve-net

networks:
  ivolve-net:
    name: ivolve-net

volumes:
  app_logs:
  db_data:
2. Launch Stack and Verify
# Launch multi-container stack in background:
#   -d      : Detached mode (runs containers in background)
#   --build : Rebuilds container images before starting, even if local image exists
docker compose up -d --build

# Verify web application health endpoint:
curl http://localhost:3000/health
# Output: iVolve web app is working! Keep calm and code on! [HTTP 200]

# Query MySQL inside database container to confirm initialization:
#   exec db : Executes command inside running 'db' service container
#   -uivolve: Authenticates as MySQL user 'ivolve'
#   -p...   : MySQL user password
#   -e      : Execute SQL query string non-interactively
docker compose exec db sh -c "mysql -uivolve -pivolve123 -e 'SHOW DATABASES;'"
# Lists database: ivolve
3. Tag and Push Image to Docker Hub
# Authenticate Docker CLI client with your Docker Hub account:
#   -u : Docker Hub username
docker login -u abdalrahmanx

# Tag the built local image with your repository namespace and version:
#   docker tag <source_image> <target_image> : Creates an alias pointing to the same image ID
docker tag ivolveapp-app abdalrahmanx/ivolve-app:v1

# Upload all layers to Docker Hub public registry:
#   docker push : Sends image manifests and blobs to remote registry
docker push abdalrahmanx/ivolve-app:v1
v1: digest: sha256:23d090e3d72bfb467300dc59845170626c47cae6a0cceed645150b18f714a680 Successfully pushed to docker.io/abdalrahmanx/ivolve-app:v1

Tips

  • Database Cold Start: Sometimes MySQL takes 5–10 seconds to create its tables on its first boot. If your app crashes immediately on startup, add a health check on the db service so Compose waits until MySQL is truly ready.
  • Shutting Down: Run docker compose down to stop containers without losing database data. If you want to wipe the database and start fresh, run docker compose down -v (the -v flag deletes volumes).
Lab 09 Kubernetes

☸️ Deploy Kubernetes Cluster using Kubeadm

Objective: Build a real multi-node Kubernetes cluster from scratch using containerd and Calico networking instead of a pre-packaged simulator.

kubeadmcontainerdCalico CNICluster Architecture
📋 Lab Prompt & Requirements (Slide Task)
  • Install and configure containerd as the container runtime on all nodes.
  • Install kubeadm, kubelet, and kubectl on the control plane and worker nodes.
  • Configure kubectl to communicate with the Kubernetes cluster.
  • Install the Calico CNI plugin to enable pod networking across the cluster.
  • Initialize the control plane node using kubeadm init.
  • Join the worker nodes to the cluster using the kubeadm join command.
  • Verify that all nodes are in the Ready state and that the cluster components are running correctly.

The Core Idea & Concepts

Docker alone only runs containers on a single computer. But what happens if that computer's power goes out or crashes? Your entire company website goes down.

Kubernetes groups multiple computers together into a single cluster so they act like one giant supercomputer:

  • The Boss (Control Plane / Master Node): Doesn't run your apps. Instead, it decides which computer has enough free memory, keeps track of cluster health, and automatically replaces dead containers.
    • kube-apiserver: The front desk receptionist. Every command you run with kubectl talks to this server.
    • etcd: The database storing cluster state.
  • The Workers (Worker Nodes): The computers where your application containers (Pods) actually run.
    • kubelet: The foreman on each worker node that receives orders from the Boss and starts containers using containerd.
  • Why do we need Calico CNI? By default, Kubernetes nodes cannot route traffic between pods on different servers. Calico acts like an internal private highway (overlay network) giving every pod its own IP address across the entire cluster.

Architecture & Workflow Flowchart

Master Node Control Plane kubeadm init
➔ Join Token ➔
Worker Node kubelet + containerd kubeadm join
➔ CNI Overlay ➔
Networking Project Calico 192.168.0.0/16
➔
Cluster Status Nodes Ready 0% Packet Loss Ping

Step-by-Step Solution & Commands (Official Kubernetes & Calico Documentation)

📖 Official Documentation Standards Followed:

1. System Prerequisites (Run on Both Nodes - kubernetes.io)

According to official Kubernetes documentation, swap memory must be disabled and Linux kernel networking modules must be loaded with packet filtering enabled:

# Disable swap memory (Kubernetes scheduler requires predictable memory allocations):
#   -a : Turns off all swap devices and files
sudo swapoff -a

# Persist swap disablement across system reboots in filesystem table:
#   -i : Edits /etc/fstab in-place
sudo sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab

# Load required Linux networking kernel modules (overlay & br_netfilter):
cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
overlay
br_netfilter
EOF

sudo modprobe overlay
sudo modprobe br_netfilter

# Enable Linux kernel packet forwarding and bridged IPv4 traffic to iptables:
cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables  = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward                 = 1
EOF

# Apply sysctl parameters immediately without rebooting:
#   --system : Loads settings from all system configuration directories
sudo sysctl --system
2. Install and Configure containerd Runtime (Both Nodes - kubernetes.io)

Install containerd and configure the systemd cgroup driver as mandated by the Kubernetes production container runtime documentation:

# Install containerd container runtime package:
#   -y : Automatically confirm installation
sudo apt-get update && sudo apt-get install -y containerd

# Generate official default containerd configuration:
sudo mkdir -p /etc/containerd
containerd config default | sudo tee /etc/containerd/config.toml

# Configure systemd cgroup driver (mandatory for kubelet stability according to kubernetes.io):
sudo sed -i 's/SystemdCgroup = false/SystemdCgroup = true/g' /etc/containerd/config.toml

# Restart and enable containerd service:
sudo systemctl restart containerd
sudo systemctl enable containerd
3. Install kubelet, kubeadm, and kubectl (Both Nodes - pkgs.k8s.io)

Install Kubernetes tools from the official community repository (pkgs.k8s.io):

# Install apt HTTPS transport packages and download Kubernetes official signing key:
sudo apt-get update && sudo apt-get install -y apt-transport-https ca-certificates curl gpg

# Create keyrings directory if not present:
sudo mkdir -p -m 755 /etc/apt/keyrings
curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.33/deb/Release.key | sudo gpg --dearmor --yes -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg

# Add official Kubernetes apt repository:
echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.33/deb/ /" | sudo tee /etc/apt/sources.list.d/kubernetes.list

# Install Kubernetes cluster tools and lock package versions to prevent accidental drift:
#   apt-mark hold : Locks installed version against automatic apt upgrade
sudo apt-get update && sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl

# Enable kubelet daemon service:
sudo systemctl enable --now kubelet
4. Initialize the Master Node (Control Plane - kubernetes.io)

Initialize the control plane with the standard pod network CIDR recommended by Calico (192.168.0.0/16):

# Bootstrap control plane with Pod CIDR matching Calico:
#   --pod-network-cidr=192.168.0.0/16 : Standard Calico default subnet block for Pod IP pool
sudo kubeadm init --pod-network-cidr=192.168.0.0/16

# Configure kubeconfig authentication credentials for your regular non-root user:
#   mkdir -p           : Creates ~/.kube directory if not existing
#   cp -i              : Prompts before overwriting existing config
#   $(id -u):$(id -g)  : Sets ownership to current user UID and GID
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
5. Install Calico CNI Networking (docs.tigera.io)

According to official Project Calico documentation, deploy Calico using the Tigera Operator:

# Step 5a: Install the Tigera Calico operator and CRDs:
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.29.2/manifests/tigera-operator.yaml

# Step 5b: Install Calico custom resources (configures Calico to manage the 192.168.0.0/16 pool):
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.29.2/manifests/custom-resources.yaml

# (Alternative from Calico Docs): If you prefer single-manifest deployment without operator:
# kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.29.2/manifests/calico.yaml

# Monitor Calico pods until all report Running status:
#   -n calico-system : Namespace where Tigera Operator provisions Calico pods
#   -w / --watch     : Streams pod status transitions live
kubectl get pods -n calico-system -w
6. Join Worker Node to the Cluster

Run the join command printed by kubeadm init on your worker node:

# Attach worker node to control plane:
#   <MASTER_IP>:6443              : Control plane API server endpoint
#   --token <TOKEN>               : Cluster bootstrap authorization token
#   --discovery-token-ca-cert-hash: SHA256 hash validating control plane Root CA
sudo kubeadm join <MASTER_IP>:6443 --token <TOKEN>   --discovery-token-ca-cert-hash sha256:<HASH>
7. Verify Cluster Status
# Check node readiness and extended details across cluster:
#   -o wide : Displays node internal IP, OS image, kernel version, and container runtime
kubectl get nodes -o wide
# Output shows all nodes in Ready state!

# List pods across all namespaces:
#   -A / --all-namespaces : Queries pods across every namespace in the cluster
kubectl get pods -A
# All Calico, CoreDNS, etcd, and kube-apiserver pods show Running!

Tips

  • Why Must Swap Be Off? The Kubernetes scheduler assumes 100% predictable memory performance. If Linux starts swapping memory to a slow hard drive, pods become unresponsive and the scheduler miscalculates available capacity. That is why swapoff is mandatory.
  • Forgot the Join Token? If your join token expires after 24 hours, generate a fresh join command on the master node anytime with:
    kubeadm token create --print-join-command
Lab 10 Kubernetes

🏷️ Node Isolation Using Taints and Labels in Kubernetes

Objective: Reserve specific worker nodes for dedicated projects by repelling unwanted pods with Taints and attracting target pods with Labels.

Taints & TolerationsNode LabelsNodeSelectorTargeted Scheduling
📋 Lab Prompt & Requirements (Slide Task)
  • Apply a taint to a worker node with key workload, value ivolveApp, and effect NoSchedule to prevent pods from being scheduled on the node unless they have a matching toleration.
  • Label the same worker node with project=ivolve to identify it for targeted pod scheduling.
  • Verify that the taint and label have been applied correctly using kubectl describe node and kubectl get nodes --show-labels.

The Core Idea & Concepts

Imagine your company has 10 general servers and 1 expensive server with high-speed SSDs dedicated to Project iVolve. If developers start launching test apps, Kubernetes might blindly put random test pods on your expensive server, wasting its capacity.

We use a two-part lock-and-key system to solve this:

  • Part 1: The Taint (The Repellent / Keep Out Sign): You put a taint (workload=ivolveApp:NoSchedule) on the node. Now, the Kubernetes scheduler will refuse to put any pod on that node. Pods are repelled.
  • Part 2: The Toleration (The VIP Pass): You give your project pods a special VIP pass called a Toleration. Now they are permitted to land on the tainted node.
  • Part 3: The Label & NodeSelector (The Target Magnet): A toleration only means "I am allowed here"—it does not force the pod to go there. Adding project=ivolve on the node and nodeSelector: project: ivolve on the pod actively guides the pod to that specific machine.

Architecture & Workflow Flowchart

blocked-pod
No Toleration ➔ Hits Tainted Node ➔ REPELLED!
Sent to other workers
Cannot land on desktop-worker because it lacks the VIP pass.
allowed-pod
Toleration + Label ➔ Hits Node ➔ ACCEPTED!
Lands on desktop-worker
Matches taint toleration and project=ivolve label selector.

Step-by-Step Solution & Commands

1. Apply Taint and Label to the Worker Node
# Apply taint to repel general pods from the worker node:
#   node desktop-worker          : Target node to apply the taint to
#   workload=ivolveApp:NoSchedule: Key=workload, Value=ivolveApp, Effect=NoSchedule
#                                  (NoSchedule prevents pods without matching toleration from scheduling)
kubectl taint node desktop-worker workload=ivolveApp:NoSchedule

# Apply label so project pods can specifically target it using nodeSelector:
#   project=ivolve : Key=value label attached to node metadata
kubectl label node desktop-worker project=ivolve
2. Verify Node Configuration
# Check taint status on target node:
#   describe node <name> : Prints detailed node specification, capacity, and conditions
#   grep -A1 Taints      : -A1 prints matching line plus 1 line of trailing context
kubectl describe node desktop-worker | grep -A1 Taints
# Output: Taints: workload=ivolveApp:NoSchedule

# Check node labels:
#   --show-labels        : Appends LABELS column to node listing output
kubectl get nodes --show-labels | grep project=ivolve
# Shows desktop-worker with label project=ivolve
3. Deploy the Authorized Pod (allowed-pod.yaml)
apiVersion: v1
kind: Pod
metadata:
  name: allowed-pod
spec:
  nodeSelector:
    project: ivolve                    # Attracts pod to this node
  tolerations:
    - key: "workload"                  # The VIP pass allowing it past the taint
      operator: "Equal"
      value: "ivolveApp"
      effect: "NoSchedule"
  containers:
    - name: nginx
      image: nginx:alpine
4. Deploy the Blocked Pod (blocked-pod.yaml)
apiVersion: v1
kind: Pod
metadata:
  name: blocked-pod
spec:
  containers:
    - name: nginx
      image: nginx:alpine
5. Proof of Isolation
# Apply both pod manifests simultaneously:
#   -f allowed-pod.yaml -f blocked-pod.yaml : Pass multiple manifest files in a single execution
kubectl apply -f allowed-pod.yaml -f blocked-pod.yaml

# Check pod scheduling distribution:
#   -o custom-columns : Custom table output selecting specific JSONPath fields
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName
NAME STATUS NODE allowed-pod Running desktop-worker <- Allowed onto isolated node! blocked-pod Running desktop-worker2 <- Repelled by taint, scheduled elsewhere!
kubectl delete pod allowed-pod blocked-pod

Tips

  • Removing a Taint: If you ever make a mistake and want to delete a taint from a node, put a minus sign (-) at the end of the command:
    kubectl taint node desktop-worker workload=ivolveApp:NoSchedule-
  • NoSchedule vs NoExecute: NoSchedule only prevents new pods from landing. If pods are already running on the node when you add the taint, they stay there. If you use NoExecute, Kubernetes kicks off existing pods immediately!
Lab 11 Kubernetes

📦 Namespace Management and Resource Quota Enforcement

Objective: Create isolated team environments using Namespaces and enforce strict boundaries with ResourceQuotas to prevent cluster overload.

NamespacesResourceQuotaMulti-TenancyRFC 1123
📋 Lab Prompt & Requirements (Slide Task)
  • Create a Kubernetes namespace named ivolve to isolate application resources.
  • Create a ResourceQuota named ivolveQuota in the ivolve namespace to limit the total number of pods to 3.
  • Verify that the ResourceQuota is applied correctly and confirm that Kubernetes prevents the creation of additional pods when the limit is reached.

The Core Idea & Concepts

Imagine your company has two developer teams sharing one Kubernetes cluster: Team Alpha and Team Beta.

  • What is a Namespace? Think of a Namespace like an apartment inside an apartment building. Team Alpha gets apartment alpha, and Team Beta gets apartment beta. They can both name a pod web-server and they will never collide because they live in separate rooms.
  • What is a ResourceQuota? What if someone on Team Alpha accidentally runs an infinite loop that creates 10,000 pods and crashes the entire server, taking down Team Beta too?
    • A ResourceQuota sets a strict ceiling on the apartment. In this lab, we set a hard cap of 3 pods maximum. If Team Alpha tries to create a 4th pod, Kubernetes rejects it with an immediate error.

Architecture & Workflow Flowchart

Setup Namespace: ivolve Logical Isolation
➔ Apply ➔
ResourceQuota Limit: pods = "3" ivolve-quota
➔ 4th Pod Attempt ➔
Rejected 403 Forbidden exceeded quota!

Step-by-Step Solution & Commands

1. Create the Isolated Namespace
kubectl create namespace ivolve
2. Create the ResourceQuota Manifest
apiVersion: v1
kind: ResourceQuota
metadata:
  name: ivolve-quota                   # Must be lowercase (RFC 1123 standard)
  namespace: ivolve
spec:
  hard:
    pods: "3"                          # Hard limit: maximum 3 pods in this namespace
kubectl apply -f resourcequota.yaml
3. Test the Limit

Create 3 pods to fill up the quota:

# Create 3 pods to consume the allocated quota in namespace:
#   run <name>     : Imperatively creates a standalone Pod
#   --image=busybox: Lightweight Linux image
#   -n ivolve      : Target namespace subject to ivolve-quota
#   -- sleep 3600  : Overrides container command to keep pod running in background
kubectl run test-1 --image=busybox -n ivolve -- sleep 3600
kubectl run test-2 --image=busybox -n ivolve -- sleep 3600
kubectl run test-3 --image=busybox -n ivolve -- sleep 3600

# Inspect quota consumption and current utilization:
#   -n ivolve : Scope query to ivolve namespace
kubectl get resourcequota -n ivolve
NAME AGE REQUEST LIMIT ivolve-quota 30s pods: 3 pods: 3 (100% Full)
4. Attempt to Create a 4th Pod (Quota Enforcement)
# This command will be rejected by the API admission controller:
kubectl run test-4 --image=busybox -n ivolve -- sleep 3600
Error from server (Forbidden): pods "test-4" is forbidden: exceeded quota: ivolve-quota, requested: pods=1, used: pods=3, limited: pods=3
# Clean up test pods:
kubectl delete pod test-1 test-2 test-3 -n ivolve

Tips

  • Naming Gotcha (RFC 1123): The lab sheet says ivolveQuota. In Kubernetes, resource names must always be lowercase alphanumeric characters or hyphens (ivolve-quota). If you write camelCase letters like ivolveQuota, Kubernetes rejects the YAML with a syntax error.
Lab 12 Kubernetes

🔐 Managing Configuration and Sensitive Data with ConfigMaps and Secrets

Objective: Inject database URLs through ConfigMaps and store passwords safely inside Base64-encoded Kubernetes Secrets.

ConfigMapsSecretsBase64Decoupled Config
📋 Lab Prompt & Requirements (Slide Task)
  • Create a ConfigMap named ivolveCM in ivolve ns to store non-sensitive MySQL configuration variables:
  • • DB_HOST: The hostname of the MySQL StatefulSet's headless Service.
  • • DB_USER: The application database user authorized to connect to the ivolve database.
  • Create a Secret named ivolveSecret in ivolve ns to store sensitive MySQL credentials:
  • • MYSQL_ROOT_PASSWORD: The root password for the MySQL database.
  • • DB_PASSWORD: The password for the application database user specified by DB_USER.
  • Use Base64 encoding to encode the Secret data values when defining the Secret using a YAML manifest.

The Core Idea & Concepts

Never write passwords or database hostnames directly inside your application code. Why? Because you would have to edit and recompile your code every time you switch from local testing to staging or production.

Kubernetes gives you two distinct storage boxes:

  • Box 1: ConfigMap (For Non-Sensitive Info): Put public settings here: server hostnames, port numbers, log levels, and database usernames (e.g., DB_USER: ivolve).
  • Box 2: Secret (For Confidential Info): Put passwords, API tokens, and private SSH keys here. Secret values are encoded in Base64 and stored in a special temporary memory filesystem inside pods so they are never written to unencrypted disks.

Architecture & Workflow Flowchart

Public Config ConfigMap (ivolve-cm) DB_HOST + DB_USER
➔ envFrom ➔
Injected at Runtime Application Pods Namespace: ivolve
➔ envFrom ➔
Confidential Secret (ivolve-secret) Base64 Encoded Passwords

Step-by-Step Solution & Commands

1. Create the ConfigMap for Non-Sensitive Variables
apiVersion: v1
kind: ConfigMap
metadata:
  name: ivolve-cm
  namespace: ivolve
data:
  DB_HOST: "ivolve-db-svc.ivolve.svc.cluster.local"   # Headless service DNS from Lab 14
  DB_USER: "ivolve"
kubectl apply -f configmap.yaml
2. Encode Passwords and Create the Secret

Use the base64 terminal command to encode the passwords:

# Encode passwords into Base64 format:
#   -n : Suppresses trailing newline (prevents appending hidden 
 that breaks password authentication)
echo -n 'ivolveroot123' | base64    # -> aXZvbHZlcm9vdDEyMw==
echo -n 'ivolvedb123'   | base64    # -> aXZvbHZlZGIxMjM=
apiVersion: v1
kind: Secret
metadata:
  name: ivolve-secret
  namespace: ivolve
type: Opaque                           # Standard unformatted arbitrary user-defined secret data
data:
  MYSQL_ROOT_PASSWORD: "aXZvbHZlcm9vdDEyMw=="
  DB_PASSWORD: "aXZvbHZlZGIxMjM="
kubectl apply -f secret.yaml
3. Verify Objects and Decode Secret
# Verify both objects exist in the ivolve namespace:
#   -n ivolve : Scope query to ivolve namespace
kubectl get configmap,secret -n ivolve

# Decode the secret value from the cluster to confirm:
#   -o jsonpath='{...}' : Extracts specific field from resource JSON structure
#   base64 -d           : Decodes base64 string back to plaintext
kubectl get secret ivolve-secret -n ivolve -o jsonpath='{.data.MYSQL_ROOT_PASSWORD}' | base64 -d
# Output: ivolveroot123

Tips

  • The echo -n Trick: If you forget -n and just run echo 'mypassword' | base64, your terminal adds an invisible newline character (\n) to the end of the password. Your app will send that extra newline when logging into MySQL and authentication will mysteriously fail!
  • Is Base64 True Encryption? No! Base64 is only encoding (obfuscation), like writing in pig latin. Anyone who can run kubectl get secret can decode it. In production, enable etcd encryption at rest with AWS KMS or HashiCorp Vault.
Lab 13 Kubernetes

💾 Persistent Storage Setup for Application Logging

Objective: Ensure application logs survive container crashes by binding a hostPath PersistentVolume with a PersistentVolumeClaim.

PersistentVolumePVCReadWriteManyhostPath
📋 Lab Prompt & Requirements (Slide Task)
  • Define a Persistent Volume (PV) with the following specifications:
  • • Name: ivolvePV
  • • Size: 1Gi
  • • Storage type: hostPath
  • • Path: /mnt/app-logs on the node file system
  • • Access mode: ReadWriteMany (to allow all replicas read/write access)
  • • Reclaim policy: Retain
  • Define a Persistent Volume Claim (PVC) with name ivolvePVC that requests 1Gi storage.
  • Ensure the PVC access mode matches the PV (ReadWriteMany).
  • Do not use any StorageClass.

The Core Idea & Concepts

Containers are temporary (ephemeral). When a container restarts, crashes, or updates to a new version, every file written inside it is deleted.

If your app writes access logs to /app/logs, you will lose all audit history whenever a pod restarts. Kubernetes solves this by separating storage into two roles:

  • PersistentVolume (PV) - The Hard Drive: A real storage volume created on the cluster. In this lab, it points to a real folder on the physical node (/mnt/app-logs).
  • PersistentVolumeClaim (PVC) - The Voucher / Request: The application developer does not need to know where the physical hard drive is. They just say: "I need a 1 GB drive with ReadWriteMany access."
  • The Binding: Kubernetes automatically finds a PV that matches the PVC's request and permanently marries them together (Status: Bound).

Architecture & Workflow Flowchart

Host System /mnt/app-logs Physical Disk Path
➔ Mapped to ➔
Cluster Storage PV: ivolve-pv 1Gi, ReadWriteMany
➔ Bound to ➔
Namespace Request PVC: ivolve-pvc Mounts to /app/logs

Step-by-Step Solution & Commands

1. Create Unified PV and PVC Manifest
apiVersion: v1
kind: PersistentVolume
metadata:
  name: ivolve-pv
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteMany                    # Allows multiple pods to write logs simultaneously
  persistentVolumeReclaimPolicy: Retain # Keeps data safe if the PVC is deleted
  storageClassName: ""                 # Empty string forces static binding!
  hostPath:
    path: /mnt/app-logs
    type: DirectoryOrCreate
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: ivolve-pvc
  namespace: ivolve
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: ""                 # Must match the PV's empty storageClassName
  resources:
    requests:
      storage: 1Gi
2. Apply and Verify the Binding
kubectl apply -f pv-pvc.yaml

# Check status of both objects:
kubectl get pv,pvc -n ivolve
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM persistentvolume/ivolve-pv 1Gi RWX Retain Bound ivolve/ivolve-pvc NAME STATUS VOLUME CAPACITY ACCESS MODES persistentvolumeclaim/ivolve-pvc Bound ivolve-pv 1Gi RWX

Tips

  • The storageClassName: "" Trap: If you omit storageClassName on the PVC, the cluster's automatic cloud provisioner will hijack the request, create a brand-new dynamic disk, and ignore your manual ivolve-pv! Setting storageClassName: "" is the only way to tell Kubernetes: "Do not use automatic provisioning; bind to my manual PV."
Lab 14 Kubernetes

🗄️ StatefulSet with Headless Service

Objective: Deploy a MySQL database with a predictable network name and permanent storage using StatefulSets and a Headless Service.

StatefulSetHeadless ServiceMySQL 8.0CoreDNS
📋 Lab Prompt & Requirements (Slide Task)
  • Create ivolveDB StatefulSet in ivolve ns with 1 replica running MySQL.
  • Configure the StatefulSet pod to consume environment variables from the ConfigMap and Secret.
  • Add node selector to ensure the pod will run on node with label 'project=ivolve'.
  • Add a toleration to the StatefulSet with key-value 'workload=ivolveApp' and effect NoSchedule.
  • Configure a Persistent Volume Claim (PVC) template to mount /var/lib/mysql in the pod.
  • Write a YAML manifest for a headless service with name ivolveDBSvc targeting the MySQL StatefulSet pod.
  • Confirm the database is operational by connecting with a MySQL client.
  • Verify Mysql pod DNS resolution inside the cluster.

The Core Idea & Concepts

Why can't we use a normal Deployment for a database like MySQL?

  • Deployments are for Anonymous Workers: In a Deployment, pods get random names (like app-7dfb8-xk2). If a pod dies, the replacement gets a new random name. That's fine for web servers, but terrible for databases.
  • StatefulSets are for Identifiable Leaders: In a StatefulSet, pods get ordered, predictable names starting from 0: ivolve-db-0. If ivolve-db-0 crashes, it is recreated with the exact same name ivolve-db-0 and automatically re-attaches to its exact same hard drive!
  • What is a Headless Service? A normal Kubernetes service gives you one shared IP that randomly balances traffic. A Headless Service (clusterIP: None) tells the internal CoreDNS server: "Give this specific database pod its own direct DNS name: ivolve-db-0.ivolve-db-svc.ivolve.svc.cluster.local."

Architecture & Workflow Flowchart

Direct DNS Headless Service clusterIP: None
➔ Predictable FQDN ➔
Pod Identity ivolve-db-0 StatefulSet (MySQL 8.0)
➔ Injects ➔
Config & Data CM + Secret + PVC Mounted /var/lib/mysql

Step-by-Step Solution & Commands

1. Create the Manifest
apiVersion: v1
kind: Service
metadata:
  name: ivolve-db-svc                  # The Headless Service
  namespace: ivolve
spec:
  clusterIP: None                      # clusterIP: None makes it Headless!
  selector:
    app: ivolve-db
  ports:
    - port: 3306
      name: mysql
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: ivolve-db
  namespace: ivolve
spec:
  serviceName: ivolve-db-svc           # Must match the Headless Service name!
  replicas: 1
  selector:
    matchLabels:
      app: ivolve-db
  template:
    metadata:
      labels:
        app: ivolve-db
    spec:
      nodeSelector:
        project: ivolve                # Target the isolated node from Lab 10
      tolerations:
        - key: "workload"
          operator: "Equal"
          value: "ivolveApp"
          effect: "NoSchedule"
      containers:
        - name: mysql
          image: mysql:8.0
          ports:
            - containerPort: 3306
              name: mysql
          envFrom:
            - configMapRef:
                name: ivolve-cm        # Load DB_HOST and DB_USER from Lab 12
            - secretRef:
                name: ivolve-secret    # Load passwords from Lab 12
          volumeMounts:
            - name: mysql-data
              mountPath: /var/lib/mysql
  volumeClaimTemplates:
    - metadata:
        name: mysql-data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 1Gi
2. Apply and Wait for Ready
# Apply StatefulSet and Headless Service manifests:
kubectl apply -f statefulset.yaml

# Wait until MySQL pod initializes storage and passes readiness probes:
#   --for=condition=Ready : Blocks execution until Pod condition equals Ready
#   --timeout=180s        : Aborts with error if pod fails to initialize within 3 minutes
kubectl wait --for=condition=Ready pod/ivolve-db-0 -n ivolve --timeout=180s
3. Verify Placement and Database Operation
# Verify the pod landed on the tainted desktop-worker:
#   -o wide : Displays node assignment (desktop-worker) and pod IP
kubectl get pods -n ivolve -o wide
# Output shows ivolve-db-0 on desktop-worker

# Run a query directly inside MySQL database container:
#   exec ivolve-db-0 : Targets pod instance
#   --               : Separates kubectl arguments from inner container command
#   -uroot -p...     : MySQL credentials
#   -e "..."         : Executes SQL query string non-interactively
kubectl exec ivolve-db-0 -n ivolve -- mysql -uroot -pivolveroot123 -e "SHOW DATABASES;"
# Lists: information_schema, ivolve, mysql, performance_schema, sys
4. Verify In-Cluster Headless DNS Name
# Connect through the full DNS domain name provided by Headless Service:
#   -h <FQDN> : Connects via CoreDNS hostname: <pod>.<service>.<ns>.svc.cluster.local
kubectl exec ivolve-db-0 -n ivolve --   mysql -h ivolve-db-0.ivolve-db-svc.ivolve.svc.cluster.local -uroot -pivolveroot123   -e "SELECT @@hostname;"
# Output: ivolve-db-0 (DNS resolution confirmed working!)

Tips

  • Naming Matching Rule: The serviceName under spec in the StatefulSet must exactly match the metadata.name of your Headless Service. If you misspell it, the pod will run, but internal DNS records will never be registered!
  • Persistent Storage Safety: When you delete a StatefulSet, Kubernetes intentionally leaves the PVCs untouched. This prevents you from accidentally wiping out your company's production database with one command.
Lab 15 Kubernetes

🚀 Node.js Application Deployment with ClusterIP service

Objective: Deploy two replicas of the Node.js application, use an Init Container to automatically initialize the MySQL database schema, and expose it internally with a ClusterIP service.

DeploymentInit ContainersClusterIP ServiceSelf-Healing
📋 Lab Prompt & Requirements (Slide Task)
  • Create a Deployment named ivolveApp in ivolve ns with 2 replicas.
  • Use your custom Docker image from Docker Hub created in Lab 8.
  • Configure the pods to consume environment variables from the existing ConfigMap and Secret.
  • Add a node selector to schedule pods on nodes labeled project=ivolve.
  • Add a toleration with key workload, value ivolveApp, and effect NoSchedule.
  • Configure the pods to use the PersistentVolume created in Lab 13.
  • Add an init container using a MySQL client image to create the ivolve database and grant the application user the necessary privileges.
  • Pass the database connection parameters to the init container using environment variables from the ConfigMap and Secret.
  • Create a ClusterIP Service named ivolvaAppSvc in ivolve ns to distribute traffic across the available application pods.
  • Connect to MySQL manually to verify that the ivolve database was created and the application user has the required privileges.
  • Check the application logs to verify that the Node.js application successfully connects to MySQL and accesses the ivolve database.

The Core Idea & Concepts

Now that our MySQL database is running from Lab 14, we are ready to deploy our Node.js web app. But there is a classic timing problem:

  • The Problem: When the Node.js app boots, it expects the ivolve database and user privileges to already exist. If MySQL isn't ready or the user isn't created, the Node app crashes instantly.
  • The Solution (Init Containers): An Init Container is a helper container that runs first before your main app container starts.
    • The helper container connects to MySQL, runs CREATE DATABASE IF NOT EXISTS ivolve;, grants permissions, and then gracefully exits.
    • Only after the helper container finishes with success does Kubernetes start your Node.js application!
  • ClusterIP Service: A private internal load balancer. It gives you one stable IP (e.g. ivolve-app-svc:3000) that automatically shares traffic equally between the two app replicas.

Architecture & Workflow Flowchart

Step 1 (First) Init Container Seeds MySQL Database
➔ Exits 0 ➔
Step 2 (Main) Node.js App 2 Replicas on Port 3000
➔ Balance ➔
Internal Gateway ClusterIP Service ivolve-app-svc

Step-by-Step Solution & Commands

1. Create the Deployment and Service Manifest
apiVersion: v1
kind: Service
metadata:
  name: ivolve-app-svc                 # ClusterIP Service for application
  namespace: ivolve
spec:
  type: ClusterIP
  selector:
    app: ivolve-app
  ports:
    - port: 3000
      targetPort: 3000
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ivolve-app
  namespace: ivolve
spec:
  replicas: 2                          # Run 2 copies for high availability
  selector:
    matchLabels:
      app: ivolve-app
  template:
    metadata:
      labels:
        app: ivolve-app
    spec:
      nodeSelector:
        project: ivolve
      tolerations:
        - key: "workload"
          operator: "Equal"
          value: "ivolveApp"
          effect: "NoSchedule"
      initContainers:                  # Runs before the app starts
        - name: init-db
          image: mysql:8.0
          envFrom:
            - configMapRef:
                name: ivolve-cm
            - secretRef:
                name: ivolve-secret
          command:
            - sh
            - -c
            - |
              mysql -h $DB_HOST -uroot -p$MYSQL_ROOT_PASSWORD <<EOF
              CREATE DATABASE IF NOT EXISTS ivolve;
              CREATE USER IF NOT EXISTS '$DB_USER'@'%' IDENTIFIED BY '$DB_PASSWORD';
              GRANT ALL PRIVILEGES ON ivolve.* TO '$DB_USER'@'%';
              FLUSH PRIVILEGES;
              EOF
      containers:
        - name: app
          image: abdalrahmanx/ivolve-app:v1  # Image pushed in Lab 8!
          ports:
            - containerPort: 3000
          envFrom:
            - configMapRef:
                name: ivolve-cm
            - secretRef:
                name: ivolve-secret
          volumeMounts:
            - name: logs
              mountPath: /app/logs
      volumes:
        - name: logs
          persistentVolumeClaim:
            claimName: ivolve-pvc      # Logging PVC from Lab 13
2. Apply and Verify Rollout
# Apply Deployment and ClusterIP Service manifests:
kubectl apply -f deployment.yaml

# Watch deployment rollout progress until both replica pods are running:
#   rollout status : Streams rollout updates and exits 0 when replica count matches spec
kubectl rollout status deployment/ivolve-app -n ivolve
3. Functional Checks
# Check app logs to verify clean database connection:
#   -c app    : Selects the main application container (skipping init-db)
#   --tail=10 : Displays only the last 10 log lines
kubectl logs deployment/ivolve-app -n ivolve -c app --tail=10
# Shows: "Connected to MySQL and 'ivolve' DB found. Server started on http://0.0.0.0:3000"

# Test response from the internal ClusterIP service via cluster DNS:
#   exec deployment/... : Selects one running pod from deployment
#   -c app              : Specifies target container
#   wget -qO-           : -q quiet mode, -O- prints response body directly to stdout
kubectl exec deployment/ivolve-app -n ivolve -c app -- wget -qO- http://ivolve-app-svc:3000/health
# Output: iVolve web app is working! Keep calm and code on!

Tips

  • ConfigMap DNS Fix: Make sure the DB_HOST inside your Lab 12 ConfigMap is set to ivolve-db-svc.ivolve.svc.cluster.local (the headless service name from Lab 14). If it was set to something generic like mysql, the app will never find the database.
Lab 16 Kubernetes

📊 Pod Resource Management with CPU and Memory Requests and Limits

Objective: Set CPU and RAM requests and limits on your deployment, solve the rolling update quota deadlock, and monitor live consumption with metrics-server.

Resource LimitsQoSMetrics-ServerQuota Deadlock
📋 Lab Prompt & Requirements (Slide Task)
  • Update the existing ivolveApp Deployment to include resource requests and limits.
  • Resource Requests:
  • ✓ cpu: 1 (1 vCPU)
  • ✓ memory: 1Gi
  • Resource Limits:
  • ✓ cpu: 2 (2 vCPUs)
  • ✓ memory: 2Gi
  • Use kubectl describe pod to verify the applied resource requests and limits.
  • Use kubectl top pod to monitor real-time resource usage (metric server must be running in the cluster).

The Core Idea & Concepts

How does Kubernetes keep pods from fighting over CPU and memory?

  • Requests (The Guaranteed Reservation): This is the minimum amount of CPU and RAM your pod needs to survive. The scheduler uses requests to find a node that has enough spare room.
  • Limits (The Ceiling): This is the maximum amount your pod is allowed to use. If your pod tries to consume more CPU than its limit, Linux throttles it. If it tries to consume more memory than its limit, Linux terminates it (OOMKilled).
  • The Rolling Update Quota Deadlock:
    • In Lab 11, we set a ResourceQuota of 3 pods maximum.
    • Currently running: 2 app pods + 1 MySQL pod = 3 pods (100% full).
    • When you update a Deployment, Kubernetes starts a new surge pod before killing the old one to avoid downtime.
    • But the 4th pod is rejected by the quota! The deployment gets stuck in a deadlock until you increase the namespace quota headroom to 5 pods.

Architecture & Workflow Flowchart

Quota Problem 3/3 Pods Full Surge Pod Blocked!
➔ Patch Quota ➔
Headroom Added Quota: 5 Pods Rollout Completes
➔ Verify ➔
Live Monitoring kubectl top pod Shows real CPU & RAM

Step-by-Step Solution & Commands

1. Add Resources to the Deployment
# Added inside deployment.yaml under spec.template.spec.containers[0]:
resources:
  requests:
    cpu: "1"
    memory: "1Gi"
  limits:
    cpu: "2"
    memory: "2Gi"
2. Solve the Quota Deadlock

When applying the update, Kubernetes attempts to create a surge pod and fails with:

FailedCreate: exceeded quota: ivolve-quota, requested: pods=1, used: pods=3, limited: pods=3

Increase the namespace quota from 3 to 5 to allow rolling update headroom:

# Update the pod limit to 5 in resourcequota.yaml and re-apply:
# (Or run 'kubectl edit resourcequota ivolve-quota -n ivolve' and set pods: "5")
sed -i 's/pods: "3"/pods: "5"/' ../Lab11/resourcequota.yaml
kubectl apply -f ../Lab11/resourcequota.yaml

# Apply the updated deployment with resource requests and limits:
kubectl apply -f deployment.yaml
kubectl rollout status deployment/ivolve-app -n ivolve
3. Install Metrics-Server

Download the official manifest, add the --kubelet-insecure-tls flag to container args (required for self-signed kubelet certificates), and apply:

# Download official Kubernetes SIGs metrics-server manifest:
curl -LO https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

# Add --kubelet-insecure-tls argument for local/kubeadm self-signed certificates:
sed -i '/--kubelet-preferred-address-types/a \        - --kubelet-insecure-tls' components.yaml

# Deploy metrics-server:
kubectl apply -f components.yaml
4. Verify Live Resource Usage
# Verify limits configured on deployment:
#   grep -A5 Limits : Shows matching line plus 5 following lines of limits configuration
kubectl describe deployment ivolve-app -n ivolve | grep -A5 Limits

# Monitor real-time CPU and memory usage of running pods:
#   top pod : Queries metrics-server for current CPU (cores/millicores) and RAM bytes
kubectl top pod -n ivolve
NAME CPU(cores) MEMORY(bytes) ivolve-app-5d4c4c8d8c-mmnlm 1m 22Mi ivolve-app-5d4c4c8d8c-ndtz4 1m 21Mi ivolve-db-0 8m 370Mi

Tips

  • Why does the app only use 21 MiB? Notice that the app uses ~21 MiB while we requested 1 GiB. Remember: requests are not what the app is currently using—they are what is reserved on the server to ensure the pod never starves during peak traffic.
Lab 17 Kubernetes

🔒 Control Pod-to-Pod Traffic via Network Policy

Objective: Block unauthorized access to MySQL by creating an in-cluster firewall policy that allows traffic only from your Node.js application pods.

NetworkPolicyZero-TrustFirewallPort 3306
📋 Lab Prompt & Requirements (Slide Task)
  • Define a Network Policy with the following specifications:
  • • Name: ivolveNP
  • • Pod Selector: Targets mysql pod.
  • • Policy Types: Only Ingress
  • • Ingress Rule:
  • ✓ Allows traffic only from the application pods.
  • ✓ Restrict access to port 3306 (MySQL default port).

The Core Idea & Concepts

By default, Kubernetes network security is wide open: any pod in the entire cluster can connect to any other pod. If an intern or compromised app in another namespace knows MySQL's IP, they can connect directly to your database.

A NetworkPolicy is a firewall for Kubernetes pods:

  • The moment you attach a NetworkPolicy to your MySQL pod, it enters Default-Deny mode. All incoming traffic is blocked.
  • Then you punch one single hole in the firewall: "Allow traffic on port 3306, but ONLY from pods that have the label app: ivolve-app."
  • Any other pod that tries to connect gets timed out and dropped.

Architecture & Workflow Flowchart

Authorized Pod
Label: app=ivolve-app ➔ Port 3306 ➔ ALLOWED!
Connection Succeeded
Matches the ingress rule in ivolve-np.
Unauthorized Pod
Different Label / Namespace ➔ Port 3306 ➔ DROPPED!
Connection Timed Out
Blocked by Calico CNI firewall enforcement.

Step-by-Step Solution & Commands

1. Create the NetworkPolicy Manifest
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: ivolve-np
  namespace: ivolve
spec:
  podSelector:
    matchLabels:
      app: ivolve-db                   # Firewall protects the MySQL pod
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: ivolve-app          # ONLY pods with this label can enter!
      ports:
        - protocol: TCP
          port: 3306                   # Strictly MySQL port
2. Apply and Verify
# Apply NetworkPolicy firewall rules to cluster:
kubectl apply -f networkpolicy.yaml

# Verify NetworkPolicy is recognized by CNI:
kubectl get networkpolicy -n ivolve
NAME POD-SELECTOR AGE ivolve-np app=ivolve-db 10s
3. Functional Verification
# Test 1: Connection from authorized application pod (ALLOWED):
#   -c app      : Target Node.js application container
#   nc -zvw3    : Netcat flags:
#                 -z : Zero-I/O mode (port scan without transmitting payload)
#                 -v : Verbose status output
#                 -w3: Timeout after 3 seconds if packet blocked
kubectl exec deployment/ivolve-app -n ivolve -c app -- nc -zvw3 ivolve-db-svc 3306
# Output: Connection to ivolve-db-svc 3306 port [tcp/mysql] succeeded!

# Test 2: Connection from unauthorized pod in default namespace (BLOCKED on Calico):
#   --rm -it    : Ephemeral interactive container deleted immediately upon exit
kubectl run rogue --image=busybox -n default --rm -it -- nc -zvw3 10.244.2.3 3306
# Output: Connection timed out! (Packets dropped by Calico iptables filter)

Tips

  • CNI Requirement: Remember from Lab 9: Kubernetes itself does not filter packets. An active CNI like Calico or Cilium must be installed to enforce NetworkPolicies. On default Kind/Docker-Desktop clusters without Calico, the manifest is saved, but packets aren't filtered.
Lab 18 Kubernetes

📈 Node-Wide Pod Management with DaemonSet & Cluster Monitoring

Objective: Deploy a complete monitoring system using a DaemonSet to collect machine hardware metrics across every server and graph them in Grafana.

DaemonSetPrometheusGrafananode-exporterAlertmanager
📋 Lab Prompt & Requirements (Slide Task)
  • Create monitoring namespace.
  • Deploy Prometheus in the monitoring namespace.
  • Deploy Alert Manager in the monitoring namespace.
  • Deploy Grafana in the monitoring namespace.
  • Deploy a DaemonSet for Prometheus node-exporter in the monitoring namespace.
  • Validate that a node-exporter pod is scheduled on each node.
  • Confirm correct metrics exposure by accessing <node_IP>:9100/metrics.
  • Configure Prometheus to collect data from node-exporter.
  • Configure Grafana dashboard for Kubernetes.

The Core Idea & Concepts

How do company monitoring teams know when a server's disk is 99% full or CPU is burning at 100%?

  • What is a DaemonSet? A normal Deployment runs 2 or 3 pods anywhere. A DaemonSet guarantees that every single server in your cluster runs exactly one copy of the monitoring pod. If you add 10 new servers tomorrow, Kubernetes automatically puts the monitoring pod on all 10 without you doing anything.
  • The 4 Pieces of the Monitoring Stack:
    1. node-exporter (The Sensor): A DaemonSet pod that reads Linux CPU, RAM, and disk metrics and exposes them at :9100/metrics.
    2. Prometheus (The Database & Collector): Periodically scrapes numbers from every node-exporter and saves them over time.
    3. Alertmanager (The Siren): Sends an alert (Slack, email, SMS) if a server crashes.
    4. Grafana (The Dashboard): Draws beautiful interactive graphs and charts so you can see your servers live on screen.

Architecture & Workflow Flowchart

Every Node node-exporter Port 9100 Metrics
➔ Scrapes Every 15s ➔
Time-Series DB Prometheus Stores Cluster Health
➔ Feeds ➔
Visualization Grafana Dashboard #1860

Step-by-Step Solution & Commands

1. Deploy Monitoring Namespace and node-exporter DaemonSet
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: node-exporter
  namespace: monitoring
spec:
  selector:
    matchLabels:
      app: node-exporter
  template:
    metadata:
      labels:
        app: node-exporter
    spec:
      hostNetwork: true                # Reads real host networking
      hostPID: true
      tolerations:
        - operator: "Exists"          # Ensures it lands on master/control-plane nodes too
      containers:
        - name: node-exporter
          image: prom/node-exporter:v1.8.1
          ports:
            - containerPort: 9100
              hostPort: 9100
          volumeMounts:
            - name: proc
              mountPath: /host/proc
              readOnly: true
            - name: sys
              mountPath: /host/sys
              readOnly: true
      volumes:
        - name: proc
          hostPath: { path: /proc }
        - name: sys
          hostPath: { path: /sys }
2. Apply the Complete Observability Stack
# Apply complete monitoring stack manifests:
kubectl apply -f 00-namespace-rbac.yaml -f 01-node-exporter.yaml -f 02-prometheus.yaml -f 03-alertmanager.yaml -f 04-grafana.yaml

# Import the popular Node Exporter Full Dashboard (ID 1860) JSON into Grafana:
#   --from-file : Loads entire JSON dashboard file into a ConfigMap key
kubectl create configmap grafana-dashboard-k8s -n monitoring --from-file=node-exporter-full.json

# Trigger rolling restart to mount the new dashboard ConfigMap into Grafana pod:
#   rollout restart : Gracefully terminates existing pods and launches replacements with new volume mounts
kubectl rollout restart deployment/grafana -n monitoring
3. Access Grafana Live Dashboard
# Forward local workstation port to Grafana service inside cluster:
#   -n monitoring     : Target monitoring namespace
#   svc/grafana       : Kubernetes Service object
#   3000:3000         : Maps local port 3000 to remote Service port 3000
kubectl port-forward -n monitoring svc/grafana 3000:3000

Open http://localhost:3000 in your browser (Username: admin, Password: admin). Click on Dashboards → "Node Exporter Full" to view live graphs of all nodes!

Tips

  • Image Name Mistake: Be careful with Docker image names: the official image is prom/node-exporter. If you accidentally write prometheus/node-exporter, that repo doesn't exist and your pods will get stuck in ImagePullBackOff!
  • Control Plane Toleration: If your master node has the control-plane:NoSchedule taint, normal pods won't land on it. Adding tolerations: [{operator: Exists}] ensures you monitor your master node hardware too.
Lab 19 Kubernetes

🛡️ Securing Kubernetes with RBAC and Service Accounts

Objective: Create a strictly limited service account token for automated CI systems (like Jenkins) that can only touch Deployments in the ivolve namespace.

RBACServiceAccountLeast PrivilegeRoleBinding
📋 Lab Prompt & Requirements (Slide Task)
  • Create jenkinsSA Service Account in the ivolve namespace.
  • Create a token for the service account.
  • Define a Role named ivolveDeployRole that grants create/update permissions on deployment in the ivolve namespace.
  • Create a Role Binding with name ivolveDeployRoleBinding to bind the ivolveDeployRole role to the jenkinsSA service account.
  • Validate the role can only create/update deployment in ivolve namespace.

The Core Idea & Concepts

When you automate deployments using Jenkins or GitHub Actions, your CI server needs to communicate with Kubernetes to deploy new versions. But you should never give Jenkins cluster administrator credentials.

If a hacker breaches your Jenkins server and Jenkins has admin keys, the hacker owns your whole company cluster! We apply the Principle of Least Privilege:

  • ServiceAccount: A user account meant for computer software (not humans). We name it jenkins-sa.
  • Role: A list of exact allowed actions. We say: "You may ONLY create, update, get, and patch Deployments inside the ivolve namespace. You cannot delete pods, you cannot view secrets, and you cannot touch any other namespace."
  • RoleBinding: The chain that ties the Role to the ServiceAccount.

Architecture & Workflow Flowchart

Identity jenkins-sa ServiceAccount
➔ Bound via ➔
RoleBinding ivolveDeployRole Namespace: ivolve
➔ Scope Test ➔
Security Result Deployments: YES Pods / Other NS: DENIED

Step-by-Step Solution & Commands

1. Create the RBAC Manifest
apiVersion: v1
kind: ServiceAccount
metadata:
  name: jenkins-sa                     # Lowercase RFC 1123 name
  namespace: ivolve
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: ivolve-deploy-role
  namespace: ivolve
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["create", "update", "get", "patch"] # get/patch are required for kubectl apply!
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ivolve-deploy-role-binding
  namespace: ivolve
subjects:
  - kind: ServiceAccount
    name: jenkins-sa
    namespace: ivolve
roleRef:
  kind: Role
  name: ivolve-deploy-role
  apiGroup: rbac.authorization.k8s.io
kubectl apply -f rbac.yaml
2. Create Permanent Token for Jenkins
apiVersion: v1
kind: Secret
metadata:
  name: jenkins-sa-token
  namespace: ivolve
  annotations:
    kubernetes.io/service-account.name: jenkins-sa
type: kubernetes.io/service-account-token
kubectl apply -f jenkins-sa-token.yaml
3. Validate Scoped Permissions
# Extract bearer token from Secret data:
#   -o jsonpath='{.data.token}' : Selects token field
#   base64 -d                   : Decodes Base64 to plaintext JWT token
TOKEN=$(kubectl get secret jenkins-sa-token -n ivolve -o jsonpath='{.data.token}' | base64 -d)

# Test 1: Allowed - Create a deployment in ivolve namespace:
#   --token                       : Authenticates using the extracted ServiceAccount bearer token
#   --server                      : Address of Kubernetes API server
#   --insecure-skip-tls-verify    : Bypasses self-signed cluster CA check for testing
#   -n ivolve                     : In-scope namespace
kubectl --token=$TOKEN --server=<K8S_URL> --insecure-skip-tls-verify   create deployment test-deploy --image=busybox -n ivolve
# Output: deployment.apps/test-deploy created (ALLOWED)

# Test 2: Forbidden - Attempt to create a pod directly:
kubectl --token=$TOKEN --server=<K8S_URL> --insecure-skip-tls-verify   run test-pod --image=busybox -n ivolve
# Output: Error from server (Forbidden): User cannot create resource "pods"!

# Test 3: Forbidden - Attempt to touch default namespace:
kubectl --token=$TOKEN --server=<K8S_URL> --insecure-skip-tls-verify   create deployment test-deploy --image=busybox -n default
# Output: Error from server (Forbidden): cannot create in namespace "default"!

Tips

  • Why get and patch are Required: The slide says "grant create/update". But when Jenkins runs kubectl apply, kubectl must first get the current deployment from the cluster and patch the differences. If you forget get and patch, your pipeline will fail with a forbidden error!
Lab 20 Jenkins CI/CD

👨‍💼 Role-Based Authorization in Jenkins

Objective: Configure Jenkins user permissions automatically at startup using Groovy code so user1 has full admin rights and user2 has read-only access.

JenkinsRBACMatrix SecurityJenkins as Code
📋 Lab Prompt & Requirements (Slide Task)
  • Create user1 and user2 in Jenkins.
  • Assign admin role for user1 & read-only role for user2.

The Core Idea & Concepts

If you set up Jenkins by clicking buttons in the web UI, what happens when your server hard drive crashes? You have to click all those buttons again by hand.

In modern DevOps, we practice Configuration as Code:

  • Automated Setup via Groovy: Jenkins lets you place .groovy scripts in an init.groovy.d/ folder. When Jenkins turns on, it runs these scripts automatically and configures itself without human intervention.
  • User 1 (The Administrator): Has Jenkins.ADMINISTER permissions. They can create jobs, install plugins, edit system settings, and trigger deployments.
  • User 2 (The Read-Only Stakeholder): Has Jenkins.READ, Item.READ, and View.READ. They can log in, view build history, and read console logs. But if they try to click "Build Now" or edit job settings, Jenkins blocks them with a 403 Forbidden error!

Architecture & Workflow Flowchart

user1 (Administrator)
Jenkins.ADMINISTER ➔ Full Access
Can Build & Configure
POST /job/.../build ➔ HTTP 201 Created
user2 (Read-Only)
Item.READ only ➔ View Dashboard Only
Cannot Trigger Builds
POST /job/.../build ➔ HTTP 403 Forbidden

Step-by-Step Solution & Commands

1. The Security Initialization Script

Inspect the script that configures Jenkins users at boot:

import jenkins.model.*
import hudson.security.*

def instance = Jenkins.getInstance()

// Create the user accounts
def realm = new HudsonPrivateSecurityRealm(false)
realm.createAccount('user1', 'admin123')
realm.createAccount('user2', 'read123')
instance.setSecurityRealm(realm)

// Configure the Matrix Authorization Table
def strategy = new GlobalMatrixAuthorizationStrategy()

// user1 gets full administrator power:
strategy.add(Jenkins.ADMINISTER, 'user1')

// user2 gets read-only permissions:
strategy.add(Jenkins.READ, 'user2')
strategy.add(hudson.model.Item.READ, 'user2')
strategy.add(hudson.model.Item.DISCOVER, 'user2')
strategy.add(hudson.model.View.READ, 'user2')

instance.setAuthorizationStrategy(strategy)
instance.save()
println("--> RBAC Security Configuration Applied Successfully!")
2. Run Dockerized Jenkins with Volume Mounts
# Build customized Jenkins image:
#   -t jenkins-ivolve : Tags output image with friendly name
docker build -t jenkins-ivolve Jenkins/Lab20/jenkins

# Start Jenkins container exposing port 8888:
#   -d                               : Detached mode (runs container in background)
#   --name jenkins                   : Container instance identifier
#   -p 8888:8080                     : Maps host port 8888 to Jenkins internal web UI port 8080
#   -v jenkins_home:/var/jenkins_home: Named volume preserving job definitions, workspace history, and plugin configs
#   -v /var/run/docker.sock:...      : Mounts host Docker daemon socket so Jenkins can build images without nested virtualization
#   -e DOCKERHUB_USER / TOKEN        : Passes environment variables into container for pipeline automation
docker run -d --name jenkins -p 8888:8080   -v jenkins_home:/var/jenkins_home   -v /var/run/docker.sock:/var/run/docker.sock   -e DOCKERHUB_USER=abdalrahmanx -e DOCKERHUB_TOKEN=<TOKEN>   jenkins-ivolve
3. Verify Permissions (UI & REST API)
# Test 1: Admin user triggering a build (ALLOWED - 201 Created):
#   -u user1:admin123 : Basic Authentication HTTP header credentials
#   -X POST           : Sends HTTP POST method required by Jenkins build endpoint
curl -u user1:admin123 http://localhost:8888/job/demoapp/build -X POST
# Response: HTTP 201 (Build triggered!)

# Test 2: Read-only user trying to trigger a build (BLOCKED - 403 Forbidden):
#   -u user2:read123  : Authenticates as read-only user lacking Job/Build permission
curl -u user2:read123 http://localhost:8888/job/demoapp/build -X POST
# Response: HTTP 403 Forbidden! User2 lacks build permission.

Tips

  • The Overall READ Requirement: In Jenkins Matrix security, you must always grant Jenkins.READ to a user before anything else. If you grant Item.READ but forget Jenkins.READ, the user won't even be able to open the login dashboard!
Lab 21 Jenkins CI/CD

🔄 Jenkins Pipeline for Application Deployment

Objective: Build a complete 7-stage automated pipeline in Jenkins that tests code, builds Docker images, scans for security flaws, and updates Kubernetes.

JenkinsfileCI/CD PipelineTrivy ScanRolling Update
📋 Lab Prompt & Requirements (Slide Task)
  • Clone source code and Dockerfile from: https://github.com/Ibrahim-Adel15/DemoApp.git
  • Create a pipeline that automates the following processes:
  • 1. Build app
  • 2. Build Docker Image.
  • 3. Scan Docker Image
  • 4. Push image to DockerHub.
  • 5. Delete image locally.
  • 6. Update image in deployment file.
  • 7. Deploy to Kubernetes cluster.
  • Set pipeline post action (always, success, failure)

The Core Idea & Concepts

Every time a developer writes new code, we don't want them doing 10 manual steps on their laptop (compiling, building docker, logging into docker hub, running kubectl). Manual steps lead to human mistakes.

A CI/CD Pipeline is an automated robot script (written in a Jenkinsfile):

  • The 7 Automated Steps:
    1. Compile: Builds the Spring Boot JAR with Maven.
    2. Package: Builds the Docker image and tags it with the build number (e.g. :1, :2).
    3. Security Audit: Scans the image with Trivy to check for security vulnerabilities.
    4. Publish: Uploads the verified image to Docker Hub.
    5. Clean Disk: Deletes the local image on the build server so the server hard drive never runs out of space.
    6. Patch Manifest: Replaces the old image tag in k8s.yaml with the new build number.
    7. Deploy: Runs kubectl apply using the limited ServiceAccount token from Lab 19 to trigger a rolling update in Kubernetes!

Architecture & Workflow Flowchart

1 & 2 Maven + Docker Builds JAR & Image
➔
3 & 4 Trivy + Registry Scans & Pushes to Hub
➔
5 & 6 Clean + Patch sed image tag in YAML
➔
7. Deploy kubectl apply Zero-Downtime Rollout

Step-by-Step Solution & Commands

1. The Complete Declarative Jenkinsfile
pipeline {
    agent any

    environment {
        APP_NAME     = 'ivolve-demoapp'
        REGISTRY     = 'abdalrahmanx'
        IMAGE_NAME   = "${REGISTRY}/${APP_NAME}"
        DOCKER_CREDS = 'dockerhub'
        KUBECONFIG   = credentials('kubeconfig')
    }

    stages {
        stage('1. Build app') {
            steps {
                dir('Jenkins/Lab21/DemoApp') {
                    // -B: Batch mode (disables interactive prompts & progress spinner animation)
                    // clean: Deletes previous target/ build artifacts
                    // package: Compiles code, runs unit tests, packages into JAR
                    sh 'mvn -B clean package'
                }
            }
        }

        stage('2. Build Docker Image') {
            steps {
                dir('Jenkins/Lab21/DemoApp') {
                    // -t <name:tag>: Names and tags the image with the unique Jenkins BUILD_NUMBER
                    // .            : Build context path containing Dockerfile and compiled JAR
                    sh "docker build -t ${IMAGE_NAME}:${BUILD_NUMBER} ."
                }
            }
        }

        stage('3. Scan Docker Image') {
            steps {
                // --severity HIGH,CRITICAL: Limits vulnerability report to actionable high-risk flaws
                // --exit-code 0           : Runs security audit in non-blocking advisory mode so pipeline completes
                sh "trivy image --severity HIGH,CRITICAL --exit-code 0 ${IMAGE_NAME}:${BUILD_NUMBER}"
            }
        }

        stage('4. Push image to DockerHub') {
            steps {
                withCredentials([usernamePassword(credentialsId: DOCKER_CREDS,
                                                  usernameVariable: 'USER',
                                                  passwordVariable: 'PASS')]) {
                    // --password-stdin: Pipes secret from standard input avoiding shell history leakage
                    // -u <user>       : Docker Hub account username
                    sh "echo \$PASS | docker login -u \$USER --password-stdin"
                    sh "docker push ${IMAGE_NAME}:${BUILD_NUMBER}"
                }
            }
        }

        stage('5. Delete image locally') {
            steps {
                // rmi: Removes local image from Jenkins host to prevent hard drive saturation
                sh "docker rmi ${IMAGE_NAME}:${BUILD_NUMBER}"
            }
        }

        stage('6. Update image in deployment file') {
            steps {
                // -i: Edits file in-place
                // s|old|new|g: Regex replaces the image tag in Kubernetes manifest with current build number
                sh "sed -i 's|image: ${IMAGE_NAME}:.*|image: ${IMAGE_NAME}:${BUILD_NUMBER}|g' Jenkins/Lab21/k8s.yaml"
            }
        }

        stage('7. Deploy to Kubernetes cluster') {
            steps {
                // --kubeconfig: Passes authenticated ServiceAccount credentials from Lab 19
                // -f          : Specifies target Kubernetes manifest file
                sh "kubectl --kubeconfig \$KUBECONFIG apply -f Jenkins/Lab21/k8s.yaml"
                // rollout status: Blocks pipeline execution until deployment update reaches Ready state
                sh "kubectl --kubeconfig \$KUBECONFIG rollout status deployment/demoapp -n ivolve"
            }
        }
    }

    post {
        always {
            echo "Pipeline run completed for build #${BUILD_NUMBER}."
        }
        success {
            echo "Deployment succeeded! Pods are live in the ivolve namespace."
        }
        failure {
            echo "Deployment failed! Check the stage logs above for error details."
        }
    }
}
2. Run Build and Verify in Kubernetes
# Verify deployment in cluster:
#   -n ivolve      : Scope query to ivolve namespace
#   -l app=demoapp : Filter pods matching selector label
kubectl get pods -n ivolve -l app=demoapp
# Output: demoapp-...  1/1  Running

# Test HTTP output:
#   exec deployment/demoapp : Connects to an active replica pod of the deployment
#   -n ivolve               : Target namespace
#   --                      : Delimiter separating kubectl flags from container command
#   wget -qO-               : -q quiet mode (no progress bar), -O- streams body directly to stdout
kubectl exec deployment/demoapp -n ivolve -- wget -qO- http://demoapp-svc:8080/
# Output: Hello from Dockerized Spring Boot!

Tips

  • Why Delete the Image Locally in Stage 5? In an active company, Jenkins builds images 50 times a day. If you don't run docker rmi to delete local copies after pushing to Docker Hub, your build server's hard drive will fill up and crash within a month.
Lab 22 Jenkins CI/CD

📚 CI/CD Pipeline Implementation with Jenkins Agents and Shared Libraries

Objective: Avoid duplicating pipeline code across projects by writing reusable Jenkins Shared Libraries and running build steps inside dynamic Docker agent containers.

Shared LibrariesDocker AgentDRY PrincipleBuild Caching
📋 Lab Prompt & Requirements (Slide Task)
  • Clone Dockerfile from: https://github.com/Ibrahim-Adel15/DemoApp.git
  • Create the following shared libraries:
  • 1. BuildApp (Unit test, Build app)
  • 2. BuildImage (Build image, scan image push image, delete image locally)
  • 3. DeployOnK8s (edit deployment file, deploy to cluster)
  • Update your pipeline to use them.
  • Configure Jenkins slave to run the pipeline.

The Core Idea & Concepts

If your company has 40 microservices, do you want to copy and paste the same 100-line Jenkinsfile into all 40 repositories? No! If a command changes, you have to edit 40 files.

Two Techniques for Professional CI/CD:

  • 1. Jenkins Shared Libraries (Don't Repeat Yourself - DRY): You write your build functions once in a shared Git repository. Your microservices just import the library with @Library('ivolve-lib') _ and call clean one-liners like buildApp() or buildImage().
  • 2. Dynamic Docker Agents ("Slaves"): Instead of running Maven directly on the main Jenkins controller, Jenkins spins up an isolated Docker container (maven:3.9) just for the build step. When the build finishes, the container is destroyed.
    • A shared volume (ivolve-maven-repo:/root/.m2) caches downloaded dependencies so builds stay fast.

Architecture & Workflow Flowchart

Controller Loads Library @Library('ivolve-lib')
➔ Spins Up ➔
Ephemeral Agent maven:3.9 container Cached .m2 Volume
➔ Calls Steps ➔
Modular Pipeline buildApp() buildImage() ➔ deployOnK8s()

Step-by-Step Solution & Commands

1. Structure of the Shared Library

Inspect the three modular Groovy functions in the library:

// vars/buildApp.groovy:
def call() {
    // -B: Batch mode (disables download animation to keep Jenkins console clean)
    // clean package: Cleans old artifacts and packages compiled JAR
    sh 'mvn -B clean package'
}

// vars/buildImage.groovy:
def call(String imageTag) {
    // -t <tag>: Tags image with repo/name:build_id
    sh "docker build -t ${imageTag} Jenkins/Lab21/DemoApp"
    // --severity HIGH,CRITICAL: Focuses scan on high-risk CVEs
    // --exit-code 0           : Runs security scan without failing build
    sh "trivy image --severity HIGH,CRITICAL --exit-code 0 ${imageTag}"
    withCredentials([usernamePassword(credentialsId: 'dockerhub',
                                      usernameVariable: 'U',
                                      passwordVariable: 'P')]) {
        // --password-stdin: Safely passes password via stdin
        sh "echo \$P | docker login -u \$U --password-stdin"
        sh "docker push ${imageTag}"
    }
    // rmi: Deletes local image copy to reclaim worker disk space
    sh "docker rmi ${imageTag}"
}

// vars/deployOnK8s.groovy:
def call(String imageTag) {
    withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
        // -i: In-place edit of Kubernetes manifest with target image
        sh "sed -i 's|image: .*|image: ${imageTag}|g' Jenkins/Lab21/k8s.yaml"
        // --kubeconfig: Authenticates via scoped ServiceAccount token
        // -f          : Path to manifest to apply
        sh "kubectl --kubeconfig \$KUBECONFIG apply -f Jenkins/Lab21/k8s.yaml"
    }
}
2. The Refactored Clean Jenkinsfile
@Library('ivolve-lib') _

pipeline {
    agent any

    stages {
        stage('Build app') {
            agent {
                docker {
                    image 'maven:3.9-eclipse-temurin-17'
                    // -v: Mounts persistent named volume caching ~/.m2 repository across agent container lifecycles
                    args '-v ivolve-maven-repo:/root/.m2'  // Cache downloads
                    reuseNode true                        // Stay in the same folder!
                }
            }
            steps {
                dir('Jenkins/Lab21/DemoApp') {
                    buildApp()                            // One clean line!
                }
            }
        }

        stage('Build and push image') {
            steps {
                script {
                    buildImage("abdalrahmanx/ivolve-demoapp:${BUILD_NUMBER}")
                }
            }
        }

        stage('Deploy to Kubernetes') {
            steps {
                script {
                    deployOnK8s("abdalrahmanx/ivolve-demoapp:${BUILD_NUMBER}")
                }
            }
        }
    }
}

Tips

  • The reuseNode true Gotcha: When you run a Docker agent inside a stage, Jenkins creates a separate folder (like demoapp@2). If you build your JAR there and switch back to the controller, the controller looks in demoapp and can't find the JAR! Setting reuseNode true forces the Docker agent to share the exact same workspace.
Lab 23 GitOps

🐙 Implementing a GitOps Workflow with Jenkins and Argo CD

Objective: Upgrade deployment architecture to pull-based GitOps: Jenkins builds images and commits YAML updates to GitHub, while Argo CD continuously reconciles live cluster state with Git.

Argo CDGitOpsDeclarative CDSelf-Healing
📋 Lab Prompt & Requirements (Slide Task)
  • Install Argo CD in your Kubernetes cluster.
  • Access the Argo CD UI and log in successfully.
  • Connect Argo CD to your GitHub repository.
  • Create an Argo CD Application named ivolve.
  • Configure the application to monitor the appropriate GitHub repository and manifest directory.
  • Configure automatic synchronization so that Argo CD automatically applies changes detected in Git.
  • Modify the DeployOnK8s Jenkins role to Push new update files into Github repo after edit the deployment file.
  • Trigger the Jenkins pipeline to build and publish a new application image.
  • Confirm that Argo CD detects the changes and synchronizes the application.

The Core Idea & Concepts

In Lab 21, Jenkins connected to Kubernetes and executed kubectl apply directly. That is the traditional Push Model. While functional, modern cloud-native architectures transition to GitOps for two key reasons:

  • Credential Decoupling: The CI runner does not hold cluster admin credentials. If CI is compromised, cluster access remains protected.
  • Drift Prevention: If someone manually modifies or deletes a workload in the cluster, push-based CI never notices. GitOps continuously reconciles cluster state against Git.

The GitOps Pull Loop:

  • Git is the Single Source of Truth: Workload manifests in Git define exactly what should run in production.
  • In-Cluster Controller: Argo CD runs inside Kubernetes, polls Git, and applies diffs automatically.
  • Clean Hand-Off: Jenkins builds and publishes the container image, updates the image tag in Jenkins/Lab21/k8s.yaml, and executes git push. Argo CD detects the commit and rolls out the change.
  • Self-Healing: If an engineer manually alters a pod or deployment via kubectl, Argo CD detects the drift and immediately restores the manifest from Git.

Architecture & Workflow Flowchart

1. CI Pipeline Jenkins Builds image & commits YAML
➔ git push ➔
2. Single Source GitHub Repo k8s.yaml updated
➔ Polls & Syncs ➔
3. In-Cluster CD Argo CD Automated & Self-Healing

Step-by-Step Solution & Commands

1. Install Argo CD into the Cluster
# Create dedicated namespace for Argo CD components:
kubectl create namespace argocd

# Apply official Argo CD manifests:
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

# Wait until all Argo CD control plane pods are running:
kubectl wait --for=condition=Ready pods --all -n argocd --timeout=300s
2. Access UI and Retrieve Initial Admin Password
# Forward Argo CD API server to local port 8081:
#   8081:443 : Maps local port 8081 to container HTTPS port 443
kubectl port-forward svc/argocd-server -n argocd 8081:443 &

# Extract and decode initial admin password:
#   -o jsonpath : Retrieves password field from Secret
#   base64 -d   : Decodes base64 payload to plaintext
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d
echo ""

Log in at https://localhost:8081 using username admin and the decoded password.

3. Connect GitHub Repository
# Register repository with Argo CD CLI (public repo requires no auth):
#   repo add : Registers source repository URL
argocd repo add https://github.com/abdalrahmanx9/Ivolve-labs.git
4. Deploy the Argo CD Application Manifest

Define the declarative application targeting the manifests in Jenkins/Lab21:

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: ivolve
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/abdalrahmanx9/Ivolve-labs.git
    targetRevision: main
    path: Jenkins/Lab21
  destination:
    server: https://kubernetes.default.svc
    namespace: ivolve
  syncPolicy:
    automated:
      selfHeal: true
# Apply application definition:
kubectl apply -f ArgoCD/Lab23/application.yaml
5. Update Jenkins Deploy Step to Push to Git

Update Jenkins/Lab22/shared-library/vars/deployOnK8s.groovy to edit the manifest and commit back to GitHub:

def call(String image) {
    sh "sed -i 's|image: abdalrahmanx/ivolve-demoapp:.*|image: ${image}|' Jenkins/Lab21/k8s.yaml"
    sh "grep image: Jenkins/Lab21/k8s.yaml"
    withCredentials([usernamePassword(credentialsId: 'github-push',
            usernameVariable: 'USR', passwordVariable: 'PSW')]) {
        sh 'git config user.email "jenkins@ivolve.local"'
        sh 'git config user.name "jenkins"'
        sh "git add Jenkins/Lab21/k8s.yaml"
        sh "git commit -m 'ci: deploy demoapp ${image}' || echo 'nothing to commit'"
        sh 'git push https://$USR:$PSW@github.com/abdalrahmanx9/Ivolve-labs.git HEAD:main'
    }
}
6. Verify Synchronization and Self-Healing
# Check Argo CD sync status:
argocd app get ivolve

# Verify live deployment reflects the committed image:
kubectl get deployment demoapp -n ivolve -o jsonpath='{.spec.template.spec.containers[0].image}'
Sync Status: Synced to (42305ff) Health Status: Healthy abdalrahmanx/ivolve-demoapp:1

Tips

  • No Cluster Credentials in CI: The kubectl apply step is removed from Jenkins entirely. Jenkins only needs Git write permissions, isolating cluster control plane credentials from the CI runner.
  • Stale Committed Tags: Ensure the initial committed manifest in Git references a valid, pushable image tag before activating automated sync, preventing ImagePullBackOff loops.
Lab 24 Ansible

🅰️ Initial Ansible Configuration and Ad-Hoc Execution

Objective: Establish agentless management across target nodes using passwordless SSH key authentication and run ad-hoc command modules.

AnsibleAgentlessSSH KeysAd-Hoc Commands
📋 Lab Prompt & Requirements (Slide Task)
  • Install and configure Ansible on control node.
  • Generate new key on control node.
  • Transfer the public key into managed node using ssh-copy-id command.
  • Create inventory of a managed node.
  • Perform ad-hoc command to install Docker.

The Core Idea & Concepts

Unlike centralized management systems requiring background daemon agents (like Puppet or Chef), Ansible operates agentlessly over OpenSSH with Python:

  • Control Node vs. Managed Node: The control node hosts Ansible and private keys; managed nodes require only SSH and Python 3.
  • Passwordless Authentication: Public keys are distributed to ~/.ssh/authorized_keys on managed nodes, enabling secure, unattended remote automation.
  • Static Inventory: Defines the hostnames, IP addresses, groups, and connection credentials for target servers.
  • Ad-Hoc Execution: One-liner commands using built-in modules (command, shell, apt) for rapid queries and tasks without writing full playbooks.

Architecture & Workflow Flowchart

Control Node Ansible CLI Private SSH Key
➔ Port 22 SSH (Agentless) ➔
Target Inventory inventory managed1 ansible_user=root
➔ Ad-Hoc Module ➔
Managed Node Docker Engine Installed & Verified

Step-by-Step Solution & Commands

1. Bootstrap Lab Containers

Deploy a lightweight control and managed node pair on a local Docker bridge network:

# Create isolated bridge network:
docker network create ansible-net

# Start managed target node (Ubuntu 24.04 with OpenSSH):
docker run -d --name managed1 --hostname managed1 --network ansible-net   --privileged -e DEBIAN_FRONTEND=noninteractive ubuntu:24.04   sh -c "apt-get update -qq && apt-get install -y -qq openssh-server openssh-client >/dev/null     && mkdir -p /run/sshd     && echo 'root:lab123' | chpasswd     && printf 'PermitRootLogin yes\n' > /etc/ssh/sshd_config.d/root.conf     && /usr/sbin/sshd && sleep infinity"

# Start Ansible control node:
docker run -d --name control --hostname control --network ansible-net   python:3.12-slim   sh -c "apt-get update -qq && apt-get install -y -qq openssh-client sshpass >/dev/null     && pip install --quiet ansible && sleep infinity"
2. Generate and Distribute SSH Keys
# Inside the control container, generate 2048-bit RSA key pair:
#   -t rsa  : Key type algorithm
#   -b 2048 : Key length in bits
#   -N ''   : Empty passphrase for unattended automation
#   -f <path> : Key file path
ssh-keygen -t rsa -b 2048 -N '' -f ~/.ssh/id_rsa

# Copy public key to managed node using sshpass for initial auth:
#   -o StrictHostKeyChecking=no : Automatically accepts new host keys
sshpass -p lab123 ssh-copy-id -o StrictHostKeyChecking=no root@managed1
3. Configure Inventory
# Define managed host in /ansible/inventory:
managed1 ansible_user=root
4. Execute Ad-Hoc Commands
# Connectivity check:
#   -i <path> : Specifies inventory file
#   -m command : Uses command module
#   -a <args>  : Arguments passed to module
ansible all -i inventory -m command -a hostname

# Install Docker engine via shell module:
ansible all -i inventory -m shell -a 'apt-get update -qq && apt-get install -y docker.io'

# Verify Docker version:
ansible all -i inventory -m command -a 'docker --version'
managed1 | CHANGED | rc=0 >> Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2

Tips

  • SSH Root Login Setting: Modern Ubuntu installations default to PermitRootLogin prohibit-password, which rejects initial password authentication during key transfer. Adding PermitRootLogin yes in /etc/ssh/sshd_config.d/ enables the initial ssh-copy-id handshake.
Lab 25 Ansible

📦 Automated Tooling Playbook (Docker, Kubectl, Jenkins)

Objective: Author an idempotent multi-task Ansible playbook installing container runtime, Java runtime, Jenkins CI server, and Kubernetes client tools.

PlaybooksYAMLIdempotencyAPT Repository
📋 Lab Prompt & Requirements (Slide Task)
  • Write a playbook to install Docker, Kubectl, and Jenkins on the managed node.
  • Configure official repository keys and sources for Jenkins and Kubernetes.
  • Execute the playbook and ensure idempotency across runs.
  • Verify installed binaries on the target node.

The Core Idea & Concepts

Playbooks are YAML files describing the state target servers should be in. Each play defines target hosts (hosts: all), privilege escalation (become: true), and an ordered list of tasks:

  • Idempotency: Tasks only make changes if the system isn't already in the desired state. If docker.io is already installed, Ansible reports ok instead of changed. A clean second run always returns changed=0.
  • Keyring Management: Modern Debian and Ubuntu deprecated apt-key add. Third-party repository keys must now be converted to binary format and saved under /usr/share/keyrings/, referenced with signed-by in the repo definition.

Architecture & Workflow Flowchart

Playbook site.yml Declarative Tasks
➔ ansible-playbook ➔
Package Engine APT + GPG Keyrings & Repositories
➔ Idempotent State ➔
Verified Tools Docker, K8s, Jenkins changed=0 on re-run

Step-by-Step Solution & Commands

1. Author the Playbook (site.yml)
---
# Target all hosts listed in inventory
- hosts: all
  # Sudo escalation so tasks can install system packages and write /usr/local/bin
  become: true
  # Collect host architecture, OS distribution, and network facts for module use
  gather_facts: true

  tasks:
    # --- TASK 1: DOCKER RUNTIME ---
    - name: install docker
      ansible.builtin.apt:
        # Standard Ubuntu/Debian Docker runtime and CLI package
        name: docker.io
        # Idempotent state: installs if missing, skips if already present
        state: present
        # Runs apt-get update first so fresh containers don't fail on missing indices
        update_cache: true

    # --- TASK 2: JENKINS DEPENDENCIES ---
    - name: install java and gnupg (jenkins dependencies)
      ansible.builtin.apt:
        name:
          # Jenkins 2.x requires Java 17+ (headless avoids pulling 300MB of GUI/X11 libraries)
          - openjdk-17-jre-headless
          # Needed for gpg binary to dearmor repository keys into binary format
          - gnupg
        # Ensures both packages are installed; skips if already satisfied
        state: present

    # --- TASK 3: JENKINS GPG REPOSITORY KEY ---
    # Fetch 2026 key — the historical 2023 key expired in March 2026 and causes apt NO_PUBKEY errors
    - name: add jenkins repository key
      ansible.builtin.get_url:
        # Official Jenkins stable signing key URL
        url: https://pkg.jenkins.io/debian-stable/jenkins.io-2026.key
        # Destination file for ASCII-armored key
        dest: /usr/share/keyrings/jenkins-keyring.asc
        # Standard read permissions for root and apt service accounts
        mode: "0644"
        # Overwrite destination file to replace expired keys
        force: true

    # --- TASK 4: DEARMOR KEYRING TO BINARY ---
    # APT signed-by expects binary OpenPGP (.gpg), not ASCII-armored (.asc)
    - name: dearmor the jenkins key
      # gpg --dearmor converts ASCII armor to binary; --yes overwrites without prompting
      ansible.builtin.command: "gpg --dearmor --yes -o /usr/share/keyrings/jenkins-keyring.gpg /usr/share/keyrings/jenkins-keyring.asc"
      args:
        # Idempotency guard: skips execution if binary file already exists (returns changed=0)
        creates: /usr/share/keyrings/jenkins-keyring.gpg

    # --- TASK 5: JENKINS APT REPOSITORY ---
    - name: add jenkins repository
      ansible.builtin.apt_repository:
        # signed-by restricts key trust exclusively to this repository, preventing apt-key poisoning
        repo: "deb [signed-by=/usr/share/keyrings/jenkins-keyring.gpg] https://pkg.jenkins.io/debian-stable binary/"
        # Adds repository entry if not already present
        state: present
        # Writes entry to /etc/apt/sources.list.d/jenkins.list instead of main sources.list
        filename: jenkins

    # --- TASK 6: JENKINS SERVER PACKAGE ---
    - name: install jenkins
      ansible.builtin.apt:
        # Package pulled from the newly registered Jenkins APT repository
        name: jenkins
        # Installs package and registers systemd/init service
        state: present

    # --- TASK 7: STANDALONE KUBECTL BINARY ---
    # Fetch standalone binary directly into PATH, avoiding the overhead of the Google cloud apt repo
    - name: install kubectl
      ansible.builtin.get_url:
        # Official Kubernetes release binary URL for amd64 Linux
        url: https://dl.k8s.io/release/v1.33.13/bin/linux/amd64/kubectl
        # Placed directly in system executable directory accessible by all users
        dest: /usr/local/bin/kubectl
        # rwxr-xr-x: grants execute permissions so non-root users can run kubectl
        mode: "0755"
2. Run Playbook and Verify Idempotency
# Run playbook against managed inventory:
#   -i inventory : Targets defined inventory
ansible-playbook -i inventory site.yml

# Re-run playbook to confirm idempotency (changed=0):
ansible-playbook -i inventory site.yml
3. Verify Installed Versions
# Query versions of all deployed tooling:
ansible all -i inventory -m shell -a 'docker --version && kubectl version --client && dpkg -l jenkins | tail -1'
Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2 Client Version: v1.33.13 ii jenkins 2.580.2 all

Tips

  • Expired Jenkins GPG Key: The historical jenkins.io-2023.key expired in March 2026, causing APT to fail with NO_PUBKEY 7198F4B714ABFC68. Always target the active jenkins.io-2026.key with force: true in get_url.
  • GPG Dearmor: APT expects the binary OpenPGP format for keyrings specified via signed-by. Using gpg --dearmor converts the ASCII armored key into valid binary format.
Lab 26 Ansible

🧩 Structured Configuration with Modular Ansible Roles

Objective: Refactor monolithic playbooks into reusable, modular Ansible Roles adhering to standard directory hierarchies.

Ansible RolesModularityReusabilityClean Architecture
📋 Lab Prompt & Requirements (Slide Task)
  • Structure configuration management using modular Ansible Roles.
  • Create separate roles for Docker, Kubectl, and Jenkins.
  • Define a master site.yml playbook executing all roles in order.
  • Verify role execution and ensure changed=0 on repeated runs.

The Core Idea & Concepts

When a single playbook grows, splitting it into Roles keeps tasks organized by tool. Each role lives in its own directory (e.g. roles/docker/tasks/main.yml). The master playbook simply declares which roles to run on which hosts, executing them in listed order.

Architecture & Workflow Flowchart

Orchestrator site.yml Calls Roles in Order
➔ Executes ➔
Modular Roles roles/ docker | kubectl | jenkins
➔ Converges ➔
Target State PLAY RECAP ok=8 changed=0

Step-by-Step Solution & Commands

1. Directory Structure
Lab26/
├── site.yml
└── roles/
    ├── docker/tasks/main.yml
    ├── kubectl/tasks/main.yml
    └── jenkins/tasks/main.yml
2. Define Individual Roles

roles/docker/tasks/main.yml:

---
- name: install docker
  ansible.builtin.apt:
    # Standard Ubuntu/Debian Docker runtime package
    name: docker.io
    # Idempotent state: installs if missing, skips if already present
    state: present
    # Refreshes package cache before installing so lookups don't fail
    update_cache: true

roles/kubectl/tasks/main.yml:

---
# Download standalone binary directly into PATH, avoiding apt repo overhead
- name: install kubectl
  ansible.builtin.get_url:
    # Official v1.33.13 Linux amd64 binary URL
    url: https://dl.k8s.io/release/v1.33.13/bin/linux/amd64/kubectl
    # Target directory in standard system $PATH
    dest: /usr/local/bin/kubectl
    # rwxr-xr-x permissions allowing all users to execute kubectl
    mode: "0755"

roles/jenkins/tasks/main.yml:

---
# Prerequisites: Headless Java 17 runtime for Jenkins + gnupg for key conversion
- name: install java and gnupg
  ansible.builtin.apt:
    name:
      - openjdk-17-jre-headless  # Java runtime without GUI overhead
      - gnupg                    # Provides gpg binary for dearmoring
    state: present

# Download official signing key (2026 key; 2023 key expired in March 2026)
- name: add jenkins repository key
  ansible.builtin.get_url:
    url: https://pkg.jenkins.io/debian-stable/jenkins.io-2026.key
    dest: /usr/share/keyrings/jenkins-keyring.asc
    mode: "0644"   # Standard read permissions for apt
    force: true    # Overwrite if key exists to ensure it's up to date

# Convert ASCII key to binary format required by Debian signed-by
- name: dearmor the jenkins key
  ansible.builtin.command: "gpg --dearmor --yes -o /usr/share/keyrings/jenkins-keyring.gpg /usr/share/keyrings/jenkins-keyring.asc"
  args:
    # Idempotency guard: skips running gpg if binary keyring already exists
    creates: /usr/share/keyrings/jenkins-keyring.gpg

# Register repository with scoped key verification
- name: add jenkins repository
  ansible.builtin.apt_repository:
    # signed-by limits key trust strictly to this repository URL
    repo: "deb [signed-by=/usr/share/keyrings/jenkins-keyring.gpg] https://pkg.jenkins.io/debian-stable binary/"
    state: present
    # Writes to /etc/apt/sources.list.d/jenkins.list
    filename: jenkins

- name: install jenkins
  ansible.builtin.apt:
    name: jenkins   # Package from newly added Jenkins apt source
    state: present  # Installs package and registers systemd service
3. Master Orchestration Playbook (site.yml)
---
# Master playbook orchestrating modular roles
- hosts: all
  # Sudo escalation so roles can install packages and write /usr/local/bin
  become: true
  roles:
    # Executed sequentially from top to bottom:
    - docker   # Role 1: Installs docker container runtime
    - kubectl  # Role 2: Installs kubectl client binary
    - jenkins  # Role 3: Installs Java 17, Jenkins apt repo, and server
4. Execute and Verify Idempotency
# Run role-based configuration:
ansible-playbook -i inventory site.yml
PLAY RECAP ********************************************************************* managed1 : ok=8 changed=0 unreachable=0 failed=0

Tips

  • Execution Order: Roles listed under roles: in the playbook execute strictly in top-to-bottom sequence before tasks defined in the play.
Lab 27 Ansible

🔐 Securing Sensitive Data with Ansible Vault (MySQL Role)

Objective: Deploy a MySQL database role configuring schemas and user grants while protecting credentials using AES-256 Ansible Vault encryption.

Ansible VaultAES-256Database AutomationMySQL
📋 Lab Prompt & Requirements (Slide Task)
  • Create a MySQL role that installs mysql-server and python3-pymysql.
  • Create database ivolve and database user ivolveuser.
  • Secure sensitive credentials using Ansible Vault (AES-256 encryption).
  • Run playbook with --vault-password-file and verify database connectivity.

The Core Idea & Concepts

Storing plaintext passwords in Git is a security risk. Ansible Vault encrypts variable files at rest using AES-256. The encrypted file is safe to commit; only runners with the password file (--vault-password-file) can decrypt the values in memory during playbook execution.

Architecture & Workflow Flowchart

Encrypted Secret vault.yml $ANSIBLE_VAULT;1.1;AES256
➔ --vault-password-file ➔
MySQL Role tasks/main.yml community.mysql modules
➔ Grants ivolveuser ➔
Verified DB ivolve Database SHOW DATABASES ok

Step-by-Step Solution & Commands

1. Create Encrypted Vault File
# Create group_vars directory:
mkdir -p group_vars/all

# Create and encrypt the vault file:
ansible-vault create group_vars/all/vault.yml

Define the database password inside the encrypted file:

# AES-256 encrypted string created with ansible-vault
# Decrypted in memory at runtime via --vault-password-file; never written plaintext to disk
vault_mysql_password: "SuperSecretPassword123!"
2. Author the MySQL Role (roles/mysql/tasks/main.yml)
---
# python3-pymysql is required on the target node so Ansible community.mysql modules can run
- name: install mysql server and pymysql
  ansible.builtin.apt:
    name:
      - mysql-server     # MySQL database server daemon
      - python3-pymysql  # Python MySQL driver required by community.mysql modules
    state: present
    update_cache: true   # Refresh package index before installation

# Sysvinit service start: needed because Docker lab containers don't run systemd PID 1
- name: start mysql
  ansible.builtin.command: service mysql start
  # changed_when: false prevents marking this task as changed on every run (preserves idempotency)
  changed_when: false

# Creates schema; connects locally as root via Unix socket without password
- name: create the ivolve database
  community.mysql.mysql_db:
    name: ivolve
    state: present       # Idempotent: creates database only if it does not exist
    login_unix_socket: /var/run/mysqld/mysqld.sock  # Auth socket authentication for local root

# Provisions database user with credentials resolved from Ansible Vault
- name: create ivolveuser with all privileges on ivolve
  community.mysql.mysql_user:
    name: ivolveuser
    host: "%"            # Wildcard host: allows connections from any IP/container
    password: "{{ vault_mysql_password }}"  # Variable decrypted in-memory from group_vars/all/vault.yml
    priv: "ivolve.*:ALL" # Restricts full permissions strictly to ivolve database tables
    state: present       # Idempotent: creates user or updates password if changed
    login_unix_socket: /var/run/mysqld/mysqld.sock

# Verification task: connects as the newly created user using the vault password
- name: validate - connect as ivolveuser and list databases
  community.mysql.mysql_info:
    login_user: ivolveuser
    login_password: "{{ vault_mysql_password }}"
    login_host: 127.0.0.1  # TCP loopback connection to test remote grant
    filter: databases      # Restricts query to database list
  register: dbcheck        # Captures module output dictionary into variable
  changed_when: false      # Read-only query; never alters database state

# Print visible databases to confirm user grants are working
- name: show validation result
  ansible.builtin.debug:
    msg: "databases visible to ivolveuser: {{ dbcheck.databases | list }}"
3. Playbook Configuration (site.yml)
---
- hosts: all
  become: true
  vars_files:
    # Loads AES-256 encrypted variables into playbook scope
    - group_vars/all/vault.yml
  roles:
    # Runs MySQL provisioning role with vault variables available
    - mysql
4. Execute Playbook with Vault Credentials
# Run playbook supplying vault password file:
#   --vault-password-file : Path to file containing decryption key
ansible-playbook -i inventory site.yml --vault-password-file .vault-pass
5. Verify Connectivity as the New User
# Connect directly using ivolveuser credentials:
mysql -u ivolveuser -p -h 127.0.0.1 -e "SHOW DATABASES;"
Database information_schema ivolve performance_schema

Tips

  • Python MySQL Dependency: The community.mysql.mysql_db and mysql_user modules require python3-pymysql to be installed on the managed target node to interact directly with MySQL sockets.
  • Vault Password Protection: Never commit the .vault-pass file to Git. Add .vault-pass to your .gitignore and restrict file permissions with chmod 600 .vault-pass.
Lab 28 Ansible

☁️ Automated Host Discovery with AWS EC2 Dynamic Inventory

Objective: Implement cloud-native host discovery using the amazon.aws.aws_ec2 dynamic inventory plugin to manage AWS EC2 instances filtered by tags.

Dynamic InventoryAWS EC2amazon.awsCloud Automation
📋 Lab Prompt & Requirements (Slide Task)
  • Configure AWS dynamic inventory using amazon.aws.aws_ec2 plugin.
  • Filter instances dynamically tagged Server=ivolve.
  • Execute Ansible ad-hoc commands and playbooks against dynamically discovered cloud instances.
  • Terminate cloud instances cleanly after verification.

The Core Idea & Concepts

In cloud environments, static IP inventories don't scale because servers launch, stop, or change IPs dynamically. Dynamic Inventory plugins (like amazon.aws.aws_ec2) query the AWS API at runtime, discover active instances matching specific tags (e.g. Server=ivolve), and hand their public IPs directly to Ansible.

Architecture & Workflow Flowchart

Plugin aws_ec2.yml amazon.aws plugin
➔ AWS API Call ➔
AWS Cloud Tag: Server=ivolve Discovers Running IPs
➔ Dynamic Inventory ➔
Playbook Run ec2.yml Docker Installed on Cloud

Step-by-Step Solution & Commands

1. Prerequisites: AWS SDK and Ansible Collection
# Install Python AWS SDK:
pip install boto3 botocore

# Install official Ansible AWS collection:
ansible-galaxy collection install amazon.aws
2. Launch EC2 Instance with Target Tag
# Launch Amazon Linux 2023 instance tagged Server=ivolve:
# (Ensure security group allows port 22 SSH from your IP)
aws ec2 run-instances   --image-id ami-0084a47cc718c111a   --count 1   --instance-type t3.micro   --key-name nti-devops-key   --security-group-ids sg-0eae4711e8c34c6eb   --tag-specifications 'ResourceType=instance,Tags=[{Key=Server,Value=ivolve}]'
3. Configure Dynamic Inventory (aws_ec2.yml)

Note: The filename must end with aws_ec2.yml or aws_ec2.yaml.

# AWS EC2 dynamic inventory configuration. Filename must end with aws_ec2.yml or aws_ec2.yaml.
plugin: amazon.aws.aws_ec2
regions:
  # AWS region where target EC2 instances are provisioned
  - eu-central-1
filters:
  # Filter: only discover instances tagged Server=ivolve, ignoring other VPC workloads
  tag:Server: ivolve
  # Filter: only target active, running instances (ignores stopped/terminated nodes)
  instance-state-name: running
hostnames:
  # Use public IPv4 address as inventory_hostname so Ansible dials over SSH
  - ip-address
vars:
  # Default SSH username for Amazon Linux 2023 AMIs
  ansible_user: ec2-user
  # SSH private key matching the AWS Key Pair used at launch
  ansible_ssh_private_key_file: /root/.ssh/nti-devops-key.pem
  # Explicit Python 3 interpreter path on Amazon Linux 2023
  ansible_python_interpreter: /usr/bin/python3
4. Query Live Cloud Inventory
# Test discovery graph from AWS API:
#   --graph : Outputs discovered host hierarchy
ansible-inventory -i aws_ec2.yml --graph
@all: |--@ungrouped: |--@aws_ec2: | |--3.75.247.89
5. Execute Playbook Against Discovered Cloud Instances (ec2.yml)
---
# Play targets all dynamically discovered EC2 instances from aws_ec2.yml
- hosts: all
  # Sudo escalation so dnf and systemd commands can run as root
  become: true
  tasks:
    # Amazon Linux 2023 uses dnf instead of yum or apt
    - name: install docker
      ansible.builtin.dnf:
        name: docker     # Official Docker package in Amazon Linux 2023 repos
        state: present   # Idempotent: ensures package is installed

    # Service configuration via systemd
    - name: start and enable docker
      ansible.builtin.service:
        name: docker     # Docker systemd service unit
        state: started   # Ensures daemon is running (starts if stopped)
        enabled: true    # Configures systemd to start Docker on system reboot

    # Verification: check installed Docker version on cloud instance
    - name: docker version
      ansible.builtin.command: docker --version
      register: dv         # Captures command stdout, stderr, and return code
      changed_when: false  # Read-only check: skips marking task as changed

    # Print output with hostname to confirm successful execution across cloud nodes
    - name: show result
      ansible.builtin.debug:
        msg: "{{ ansible_hostname }} -> {{ dv.stdout }}"
# Run playbook against discovered instances:
ansible-playbook -i aws_ec2.yml ec2.yml
ok: [3.75.247.89] => { "msg": "ip-172-31-21-200 -> Docker version 25.0.14, build 0bab007" } PLAY RECAP ********************************************************************* 3.75.247.89 : ok=5 changed=2 unreachable=0 failed=0
6. Terminate Cloud Resources
# Clean up EC2 instance:
aws ec2 terminate-instances --instance-ids <INSTANCE_ID>

Tips

  • Naming Requirement: The inventory configuration file must end in aws_ec2.yml or aws_ec2.yaml. Ansible uses the filename pattern to identify and invoke the dynamic inventory plugin.
  • Connection Variables: In plugin inventories, define connection variables (like ansible_user and private key path) directly within the plugin's vars: block so they reliably attach to dynamically discovered hosts.
Resumed reading