The hard way · Part 1

Network and machines

Three machines, and no way in from the internet.

Three machines on a private network with no way in from the internet. You reach them through AWS Session Manager.

1Create the files

Everything lives in one folder. Open each file below and use its copy button: it creates the file for you.

$ mkdir -p ~/k8s-hard-way/{scripts,remote,manifests} && cd ~/k8s-hard-way
config.env (22 lines)
$ cat > config.env <<'SCRIPT_EOF'
# Settings for the whole guide. Sourced by every script through lib.sh.
# Edit before you start; do not edit halfway through.

PROJECT=k8s-hard-way             # tag on every resource: it is how teardown finds them
REGION=${AWS_REGION:-us-west-2}
INSTANCE_TYPE=t3.small           # 2 vCPU, 2 GiB: enough for etcd + API server, or a worker
DISK_GB=20
SSH_USER=ec2-user                # Amazon Linux 2023

# Network plan. Three separate address ranges, which must not overlap:
VPC_CIDR=10.240.0.0/24           # the machines
POD_CLUSTER_CIDR=10.200.0.0/16   # all Pods; each worker gets one /24 slice of it
SERVICE_CIDR=10.32.0.0/24        # virtual addresses of Services (kube-proxy rules, no interface)
KUBERNETES_SERVICE_IP=10.32.0.1  # first Service address: the API server, seen from inside the cluster
CLUSTER_DNS_IP=10.32.0.10        # where the DNS add-on will live

# Fixed private IPs, so certificates and kubeconfigs can name them in advance.
SERVER_IP=10.240.0.10
NODE0_IP=10.240.0.20
NODE1_IP=10.240.0.21
NODE0_POD_CIDR=10.200.0.0/24
NODE1_POD_CIDR=10.200.1.0/24
SCRIPT_EOF
versions.env (9 lines)
$ cat > versions.env <<'SCRIPT_EOF'
# Versions pinned for this guide (latest stable when it was written, November 2026).
# Change them here and every script follows. The scripts verify the Kubernetes
# binaries against the sha256 files published next to them.
K8S_VERSION=v1.37.2
ETCD_VERSION=v3.7.4
CONTAINERD_VERSION=2.4.2        # no leading "v" in the tarball name
RUNC_VERSION=v1.5.3
CNI_PLUGINS_VERSION=v1.10.0
COREDNS_VERSION=v1.12.1
SCRIPT_EOF
lib.sh (65 lines)
$ cat > lib.sh <<'SCRIPT_EOF'
#!/usr/bin/env bash
# Shared helpers. Every script starts with:  source "$(dirname "$0")/../lib.sh"
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STATE="$ROOT/.state"                  # generated files live here (git-ignored)
mkdir -p "$STATE"

# shellcheck source=config.env
source "$ROOT/config.env"
# shellcheck source=versions.env
source "$ROOT/versions.env"

export AWS_REGION="$REGION"
export AWS_PAGER=""                   # never open a pager inside a script

log()  { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m!!\033[0m  %s\n' "$*" >&2; }
die()  { printf '\033[1;31mxx\033[0m  %s\n' "$*" >&2; exit 1; }

# --- state: a tiny key=value file remembering the IDs of what we created ----------------
# State is what lets later scripts, and teardown, find resources. Teardown also searches
# by tag, so a lost state file does not leave anything behind.
STATE_FILE="$STATE/ids.env"
touch "$STATE_FILE"
state_set() { sed -i "/^$1=/d" "$STATE_FILE"; echo "$1=$2" >> "$STATE_FILE"; }
state_get() { grep "^$1=" "$STATE_FILE" | tail -1 | cut -d= -f2- || true; }
state_need() { local v; v="$(state_get "$1")"; [ -n "$v" ] || die "$1 is not set. Run the earlier scripts first."; echo "$v"; }

# --- tags: every taggable resource gets Project=<PROJECT> and a Name -------------------
tagspec() { echo "ResourceType=$1,Tags=[{Key=Project,Value=$PROJECT},{Key=Name,Value=$2}]"; }

# --- safety: show which account and region we are about to change, and ask ---------------
confirm_account() {
  local arn acct
  arn="$(aws sts get-caller-identity --query Arn --output text)"
  acct="$(aws sts get-caller-identity --query Account --output text)"
  echo "  account : $acct"
  echo "  identity: ${arn##*:}"
  echo "  region  : $REGION"
  if [ "${ASSUME_YES:-no}" != yes ]; then
    read -r -p "Create or delete resources there? [y/N] " a
    [ "$a" = y ] || die "Cancelled."
  fi
}

# --- reaching the machines: SSH tunnelled through SSM Session Manager ------------------
# The instances have no inbound rules at all. ssh_config (written by 20-compute.sh) makes
# `ssh` start an SSM session as its transport.
SSH_OPTS=(-F "$STATE/ssh_config" -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$STATE/known_hosts" -o LogLevel=ERROR)
kssh() { ssh "${SSH_OPTS[@]}" "$@"; }
kscp() { scp "${SSH_OPTS[@]}" "$@"; }

# run_remote HOST SCRIPT [VAR=value ...]: run a script from remote/ on a machine, as root
run_remote() {
  local host=$1 script=$2; shift 2
  kssh "$host" sudo env "$@" bash -s < "$ROOT/remote/$script"
}

# --- kubectl: use a copy that matches the cluster version -------------------------------
# kubectl may differ from the cluster by one minor version at most. 96-kubectl.sh downloads
# the exact version into .state/bin; before that, fall back to whatever is on your PATH.
KUBECTL="$STATE/bin/kubectl"; [ -x "$KUBECTL" ] || KUBECTL="$(command -v kubectl || true)"
# kc ARGS: kubectl as the cluster admin, through the tunnel (96-kubectl.sh start)
kc() { "$KUBECTL" --kubeconfig "$STATE/kubeconfigs/admin.kubeconfig" "$@"; }
SCRIPT_EOF
scripts/00-prereqs.sh (21 lines)
$ cat > scripts/00-prereqs.sh <<'SCRIPT_EOF'
#!/usr/bin/env bash
# 00 - check your machine has what the guide needs, and show where it will build.
# Changes nothing.
source "$(dirname "$0")/../lib.sh"

need() { command -v "$1" >/dev/null || die "$1 is missing: $2"; log "$1 ok"; }
need aws    "https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html"
need jq     "your package manager"
need openssl "your package manager"
need kubectl "https://kubernetes.io/docs/tasks/tools/"
need ssh    "your package manager"
need session-manager-plugin "https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html"
need curl   "your package manager"

log "who and where"
aws sts get-caller-identity --query '[Account,Arn]' --output text
echo "region: $REGION"

log "an Amazon Linux 2023 image exists in this region"
aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \
  --query Parameter.Value --output text
SCRIPT_EOF
scripts/10-network.sh (65 lines)
$ cat > scripts/10-network.sh <<'SCRIPT_EOF'
#!/usr/bin/env bash
# 10 - the network: VPC, one subnet, internet gateway, route table, security group,
#      and the IAM role that lets Session Manager (our way in) talk to the instances.
#
# Security design, on purpose:
#   * the security group allows traffic ONLY from itself and from the Pod range.
#     There is no rule for the internet at all: no SSH, no 6443.
#   * the instances still get public IPs, but only so they can DOWNLOAD (Kubernetes,
#     etcd, containerd) and reach the SSM service. Nothing can connect IN.
source "$(dirname "$0")/../lib.sh"
confirm_account

AZ="$(aws ec2 describe-availability-zones --filters Name=state,Values=available \
      --query 'AvailabilityZones[0].ZoneName' --output text)"
log "using availability zone $AZ"

log "VPC $VPC_CIDR"
VPC=$(aws ec2 create-vpc --cidr-block "$VPC_CIDR" \
      --tag-specifications "$(tagspec vpc "$PROJECT-vpc")" --query Vpc.VpcId --output text)
state_set VPC "$VPC"
# DNS names for instances; the SSM agent likes them
aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-support  '{"Value":true}'
aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-hostnames '{"Value":true}'

log "subnet (public IPs on launch, for downloads only)"
SUBNET=$(aws ec2 create-subnet --vpc-id "$VPC" --cidr-block "$VPC_CIDR" --availability-zone "$AZ" \
      --tag-specifications "$(tagspec subnet "$PROJECT-subnet")" --query Subnet.SubnetId --output text)
state_set SUBNET "$SUBNET"
aws ec2 modify-subnet-attribute --subnet-id "$SUBNET" --map-public-ip-on-launch

log "internet gateway and default route"
IGW=$(aws ec2 create-internet-gateway \
      --tag-specifications "$(tagspec internet-gateway "$PROJECT-igw")" --query InternetGateway.InternetGatewayId --output text)
state_set IGW "$IGW"
aws ec2 attach-internet-gateway --internet-gateway-id "$IGW" --vpc-id "$VPC"
RTB=$(aws ec2 create-route-table --vpc-id "$VPC" \
      --tag-specifications "$(tagspec route-table "$PROJECT-rtb")" --query RouteTable.RouteTableId --output text)
state_set RTB "$RTB"
aws ec2 create-route --route-table-id "$RTB" --destination-cidr-block 0.0.0.0/0 --gateway-id "$IGW" >/dev/null
aws ec2 associate-route-table --route-table-id "$RTB" --subnet-id "$SUBNET" >/dev/null

log "security group: members and Pods may talk to each other; nobody else"
SG=$(aws ec2 create-security-group --group-name "$PROJECT-sg" --description "$PROJECT: no inbound from the internet" \
      --vpc-id "$VPC" --tag-specifications "$(tagspec security-group "$PROJECT-sg")" --query GroupId --output text)
state_set SG "$SG"
# 1. anything in this group may send anything to anything in this group
aws ec2 authorize-security-group-ingress --group-id "$SG" --protocol -1 --source-group "$SG" >/dev/null
# 2. Pod traffic arrives with Pod IPs as its source, which are not "in the group"
aws ec2 authorize-security-group-ingress --group-id "$SG" --protocol -1 --cidr "$POD_CLUSTER_CIDR" >/dev/null

log "IAM role for Session Manager"
ROLE="$PROJECT-ssm"
aws iam create-role --role-name "$ROLE" --tags "Key=Project,Value=$PROJECT" \
  --assume-role-policy-document '{
    "Version":"2012-10-17",
    "Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}' >/dev/null
# AWS-managed policy: lets the agent on the instance register with Systems Manager. Nothing else.
aws iam attach-role-policy --role-name "$ROLE" --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
aws iam create-instance-profile --instance-profile-name "$ROLE" --tags "Key=Project,Value=$PROJECT" >/dev/null
aws iam add-role-to-instance-profile --instance-profile-name "$ROLE" --role-name "$ROLE"
aws iam wait instance-profile-exists --instance-profile-name "$ROLE"
sleep 10   # IAM is eventually consistent; run-instances can fail if we are too quick
state_set ROLE "$ROLE"

log "network ready: $VPC / $SUBNET / $SG"
SCRIPT_EOF
scripts/20-compute.sh (70 lines)
$ cat > scripts/20-compute.sh <<'SCRIPT_EOF'
#!/usr/bin/env bash
# 20 - three machines: server (control plane), node-0 and node-1 (workers).
#      No jumpbox: your own machine is the admin host, and reaches them over SSM.
source "$(dirname "$0")/../lib.sh"
confirm_account

SUBNET=$(state_need SUBNET); SG=$(state_need SG); ROLE=$(state_need ROLE)
AMI=$(aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \
      --query Parameter.Value --output text)
log "image $AMI (Amazon Linux 2023: has the SSM agent preinstalled)"

log "SSH key pair (local only; the private key never leaves $STATE/ssh)"
mkdir -p "$STATE/ssh"
[ -f "$STATE/ssh/key" ] || ssh-keygen -q -t ed25519 -N '' -C "$PROJECT" -f "$STATE/ssh/key"
aws ec2 import-key-pair --key-name "$PROJECT" --public-key-material "fileb://$STATE/ssh/key.pub" \
  --tag-specifications "$(tagspec key-pair "$PROJECT")" >/dev/null
state_set KEY "$PROJECT"

launch() {  # launch NAME PRIVATE_IP
  local name=$1 ip=$2 id
  # user-data runs once at first boot: the only thing we set is the hostname,
  # which Kubernetes uses as the node name.
  id=$(aws ec2 run-instances --image-id "$AMI" --instance-type "$INSTANCE_TYPE" \
      --subnet-id "$SUBNET" --private-ip-address "$ip" --security-group-ids "$SG" \
      --iam-instance-profile "Name=$ROLE" --key-name "$PROJECT" \
      --metadata-options 'HttpTokens=required,HttpEndpoint=enabled' \
      --block-device-mappings "DeviceName=/dev/xvda,Ebs={VolumeSize=$DISK_GB,VolumeType=gp3,Encrypted=true}" \
      --user-data "#!/bin/bash
hostnamectl set-hostname $name" \
      --tag-specifications "$(tagspec instance "$name")" "$(tagspec volume "$name")" \
      --query 'Instances[0].InstanceId' --output text)
  state_set "ID_$name" "$id"
  echo "$id"
}
log "launching server, node-0, node-1"
S=$(launch server "$SERVER_IP"); N0=$(launch node-0 "$NODE0_IP"); N1=$(launch node-1 "$NODE1_IP")
aws ec2 wait instance-running --instance-ids "$S" "$N0" "$N1"

# Pods will send packets whose source is a Pod IP, not the instance's own IP. By default EC2
# drops those. Turn that check off, or cross-node Pod traffic will silently disappear.
log "turning off the source/destination check"
for i in "$S" "$N0" "$N1"; do aws ec2 modify-instance-attribute --instance-id "$i" --no-source-dest-check; done

log "waiting for the SSM agent on each machine to register (about a minute)"
for i in "$S" "$N0" "$N1"; do
  for _ in $(seq 1 40); do
    st=$(aws ssm describe-instance-information --filters "Key=InstanceIds,Values=$i" \
         --query 'InstanceInformationList[0].PingStatus' --output text 2>/dev/null || true)
    [ "$st" = Online ] && break; sleep 5
  done
  [ "$st" = Online ] || die "$i never came online in Session Manager"
done

# `ssh server` will now start an SSM session as its transport: no inbound port needed.
log "writing $STATE/ssh_config"
{
  for pair in "server:$S" "node-0:$N0" "node-1:$N1"; do
    cat <<CFG
Host ${pair%%:*}
  HostName ${pair##*:}
  User $SSH_USER
  IdentityFile $STATE/ssh/key
  IdentitiesOnly yes
  ProxyCommand aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=%p --region $REGION
CFG
  done
} > "$STATE/ssh_config"

log "test: ssh to each machine"
for h in server node-0 node-1; do echo -n "$h: "; kssh "$h" hostname; done
SCRIPT_EOF
$ chmod +x scripts/*.sh remote/*.sh 2>/dev/null; true

2Run it

$ scripts/00-prereqs.sh      # checks your tools, changes nothing
$ scripts/10-network.sh      # asks to confirm the account and region
$ scripts/20-compute.sh
What gets created
  • A VPC 10.240.0.0/24 with one subnet, an internet gateway and a default route.
  • A security group with two rules, both from itself: the group, and the Pod range 10.200.0.0/16. Nothing from the internet.
  • A role with AmazonSSMManagedInstanceCore, so the agent on each machine can register with Session Manager.
  • Three t3.small instances on Amazon Linux 2023: server (10.240.0.10), node-0 (.20), node-1 (.21). IMDSv2 required, encrypted disks.

3Check it

$ ssh -F .state/ssh_config server hostname
server
$ ssh -F .state/ssh_config node-0 hostname
node-0

Look for the right hostname on each. If a machine never shows up, 20-compute.sh stops with never came online in Session Manager.

Why no jumpbox and no SSH port?
  • The original guides use a jumpbox and open SSH to the world. Here your own machine is the admin host.
  • ssh runs through Session Manager: the instance connects out to AWS, and your SSH rides that connection. So the security group needs no inbound rule.
  • The instances still have public IPs, but only to download software and reach AWS. Nothing can connect in.
Why turn off the source/destination check?
  • By default EC2 drops any packet whose source or destination is not the instance's own IP.
  • A Pod on node-0 sends packets with a Pod IP as the source. Without this change, cross-node Pod traffic silently disappears.
Remember

Three address ranges, kept apart: machines (10.240.0.0/24), Pods (10.200.0.0/16) and Services (10.32.0.0/24).

Dig deeper with your AI

Guess first, then click for the TL;DR. Ask your AI for the full answer, and check it on your cluster or with kubectl explain.

  • Why one subnet and one availability zone?

    To keep the guide readable. A real cluster spreads control plane nodes over three zones so one zone failing does not stop it.

  • What is Session Manager?

    An AWS service where the instance agent opens an outbound connection to AWS, and you start a session through the AWS API. It needs an IAM role on the instance, and your own IAM permission.

  • Why is the whole security group open to itself?

    Kubernetes components use many ports (6443, 10250, NodePorts, Pod traffic). Inside a private group that only the three machines belong to, it keeps the guide simple. Tighten it for anything real.

  • What does this cost while it runs?

    Three t3.small instances, three disks and three public IPv4 addresses: about $0.08 an hour. Check current prices, and run the teardown.

Inspired by Kubernetes The Hard Way. Text and scripts: CC BY-NC-SA 4.0.