#!/usr/bin/env bash # Ensure the helper image is built locally. If missing, build from the # Dockerfile adjacent to this script (same `contws` directory). script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" IMAGE_NAME="inftools-cn:latest" if ! docker image inspect "$IMAGE_NAME" >/dev/null 2>&1; then echo "Docker image $IMAGE_NAME not found. Building from $script_dir/Dockerfile..." docker build -t "$IMAGE_NAME" -f "$script_dir/Dockerfile" "$script_dir" || { echo "Failed to build Docker image $IMAGE_NAME" >&2 exit 1 } fi # Check if the Docker network 'student-net' exists, if not, create it if ! docker network inspect student-net >/dev/null 2>&1; then echo "Docker network 'student-net' not found. Creating it..." docker network create student-net || { echo "Failed to create Docker network 'student-net'" >&2 exit 1 } fi # docker ps | grep mycluster | wc -l # 2 if docker ps | grep -q mycluster; then echo "Cluster already exists. Skipping creation." docker run --rm -it \ --network student-net \ -v /var/run/docker.sock:/var/run/docker.sock \ -v mykube:/root/.kube \ $IMAGE_NAME bash exit 0 fi # create cluster # # Capture k3d output and extract the load-balancer node name. # Example line in output: "INFO[0005] Starting node 'k3d-mycluster-serverlb'" # tmpfile=$(mktemp) # Stream docker output live to terminal and save it to a temp file for parsing docker run --rm \ --network student-net \ -v /var/run/docker.sock:/var/run/docker.sock \ -v mykube:/root/.kube \ $IMAGE_NAME k3d cluster create mycluster --network student-net 2>&1 | tee "$tmpfile" # Read captured output into a variable for parsing output=$(cat "$tmpfile") rm -f "$tmpfile" # Prefer the node name that contains 'serverlb' (most likely the LB), # otherwise fall back to the last "Starting node '..." match. # First try to find a line that includes 'serverlb'. LB_NODE=$(printf "%s" "$output" | grep "Starting node" | grep -E "serverlb" | sed -n "s/.*Starting node '\\([^']*\\)'.*/\\1/p" | head -n1 || true) if [ -z "$LB_NODE" ]; then # Fallback: take the last Starting node match (in case serverlb isn't present) LB_NODE=$(printf "%s" "$output" | sed -n "s/.*Starting node '\\([^']*\\)'.*/\\1/p" | tail -n1) fi if [ -n "$LB_NODE" ]; then echo "Load balancer node: $LB_NODE" export LB_NODE else echo "Warning: could not parse load balancer node from k3d output" >&2 fi # edit kubeconfig to use load-balancer node IP # server: https://0.0.0.0:40115 # needs to be changed to be sed -i 's/:34791/:6443/g' ~/.kube/config # 0.0.0.0:40115 -> :6443 docker run --rm \ --network student-net \ -v /var/run/docker.sock:/var/run/docker.sock \ -v mykube:/root/.kube \ $IMAGE_NAME sed -i "s/0.0.0.0:[0-9]*/${LB_NODE}:6443/g" /root/.kube/config