Hour 5 of Linux: Automated operation and maintenance - image construction, patches and logs
- Name five things that a ops script that can be put into production must have (strict mode, trap cleaning, writing journald logs, clear exit codes, ShellCheck in CI), and know which section of the Bash class to study in depth.
- Explain the structure of Packer's architecture (core + plug-in process, source/builder, communicator, provisioner, post-processor, data source) and HCL2 templates, and be proficient in using
packer init / fmt / validate / buildand variable files. - Use the same template to build Azure (azure-arm) and AWS (amazon-ebs) golden images, bake myapp (
/opt/myapp/app,/opt/myapp/venv,myapp.service) into it and do a smoke test before capturing. - Correctly generalize the image (cloud-init clean, machine-id reset, delete host keys and logs,
waagent -deprovision+user), do CIS style hardening during baking, and use Azure Compute Gallery version with AMI Naming/Tagging/DeprecationManage image lifecycle (immutable infrastructure). - Configure patch automation: unattended-upgrades / dnf-automatic, needrestart, restart strategy and maintenance window, understand the positioning of Livepatch / kpatch, and the division of labor with Azure Update Manager / SSM Patch Manager.
- Understand the sources and detection methods of configuration drift, determine the boundaries of "baking/startup configuration/configuration management", and use a minimal Ansible playbook to detect (
--check --diff) and correct drift. - Build a log centralized link: journald → rsyslog (omfwd + disk queue) or systemd-journal-upload, use Azure Monitor Agent / CloudWatch Agent on the cloud; deploy
myapp-healthchecktimer to implement discovery → self-healing → notification.
1-hour time allocation table
| # | Time | Module | Core content | Animation/Interaction | Experiment |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: Operation and maintenance workspace and cloud credentials | Install Packer, Ansible, jq, ShellCheck, rsyslog on linuxlab, confirm Azure / AWS CLI login, and establish ~/linuxlab/ops repository | Environment self-check list | Tool version self-check |
| 1 | 00–06 | Operation and maintenance script quick overview: Bash lesson points and links | "Five things" of operation and maintenance scripts: strict mode, trap cleaning, logger / systemd-cat writes journald, exit code convention, ShellCheck in CI - the corresponding section of the Bash class for each link | One run of the operation and maintenance script under systemd | Write myapp-config-snapshot and use systemd-run to observe logs and exit codes |
| 2 | 06–14 | Packer principle and HCL template | Core and plug-in, source/builder, communicator, provisioner, post-processor, data source; variable / locals / *.pkrvars.hcl; packer init/fmt/validate/build; HCP Packer | Core Animation (Part 1): How template blocks drive the build lifecycle | Write and verify minimal templates (no cost) |
| 3 | 14–22 | Build Azure and AWS golden images with Packer | azure-arm with amazon-ebs, provisioning myapp, smoke test, manifest, build failure rollback | Core Animation (Part 2): source → provisioning → generalization → capture → release build (Azure / AWS, injectable faults) | Bake myapp to Azure Image and AL2023 AMI |
| 4 | 22–29 | Image generalization, hardening and version management | cloud-init clean, machine-id, SSH host key, log and history, waagent deprovision; CIS style hardening during baking; Compute Gallery version, AMI Naming/Tagging/Deprecation; Immutable Infrastructure | "Clone First Boot" emulator: What's wrong if you miss a step | Release Gallery version 1.0.0 and AMI with deprecation time |
| 5 | 29–37 | Patch automation: unattended-upgrades, dnf-automatic and maintenance window | apt-daily timer chain, source filtering and blacklist, needrestart, restart strategy, Livepatch / kpatch, maintenance window and cloud patch service | A day of automatic patching (four updates) | Security updates only + 02:00 installation + 03:30 Restart window |
| 6 | 37–43 | Configuration drift and Ansible connection | Source of drift, dpkg --verify / rpm -Va / Image list comparison; baking vs startup vs configuration management; minimum playbook and --check --diff | Drift Timeline: Detect → Correct or Rebuild | Making drift, detecting, correcting with Ansible |
| 7 | 43–51 | Log concentration: journald forwarding, rsyslog and cloud collection | myapp-healthcheck + systemd timer, OnFailure notification; journald ForwardToSyslog, rsyslog omfwd + queue, systemd-journal-upload; AMA / CloudWatch Agent | Health check → self-healing → log forwarding link | Deploy health check timer and centralized log |
| 8 | 51–60 | Summary, self-test and cleanup of the first five hours | Five-lesson knowledge map, common pitfall summary, mirror/snapshot/Gallery cleaning list, interactive troubleshooting tree | Knowledge Map Flashcards + Interactive Troubleshooting Tree | Cleaning Images, Gallery, AMIs, Snapshots and Cloud Resources |
| — | After class | Cheatsheet · Comprehensive experiment | myapp 1.1.0: hardened and generalized image → release version → startup verification → patch baseline → drift check → centralized log → cleanup | Final exam (12 questions) | Comprehensive Experiment |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands/objects | Experiments |
|---|---|---|---|---|---|---|---|---|---|---|
| Operation and maintenance script conventions | ✓ | · | ✓ | · | · | · | ✓ | ✓ | set -Eeuo pipefail, trap, logger -t, shellcheck | M1 experiments |
| Packer Architecture and Templates | · | ✓ | ✓ | ✓ | · | · | · | ✓ | packer init/fmt/validate/build, -var-file | M2 Experiment |
| Multi-Cloud Golden Image | · | ✓ | ✓ | ✓ | · | · | · | ✓ | azure-arm, amazon-ebs, manifest | M3 Experiment |
| Generalization and Reinforcement | · | · | ✓ | ✓ | · | ✓ | · | ✓ | cloud-init clean --machine-id, waagent -deprovision+user | M4 Experiment |
| Image version and life cycle | · | ✓ | · | ✓ | ✓ | ✓ | · | ✓ | az sig image-version, deprecate_at, tags | M4/M8 Experiment |
| Patch Automation | · | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | unattended-upgrade --dry-run, needrestart -b, dnf-automatic | M5 Experiment |
| Drift detection and configuration management | · | · | · | ✓ | ✓ | ✓ | · | ✓ | dpkg --verify, ansible-playbook --check --diff | M6 experiment |
| Scheduled tasks and self-healing | ✓ | · | · | · | ✓ | · | ✓ | ✓ | systemctl list-timers, OnFailure= | M7 experiment |
| Log concentration | ✓ | · | · | ✓ | · | · | ✓ | ✓ | ForwardToSyslog, rsyslog omfwd, systemd-journal-upload | M7 Experiment |
Content excluded from this lesson (and where to learn)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
The Bash language itself: expansion order, quotes, arrays, functions, set -e exceptions, trap, getopts, jq/xargs/parallel, ShellCheck/shfmt/bats | There is a complete 8-hour course; Module 1 of this course only gives the checklist and link to the operation and maintenance script | Bash 8 hours (hours 1, 2, 4, 5, 7) |
| CI/CD The platform itself (Runner, pipeline syntax, OIDC, environment approval) | This lesson only explains the position of "image construction into the pipeline" | GitHub 8 hours · GitLab 8 hours |
| Ansible role, inventory, Vault, rolling deployment | This lesson only uses a minimal playbook to demonstrate drift detection and correction | Ansible 8 hours |
| Use Terraform to consume images (VMSS/ASG, startup templates, instance refresh) | This lesson produces and publishes images; the infrastructure code for consuming images belongs to IaC | Terraform 8 Hours |
| Full CIS baseline, SELinux/AppArmor, nftables, auditd | This lesson applies only a few hardening items while baking | Lesson 6: Security Hardening and Kernel Mechanism |
| Indicator Monitoring and Alert (Prometheus, Grafana, Alertmanager) | This lesson only does "scripted health check + Log concentration" | Prometheus & Grafana 8 hours |
| Container image build (Dockerfile, multi-stage build) | This course talks about virtual machine images | Docker 8 hours |
How to use this courseware
Principle · Diagram · Animation · Command · Experiment · Production case · Troubleshooting · Test · Voice · Video. The animations of Modules 2 and 3 together are the core of this lesson: first look at "when each block of the HCL template takes effect in the build", and then look at "what a real cloud build does from source to release version".
Test score ≥ 70% or click "Mark this module completed" will be counted into the progress and saved in this browser (it will be cleared after refreshing when local storage is disabled).
The "Voice" tab uses the browser's built-in Web Speech API (en-US) to read the transcript; when there is no Chinese voice package, the transcript can still be read or handed over to the TTS tool.
linuxlab(Ubuntu 26.04 LTS, released 2026-04, current version 26.04.1). In the Ubuntu 26.04 repository: cloud-init 26.1, walinuxagent 2.15.0.1, needrestart 3.11, unattended-upgrades 2.12, systemd 259, rsyslog 8.2512, ansible-core 2.20.1. Packer is currently 1.16.2 (2026-10-22, from HashiCorp apt repository), plug-in azure v2.6.5, amazon v1.8.4, ansible v1.1.6. Cloud: Azure using Canonical:ubuntu-26_04-lts:server, AWS using Amazon Linux 2023 (consistent with Lesson 4). RHEL system control machine rhellab(Rocky Linux 10.x) uses dnf. Note: Ubuntu 26.04 defaults sudo-rs and coreutils implemented in Rust. The provisioning script in this lesson adopts sudo env VAR=… cmd and other writing methods that are compatible with both implementations. Module 0 · Preparation: Operations Workspace and Cloud Credentials (completed before class)
- Completed Lesson 1 (Shell, permissions, package management), Lesson 2 (systemd, journald, myapp.service), No. Lesson 3 (Azure:
rg-linux-lab/vm-linux-lab, regioncanadacentral), Lesson 4 (AWS:ca-central-1, tagName=linux-lab, Amazon Linux 2023). - Local lab VM
linuxlab(Multipass creation, 2 vCPU / 4 GiB / 20 GiB), userlabadminhas sudo; myapp runs asmyapp.service: code/opt/myapp/app, virtual environment/opt/myapp/venv, configure/etc/myapp/myapp.env(root:myapp 0640), listen on 5000 port and provide/healthz. - Bash basics: Able to read scripts with
set -Eeuo pipefailandtrap. If you are not familiar with it, learn Bash hour 4: Robustness (this lesson will not be repeated). - Module 3–4 Optional: Resource groups can be created in Azure subscriptions (Packer will create temporary resource groups, or use
build_resource_group_nameinstead) and Compute Gallery; AWS accounts have EC2 permissions to create instances/AMIs/snapshots.
Step 1: Start the lab VM and confirm that myapp is online
# On Windows / macOS host multipass start linuxlab multipass shell linuxlab # In the lab VM (labadmin) grep -E '^(PRETTY_NAME|VERSION_ID)=' /etc/os-release systemctl is-active myapp.service redis-server.service systemctl show myapp.service -p WorkingDirectory -p Type -p SyslogIdentifier sudo stat -c '%U:%G %a %n' /etc/myapp/myapp.env curl -fsS http://127.0.0.1:5000/healthz; echo
PRETTY_NAME="Ubuntu 26.04.1 LTS"
VERSION_ID="26.04"
active
active
Type=exec
WorkingDirectory=/opt/myapp/app
SyslogIdentifier=myapp
root:myapp 640 /etc/myapp/myapp.env
{"status":"ok"}
If myapp is not online, return to the "Experiment" tab of Lesson 2 to redeploy (sudo systemctl enable --now myapp.service, journalctl -u myapp -n 50 to see the reason). The response body of /healthz is based on your myapp version. The script in this lesson only relies on HTTP status codes.
Step 2: Install operation and maintenance tools
sudo apt-get update sudo apt-get install -y jq shellcheck ansible-core rsyslog curl git debsums for c in jq shellcheck ansible; do printf '%-11s ' "$c"; "$c" --version 2>&1 | head -1; done
jq jq-1.8.1 shellcheck ShellCheck - shell script analysis tool ansible ansible [core 2.20.1]
ansible-core Contains only core and ansible.builtin collections, sufficient for the minimum playbook of Module 6 of this course; when Azure / AWS collections are required, install the ansible package or use pipx install --include-deps ansible (see Ansible Chapter 1 Hours). debsums For drift detection of module 6 (dpkg --verify It is not needed, the two are complementary) Step 3: Install Packer (HashiCorp official apt repository)
The resolute (26.04) package is available in the HashiCorp repository. The following uses a .sources file in deb822 format (consistent with the new apt format taught in Lesson 1):
curl -fsSL https://apt.releases.hashicorp.com/gpg \ | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg sudo tee /etc/apt/sources.list.d/hashicorp.sources >/dev/null <<EOF Types: deb URIs: https://apt.releases.hashicorp.com Suites: $(. /etc/os-release; echo "$VERSION_CODENAME") Components: main Architectures: $(dpkg --print-architecture) Signed-By: /usr/share/keyrings/hashicorp-archive-keyring.gpg EOF sudo apt-get update && sudo apt-get install -y packer packer version
Packer v1.16.2
Building in the cloud also requires Azure CLI (az login, installed in Lesson 3) and AWS CLI v2 (configured in Lesson 4). Packer has adopted the BUSL 1.1 license since 1.10. Personal learning and internal use of the enterprise are not affected. Please evaluate it yourself for commercial distribution.
Step 4: Establish an operation and maintenance repository
mkdir -p ~/linuxlab/ops/{bin,packer/{files,scripts},systemd,ansible} && cd ~/linuxlab/ops
git init -b main
printf '*.sh text eol=lf\nbin/* text eol=lf\n*.hcl text eol=lf\n' > .gitattributes
printf 'manifest.json\n*.log\npacker/files/app/\n' > .gitignore
git add . && git commit -m "chore: scaffold linuxlab ops repo"
find . -path ./.git -prune -o -type d -print
~/linuxlab/ops/ ├── bin/ # Operation and maintenance scripts: myapp-config-snapshot, patch-status.sh, drift-check, myapp-healthcheck, cleanup-lab.sh ├── packer/ # myapp.pkr.hcl, variables.pkr.hcl, *.pkrvars.hcl, files/, scripts/ ├── systemd/ # myapp-healthcheck.service / .timer, notify-failure@.service ├── ansible/ # baseline.yml (module 6) └── .gitattributes .gitignore
If you have taken the Bash class, the CI configuration (ShellCheck + shfmt + bats) of ~/bashlab/opsctl can be copied directly to this repository; this class only requires ShellCheck (module 1).
Warm-up: Answer from memory (30 seconds)
In Lessons 3 and 4, who is doing the "instance-related" initialization when the new VM/instance is started for the first time?
cloud-init: Read IMDS/user data, set host name, create user, write SSH public key, generate SSH host key, run script. It determines "whether it is a new instance" based on instance-id - this is the key to the generalization of module 4: the remaining state in the image will make the cloned machine "think it is not new."
In Lesson 2, where can I see the logs of myapp? What is its log ID?
journalctl -u myapp.service or journalctl -t myapp (in unit SyslogIdentifier=myapp). Module 7 of this lesson will forward journald / rsyslog logs to a centralized location.
What does it mean when the /var/run/reboot-required file appears?
An installed update (usually the kernel or a core library such as libc) requires a restart to take full effect. The default automatic update will not automatically restart - Module 5 talks about restart strategies and maintenance windows.
Module 1 · Overview of operation and maintenance scripts: Bash lesson key points and links
- Tell me five things that operation and maintenance scripts on Linux must do: strict mode, trap cleaning, writing journald logs, clear exit codes, ShellCheck in CI, and the corresponding sections of each item in the Bash class.
- Understand how stdout/stderr, priority prefix
,SyslogIdentifierand exit code become journald records and unitResultwhen a script is run under systemd. - Use a 40-line template script to complete a closed loop of "write → check → run under systemd → check logs and exit codes".
What: The "operation and maintenance script" mentioned in this lesson
The ops script is a Bash program that runs unattended: the Packer provisioner runs it on the build machine, the systemd timer runs it every minute, and CI checks it on every commit. No one is watching the terminal, so it must fail obviously (non-zero exit code + log), fail cleanly (clean up temporary files and locks), and be judged by the machine (exit code has a convention, logs can be retrieved by identifier).
Why: Five things to compare with the Bash class
| # | Must do | What it means on Linux | System learning |
|---|---|---|---|
| 1 | Strict mode set -Eeuo pipefail | Command failure, undefined variables, and pipeline failure will terminate the script instead of continuing with the error (for example, the DIR in rm -rf "$DIR"/* is empty). The exceptions to remember are: if conditions, &&/|| non-last term, local x=$(…). | Bash hour 4 · Module 1: Strict Mode |
| 2 | trap cleanup (EXIT / ERR) + mktemp + flock | Regardless of success, failure, or being stopped by SIGTERM (sent when systemd stops the service), the temporary directory must be deleted and the lock released; ERR trap records the error line number. | trap · mktemp · flock and idempotent |
| 3 | Log into journald: logger / systemd-cat / stderr | by systemd When starting, stdout/stderr directly enters journald, and the <3>/<4>/<6> at the beginning of the line is parsed as priority (SyslogLevelPrefix=yes is enabled by default); when running manually, use logger -t flag -p user.err. Use the key=value format to facilitate parsing by the centralized log platform (Module 7). | Bash hour 4 · Module 5: Logging · Linux Lesson 2 · journald |
| 4 | Explicit exit code | 0 Success; 1 General failure; 2 Usage error; 3 Missing dependencies; other values are written in comments. systemd marks a non-zero exit as a unit failure (triggering OnFailure=), Packer treats a non-zero exit as a provisioning failure and rolls back, and CI treats it as a red light. | Bash hour 1 · Exit status · Hour 3 · Exit code convention |
| 5 | ShellCheck in CI | Automatically statically checks bin/ and packer/scripts/ for each submission, and prevents problems such as "variables are not quoted" and "cd failure is not handled" before merging. | Bash hour 7 · ShellCheck · Hour 6 · In CI Run the script in systemd |
How: Run the script once under systemd
- systemd forks + execs the script as a unit, sets the environment variable
INVOCATION_ID, and connects stdout/stderr to journald's stream socket. - Strict mode and trap are in effect;
flock -nprevents re-entering before the previous round is finished (the systemd timer itself will not repeatedly start services that are still running). - Each line of stderr output is recorded by journald, with fields such as
SYSLOG_IDENTIFIER,_SYSTEMD_UNIT,PRIORITY,_PID. - The script exits, EXIT trap cleans up the scene; systemd records
ExecMainStatusandResult(success/exit-code/signal/timeout), and starts the unit specified byOnFailure=when it fails.
When: Is Bash enough?
Concatenate ready-made commands, provision images, regularly check, and clean up resources - Bash is suitable. When you need complex data structures, HTTP API clients, and hundreds of lines of business logic, switch to Python/Go (for judgment signals, see Bash hour 7 · Module 7); hand over the desired status of multiple hosts to Ansible (module 6).
set -e Can catch all failures" - Failures in the conditional context are ignored, and the pipeline only looks at the last command by default (so pipefail). ② "In the script echo is the log" - cron The output will be lost or become emails; although journald is entered under systemd, there is no priority, and the alarm rules cannot be filtered. ③ "The exit code is returned at will" - Packer, systemd, and CI only look at the exit code. || true Failure to swallow will cause the bad image to be "successfully" output. ④ "ShellCheck has no warning, so there is no problem" - it only does static analysis, and its behavior depends on testing (bats) and build-time smoke testing (module 3). Architecture diagram: "Contract" of operation and maintenance scripts
Comparison chart: where the same line of logs goes in three operating modes
Interactive simulator: a run of the operation and maintenance script under systemd
Select a scenario and play it to observe how strict mode, locks, traps, logs and exit codes work together, and what systemd ultimately records. The terminal below shows typical output (illustrated) from journalctl and systemctl show.
Core commands
| Command | Function | Description |
|---|---|---|
logger -t TAG -p user.err -- "msg" | Write journald / syslog from script | Run manually or cron Used under; --id=$$ comes with PID |
systemd-cat -t TAG -p warning cmd | Write all the output of a command to journald | Suitable for packaging third-party commands |
systemd-run --wait --unit=NAME -p SyslogIdentifier=TAG cmd | Temporarily run as a service, wait and report the results | You can see the real behavior under systemd without writing unit files |
journalctl -t TAG -p warning -o short-iso | Retrieve by identification and priority | -o json View all fields |
systemctl show UNIT -p Result,ExecMainStatus | Unit final result and exit code | The first step in troubleshooting service triggered by timer |
shellcheck -x FILE… | Static check | Ubuntu 26.04 repository is 0.11.0 |
Template script: bin/myapp-config-snapshot
#!/usr/bin/env bash
# myapp-config-snapshot - package /etc/myapp and myapp.service to $DEST, keeping the latest $KEEP copy
# Exit code: 0 success; 1 failed to run; 2 usage error; 3 missing dependency; 75 instance is already running (EX_TEMPFAIL)
set -Eeuo pipefail
DEST=${DEST:-/var/backups/myapp}
KEEP=${KEEP:-7}
log() { # log LEVEL MSG… LEVEL: err | warning | info
local lvl=$1; shift
if [[ -n ${INVOCATION_ID:-} ]]; then # Started by systemd: stderr directly enters journald
local -A pri=([err]=3 [warning]=4 [info]=6)
printf '<%s>%s\n' "${pri[$lvl]}" "$*" >&2
else # Manual operation: write journald and display in the terminal
logger -t myapp-config-snapshot -p "user.$lvl" -- "$*"
printf '%s: %s\n' "$lvl" "$*" >&2
fi
}
(( $# == 0 )) || { log err "usage: ${0##*/} (takes no arguments; use DEST= KEEP=)"; exit 2; }
command -v tar >/dev/null || { log err "missing dependency: tar"; exit 3; }
exec 9>/run/lock/myapp-config-snapshot.lock
flock -n 9 || { log warning "another run holds the lock, skipping"; exit 75; }
tmp=$(mktemp -d)
trap 'rm -rf -- "$tmp"' EXIT
trap 'log err "status=failed line=$LINENO cmd=$BASH_COMMAND"' ERR
stamp=$(date +%Y%m%d-%H%M%S)
install -d -m 0750 "$DEST"
tar -C / -czf "$tmp/config-$stamp.tar.gz" etc/myapp etc/systemd/system/myapp.service
mv -- "$tmp/config-$stamp.tar.gz" "$DEST/" # After writing it completely, put it in the target directory
shopt -s nullglob
files=("$DEST"/config-*.tar.gz) # The name contains timestamp, glob ascending order = time ascending order
n=$(( ${#files[@]} - KEEP )); removed=0
if (( n > 0 )); then rm -f -- "${files[@]:0:n}"; removed=$n; fi
log info "status=ok snapshot=$DEST/config-$stamp.tar.gz kept=$KEEP removed=$removed"
Why is it written like this: Each item corresponds to five things in the "Principles" page; INVOCATION_ID is an environment variable set by systemd for each service run, which is used to distinguish "under systemd" from "manual running". /etc/myapp/myapp.env has permissions of root:myapp 0640, which is also included in the snapshot file, so the target directory is set to 0750 (only root can read and write). Language details - local -A, ${files[@]:0:n}, ERR trap inheritance (-E) - see Bash hour 2 · Arrays and Hour 4 · trap. Bash hour 6 · Module 7). Module 2 will add packer fmt -check and packer validate to the same pipeline.
CI minimum job: .github/workflows/ops-ci.yml
name: ops-ci
on: [push, pull_request]
jobs:
shellcheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- run: sudo apt-get update -q && sudo apt-get install -y -q shellcheck
- run: shellcheck -x bin/* packer/scripts/*.sh
Third-party Action submits SHA fixation by 40 bits (see Bash hour 6 · Module 7 for reasons and GitLab CI writing methods). Module 2 will add packer fmt -check and packer validate to the same pipeline.
Experiment 1: Write an operation and maintenance script and observe its performance under systemd (about 5 minutes)
~/linuxlab/ops/bin/myapp-config-snapshot:
cd ~/linuxlab/ops chmod +x bin/myapp-config-snapshot bash -n bin/myapp-config-snapshot && shellcheck -x bin/myapp-config-snapshot && echo "lint ok" sudo install -m 0755 bin/myapp-config-snapshot /usr/local/bin/
lint ok
systemd-run):
sudo systemd-run --wait --unit=snap-test -p SyslogIdentifier=myapp-config-snapshot \
/usr/local/bin/myapp-config-snapshot
journalctl -t myapp-config-snapshot -n 3 -o short-iso --no-pager
journalctl -t myapp-config-snapshot -n 1 -o json --no-pager | jq '{PRIORITY, SYSLOG_IDENTIFIER, _SYSTEMD_UNIT}'
sudo ls -l /var/backups/myapp/
Running as unit: snap-test.service; invocation ID: 4f0c…
Finished with result: success
Main processes terminated with: code=exited, status=0/SUCCESS
Service runtime: 41ms
2026-11-17T09:02:11+00:00 linuxlab myapp-config-snapshot[2210]: status=ok snapshot=/var/backups/myapp/config-20261117-090211.tar.gz kept=7 removed=0
{
"PRIORITY": "6",
"SYSLOG_IDENTIFIER": "myapp-config-snapshot",
"_SYSTEMD_UNIT": "snap-test.service"
}
-rw-r--r-- 1 root root 1432 Nov 17 09:02 config-20261117-090211.tar.gzsudo systemd-run --wait --unit=snap-bad -p SyslogIdentifier=myapp-config-snapshot \ /usr/local/bin/myapp-config-snapshot --now; echo "rc=$?" sudo systemd-run --wait --unit=snap-ro -p SyslogIdentifier=myapp-config-snapshot \ -p ReadOnlyPaths=/var/backups /usr/local/bin/myapp-config-snapshot; echo "rc=$?" journalctl -t myapp-config-snapshot -p err -n 2 --no-pager systemctl show snap-ro.service -p Result -p ExecMainStatus 2>/dev/null || true
Finished with result: exit-code Main processes terminated with: code=exited, status=2/INVALIDARGUMENT rc=2 Finished with result: exit-code Main processes terminated with: code=exited, status=1/FAILURE rc=1 … myapp-config-snapshot[2290]: usage: myapp-config-snapshot (takes no arguments; use DEST= KEEP=) … myapp-config-snapshot[2301]: status=failed line=30 cmd=install -d -m 0750 "$DEST"
ReadOnlyPaths= makes /var/backups read-only in this run, simulating "the target is not writable"; the specific failed line number and command shall be subject to actual conditions. The temporary unit will be recycled after the end, and systemctl show may not be found - the log is the basis for subsequent troubleshooting.
logger) and submitted:
sudo KEEP=3 /usr/local/bin/myapp-config-snapshot journalctl -t myapp-config-snapshot -n 1 -o cat --no-pager git add bin/myapp-config-snapshot && git commit -m "feat: myapp-config-snapshot"
info: status=ok snapshot=/var/backups/myapp/config-20261117-090540.tar.gz kept=3 removed=0 status=ok snapshot=/var/backups/myapp/config-20261117-090540.tar.gz kept=3 removed=0
Clean up: It doesn't hurt to keep /var/backups/myapp; to remove: sudo rm -rf /var/backups/myapp.
Case 1: Provisioning failed by || true
Problem: In the image provisioning script, pip install -r requirements.txt || true is to "avoid occasional network errors interrupting the build". As a result, a PyPI Timeout, the image is successfully produced without dependencies, but all instances fail to start after going online. What to do: Remove || true, do a limited retry of network operations (Bash hour 4 · Retries and Backoff), and run a smoke test before capturing (module 3). Limitations: Retrying will lengthen the build time and an upper limit needs to be set.
Case 2: cron job failed "silently" for three months
Issue: Configuration backups are run by cron and output is redirected to /dev/null; backups keep failing after the disk is full and no one knows. Method: Change to systemd timer + oneshot service. The script writes journald according to priority. The failure exit code triggers OnFailure= notification (module 7), and creates an alarm for PRIORITY<=3 on the log platform. Restrictions: Notifications must be deduplicated and upgraded, otherwise they will be ignored.
Case 3: ShellCheck in CI blocks a dangerous delete
Issue: The cleanup script rm -rf $WORKDIR/* was not noticed in the review. How to do it:CI's ShellCheck reports SC2115/SC2086, the merge is blocked; change to rm -rf -- "${WORKDIR:?}"/*. Limitations: ShellCheck cannot determine "whether the value is correct" (for example, WORKDIR is set to /), and the critical path still needs to be whitelisted for verification.
Common errors and solutions
journalctl -t myapp-config-snapshot has no output
Cause:systemd-run does not set SyslogIdentifier, the log identifier is the executable file name or unit name; or the script output is redirected.
journalctl -u snap-test.service -n 20 --no-pager journalctl _COMM=myapp-config-s -n 5 --no-pager # _COMM truncated to 15 characters
Fix: Write SyslogIdentifier= in the unit or systemd-run; press -u to query and confirm that the log exists.
Literal "<6>status=ok..." appears in the terminal
Cause: The priority prefix is only parsed by journald on the stdout/stderr of the service; it is just plain text when running in the terminal or cron.
Fixed: Press INVOCATION_ID to switch like a template; or always use logger when running manually.
flock: 9: Bad file descriptor / /run/lock/…: Permission denied
Cause: Non-root users cannot create the file in /run/lock (depending on directory permissions), or exec 9> fails.
ls -ld /run/lock; id
Fix: Run as root, or put the lock in the $XDG_RUNTIME_DIR/service's RuntimeDirectory=.
systemd-run: Failed to start transient service unit: Unit snap-test.service already exists
Cause: The temporary unit with the same name is still there (remaining in the failed state since the last run failed).
systemctl status snap-test.service --no-pager; sudo systemctl reset-failed snap-test.service
Fixed: reset-failed and then try again, or change the name of --unit; add --collect to allow the failed temporary unit to be recycled.
1. Find the logs with a priority of err and above in all myapp-related scripts (identification starting with myapp) today, and only display the time, identification and message.
journalctl --since today -p err -o json --no-pager \
| jq -r 'select(.SYSLOG_IDENTIFIER // "" | startswith("myapp")) | [.__REALTIME_TIMESTAMP, .SYSLOG_IDENTIFIER, .MESSAGE] | @tsv'2. Use systemd-run to run /usr/local/bin/myapp-config-snapshot as a service, set the environment variable KEEP=3, and print the exit code after completion.
sudo systemd-run --wait --collect --unit=snap-keep3 -E KEEP=3 \ -p SyslogIdentifier=myapp-config-snapshot /usr/local/bin/myapp-config-snapshot; echo "rc=$?"
You have to review a Packer provisioning script written by a colleague, and you only have 5 minutes. In what order would you check?
① The first line of shebang and set -Eeuo pipefail; ② Whether there is || true, 2>/dev/null swallowing failure; ③ Whether the network operation has timeout and limited retry; ④ Whether the temporary file uses mktemp and trap Clean (should not remain in the image); ⑤ Whether secrets are written (cannot exist in the image); ⑥ Whether to exit non-zero and print enough context (ERR trap line number) on failure; ⑦ Whether ShellCheck is run in CI. The details at the language level are reported to ShellCheck first, and the manual review focuses on "what happens when it fails."
Verified instructional video
System learning and official documents
- Bash 8-hour course directory: Hour 4 Robustness · Hour 6 Automation in Action · Hour 7 Testing and Quality
- systemd.exec(5)(SyslogIdentifier, SyslogLevelPrefix, $INVOCATION_ID) · systemd-run(1)
- logger(1) · systemd-cat(1) · ShellCheck Wiki
Video storyboard (about 70 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: In the computer room late at night, no one is staring at the screen; the three icons of timer, Packer and CI take turns to start the same script.
Narration: The operation and maintenance script is an unattended program. The caller only sees two things: exit code and log.
Screen: Five labels light up in sequence on the script shell: strict mode, trap cleanup, journald log, exit code, ShellCheck; the section number corresponding to the Bash class appears next to each label.
Narration: Five things are indispensable, and the language details will be explained one by one in the Bash class.
Screen: The script fails, the red "exit 1" flies to systemd, systemd lights OnFailure, and the log entry flies to the centralized platform with priority three.
Narration: Failure is obvious and failure is clean. Subsequent image construction, patches and health checks are all based on this agreement.
Module 2 · Packer Principle and HCL Template
- Draw the architecture of Packer: core process + plug-in process (builder / provisioner / post-processor / data source), and communicator (SSH / WinRM / none) position.
- Read and write the six blocks of the HCL2 template:
packer,variable,locals,data,source,build(including provisioner, post-processor,hcp_packer_registry), and tell the priority of variable values. - Be proficient in using
packer init / fmt / validate / inspect / console / build, know the functions of-only,-var-file,-on-error, and understand the positioning of HCP Packer.
What: Packer
Packer is HashiCorp's "image as code" tool (BUSL 1.1 License): Read the HCL2 template, start a temporary machine on the target platform, connect to it and run the provisioning script, then capture the disk into a platform image (Azure managed image/Compute Gallery version, AWS AMI, VMware template, Docker image...), and finally clean the temporary resources and run the post-processor. The same template can produce "consistent" images for multiple platforms at the same time.
| Component | In template | Responsibility | Used in this lesson |
|---|---|---|---|
| Builder (builder) | source "type" "name" {} | Talk to platform API: create temporary machine, wait for ready, shutdown, capture, cleanup | azure-arm, amazon-ebs, null (for practice) |
| Communicator (communicator) | in the source block: ssh_* / winrm_* / communicator | Connect to the temporary machine, upload files, execute commands | SSH (Linux), none (no connection) |
| Provisioner (provisioner) | build { provisioner "type" {} } | Do things in the machine in order: upload, run script, call Ansible | file, shell, shell-local; ansible (mentioned in module 6) |
| Post-processor (post-processor) | build { post-processor "type" {} } | Reprocess or record the product: list, checksum, upload, trigger script | manifest |
| Data source (data source) | data "type" "name" {} | Query external information before building, such as the "latest base AMI" or the image of a channel in HCP Packer | amazon-ami (cf. source_ami_filter) |
Except the file/null builder, shell/file/shell-local provisioner, and manifest/checksum/shell-local After the post-processor is built into the core, other components are independent plug-in binaries: packer init Press required_plugins to download to ~/.config/packer/plugins (or PACKER_PLUGIN_PATH). When building, the core starts the plug-in as a child process and calls it through local RPC. Plug-in versions are released independently from Packer versions (currently azure v2.6.5, amazon v1.8.4, ansible v1.1.6).
Why: Why use Packer instead of "start a machine and install it manually and then take a snapshot"
- Repeatable: Template + provisioning script into Git, anyone can rebuild the same result from the base image at any time.
- Reviewable: Mirror changes go through PR, CI (
packer fmt -check,packer validate, ShellCheck). - Multi-platform consistency: One set of provisioning scripts, multiple sources built in parallel.
- Clean: The temporary machine only exists during the build and rolls back by default on failure (
-on-error=cleanup). - Cloud native alternatives: Azure VM Image Builder (Microsoft managed service, based on Packer) and EC2 Image Builder (AWS managed pipeline and components). They eliminate the need to build a self-built machine, but bind a single cloud; this lesson uses Packer to keep multi-cloud consistent.
How: The effective order of each block in a packer build
- Parse all
*.pkr.hclin the directory (one directory = one configuration), checkpacker { required_version, required_plugins }. - Variable evaluation:
variabledefault value → environment variablePKR_VAR_name→ automatically loaded*.auto.pkrvars.hcl(in lexicographic order by file name) → command line-var-file/-var(in order of appearance), the latter overrides the former; thevalidationrule is run; the value ofsensitive = trueappears in the output as. - locals and data are evaluated (the data source will call the cloud API at this time).
- For each source in
build.sourcesParallel: Builder creates temporary machine → Communicator connection → Run provisioner in written order (only/exceptfiltering) → Builder shutdown, generalize, capture → Delete temporary resources. - Each product passes through post-processor in turn (
post-processors {}blocks can be chained), and metadata can be reported to HCP Packer (hcp_packer_registryblock).
When: Packer boundaries
| Good for Packer | Not suitable for Packer |
|---|---|
| OS patches, base packages, hardening, agents, runtimes and application code - "the same for all instances of the same role" stuff | Secrets, hostname, environment address (injected by cloud-init or configuration management at startup); Continuous configuration of running instances (Ansible, module 6); VM scale set/launch template for consuming images (Terraform) |
HCP Packer is HashiCorp The managed Image metadata registry (does not store the image itself): When building, use hcp_packer_registry to report "which template, which Git commit, and which image ID was produced in which region", and then use "channel" (such as production) to label the version. Terraform uses hcp_packer_artifact data source to get the image by channel. ID to realize promotion and rollback. Requires an HCP account and service principal (HCP_CLIENT_ID / HCP_CLIENT_SECRET); this lesson does not rely on it, Module 4 instead uses the Compute Gallery version and AMI tag to achieve the same purpose.
packer validate It will be built successfully if passed" - it only checks the syntax, type and some parameters, and does not actually create resources or run the provisioning script. ③ "*.pkrvars.hcl will load automatically" - only *.auto.pkrvars.hcl will load automatically, others must be specified with -var-file . ④ "env() can be used anywhere" - it can only appear in variable 's default Medium. ⑤ "Shell variables will be shared between provisioners" - each provisioner is a new process. To pass values, use shell The provisioner is a new process, you need to pass the value environment_vars or write a file. Architecture diagram: core, plug-ins and temporary machines
Structural chart: how template files are organized
Core Animation (Part 1): When does each block of the template take effect
The left side is the block structure of myapp.pkr.hcl, and the currently active block is highlighted during playback; the chip on the right is the build life cycle source → provisioning → generalization → capture → release version. Switch the scene and see where the process stops when "variable verification fails" and "provisioning fails + cleanup / abort". The animation in Module 3 expands on the specific API calls made by Azure and AWS in the cloud.
Core commands and parameters
| Commands | Function | Key parameters/description |
|---|---|---|
packer init . | Press required_plugins to install the plug-in | -upgrade to upgrade to the latest version within the constraints; cache the plug-in directory in CI |
packer fmt -recursive . | Format HCL | -check -diff: only check (for CI), if there is a difference, exit with non-zero value |
packer validate . | Verify syntax, type, variable rules and some parameters | -syntax-only does not require plug-ins and credentials; -var-file is the same build |
packer inspect . | List variables, sources, build | Quickly understand the structure when reviewing templates |
packer console . | Interactive evaluation of expressions | Debugging local.*, function: formatdate("YYYYMMDD", timestamp()) |
packer build . | Build | -only='azure-arm.ubuntu' / -except; -var k=v; -var-file=f; -on-error=cleanup|abort|ask|run-cleanup-provisioner; -parallel-builds=N; data-xlt-id="T6">Detailed logs |
packer plugins installed / install / required | Manage plug-ins | packer plugins install github.com/hashicorp/azure |
PACKER_LOG=1 PACKER_LOG_PATH=packer.log | Detailed log | Troubleshoot plug-in, API and SSH issues (note that logs may contain sensitive information) |
Split template: versions.pkr.hcl and variables.pkr.hcl
packer {
required_version = ">= 1.16.0"
required_plugins {
azure = {
source = "github.com/hashicorp/azure"
version = "~> 2.6"
}
amazon = {
source = "github.com/hashicorp/amazon"
version = "~> 1.8"
}
}
}
variable "app_version" {
type = string
description = "myapp version (MAJOR.MINOR.PATCH), also used as mirror version number"
default = "1.0.0"
validation {
condition = can(regex("^[0-9]+[.][0-9]+[.][0-9]+$", var.app_version))
error_message = "The app_version value must look like 1.2.3."
}
}
variable "azure_subscription_id" {
type = string
default = env("ARM_SUBSCRIPTION_ID") # env() can only be used in default
}
variable "webhook_url" { # Example: sensitive values, do not write *.pkrvars.hcl Submit to Git
type = string
default = ""
sensitive = true
}
locals {
stamp = formatdate("YYYYMMDDhhmmss", timestamp())
tags = {
app = "myapp"
version = var.app_version
built_by = "packer"
}
}
app_version = "1.0.0"
Data source comparison: use data block to find the underlying AMI
data "amazon-ami" "al2023" {
region = "ca-central-1"
owners = ["amazon"]
most_recent = true
filters = {
name = "al2023-ami-2023.*-x86_64"
virtualization-type = "hvm"
}
}
# Referenced in source: source_ami = data.amazon-ami.al2023.id
# Equivalent to source_ami_filter in source; the advantage of data is that the same result can be reused by multiple sources
HCP Packer (optional, just understand it)
hcp_packer_registry {
bucket_name = "myapp"
description = "myapp golden image"
bucket_labels = { owner = "platform" }
build_labels = { app_version = var.app_version }
}
# Environment variables HCP_CLIENT_ID / HCP_CLIENT_SECRET (service principal) are required; please delete this block if not set
How to verify:packer fmt -check . No output, packer validate . output The configuration is valid.. Common mistakes: Write env() into locals; the variable is not declared but assigned in *.pkrvars.hcl (an undeclared variable warning will be given). Production use: Run packer init, packer fmt -check -recursive, packer validate for each PR in CI; the real build is placed in the release pipeline with cloud credentials (OIDC).
Experiment 2: Zero-cost minimal template (null builder, ~5 minutes)
Using the core built-in null builder (communicator = "none", no connection to any machine) on linuxlab with shell-local The provisioner experiences the complete process of variables, verification, locals, build and manifest, and does not require any cloud account.
mkdir -p ~/linuxlab/ops/packer/lab && cd ~/linuxlab/ops/packer/lab
cat > lab.pkr.hcl <<'EOF'
packer {
required_version = ">= 1.16.0"
}
variable "app_version" {
type = string
default = "0.0.1"
validation {
condition = can(regex("^[0-9]+[.][0-9]+[.][0-9]+$", var.app_version))
error_message = "The app_version value must look like 1.2.3."
}
}
locals {
image_name = "myapp-${var.app_version}-${formatdate("YYYYMMDDhhmmss", timestamp())}"
}
source "null" "local" {
communicator = "none"
}
build {
name = "lab"
sources = ["source.null.local"]
provisioner "shell-local" {
inline = ["echo source=${source.type}.${source.name} image=${local.image_name}"]
}
post-processor "manifest" {
output = "manifest-lab.json"
custom_data = { image_name = local.image_name }
}
}
EOF
packer fmt -check . && packer validate .
The configuration is valid.
packer validate -var app_version=1.0 .; echo "rc=$?" echo 'app_version = "2.0.0"' > lab.auto.pkrvars.hcl PKR_VAR_app_version=3.0.0 packer console . <<< 'var.app_version' PKR_VAR_app_version=3.0.0 packer console -var app_version=4.0.0 . <<< 'var.app_version'
Error: Invalid value for variable
on lab.pkr.hcl line 5:
5: variable "app_version" {
The app_version value must look like 1.2.3.
rc=1
2.0.0
4.0.0
Environment variables (3.0.0) are overridden by *.auto.pkrvars.hcl (2.0.0), and command line -var (4.0.0) has the highest priority. The formatting of error messages is subject to the actual version.
packer build -timestamp-ui .
jq '.builds[0] | {name, builder_type, custom_data}' manifest-lab.json
2026-11-17T09:20:03Z: lab.null.local: output will be in this color.
2026-11-17T09:20:03Z: ==> lab.null.local: Running local shell script: /tmp/packer-shell1873441201
2026-11-17T09:20:03Z: lab.null.local: source=null.local image=myapp-2.0.0-20261117092003
2026-11-17T09:20:03Z: Build 'lab.null.local' finished after 31 milliseconds.
==> Builds finished. The artifacts of successful builds are:
--> lab.null.local: Did not export anything. This is the null builder
{
"name": "local",
"builder_type": "null",
"custom_data": {
"image_name": "myapp-2.0.0-20261117092003"
}
}ops-ci.yml (installation method is the same as the "Prepare" tab, or use the installation Action provided by HashiCorp, press SHA fixed):
- run: packer init packer && packer fmt -check -recursive packer && packer validate -syntax-only packer
rm -f lab.auto.pkrvars.hcl manifest-lab.json cd ~/linuxlab/ops && git add packer/lab && git commit -m "chore: packer lab template"
Cleanup: This experiment does not create any cloud resources.
Case 1: Plug-in "quietly" upgrade leads to changes in build behavior
Problem: The template says version = ">= 1.0", CI's new Runner executes packer init and installs a new major version of the plug-in, and the default value of a certain parameter changes, causing the image build to fail. Method: Use pessimistic constraints such as ~> 2.6 to lock the large version; upgrade the plug-in through PR, and cache the plug-in directory in CI. Restrictions: Pessimistic constraints will still accept minor version updates, and key pipelines can hard-code the full version number.
Case 2: The secret in the variable file entered Git
Problem: For convenience, someone wrote client_secret into prod.pkrvars.hcl and submitted it, and was subsequently alerted by the key scan. How to do it: Use Azure CLI / OIDC federated identity, AWS SSO / OIDC role for authentication; use the environment variable PKR_VAR_x to inject the CI secret for the value that needs to be passed in, and declare the variable sensitive = true; rotate the leaked credentials. Limitations:sensitive is only hidden in Packer output, PACKER_LOG debug logs and the output of the provisioning script itself may still be leaked.
Case 3: Use HCP Packer channel to implement image upgrade
Problem: Development, pre-release, and production each started from the "latest image", and as a result, the unverified image went directly to production. Method: Report to HCP Packer when building, and after passing the verification, assign the version to the staging and then to the production channel; Terraform only references the channel. Without HCP, a similar "pointer" can be implemented using Compute Gallery's exclude_from_latest with AWS SSM parameters (Module 4). Limitations: Channels/pointers are just metadata, the image itself still needs to be copied and cleaned by region.
Common errors and solutions
Error: Missing plugins — The following plugins are required, but not installed
Cause: packer init was not run, or the plug-in directory in CI is different from the local one (PACKER_PLUGIN_PATH).
packer init . && packer plugins installed
Fix: packer init before every build (idempotent, fast when installed).
Error: Unsupported block type / An argument named "xxx" is not expected here
Cause: The parameter is written in the wrong position (for example, ssh_username is written into build), or the parameter name belongs to another plug-in version.
packer validate . 2>&1 | head -20 packer plugins installed
Fix: Compare the parameter list of the builder in the plug-in document; confirm that the plug-in version is consistent with the document version.
Error: Call to unknown function / Function calls not allowed — env("…")
Reason: env() can only be used for variable default values; calling it directly in locals or source will report an error.
Fix: Declare variable "x" { default = env("X") }, reference var.x elsewhere; or use PKR_VAR_x directly.
Warning: Undefined variable — A "app_versoin" variable was passed in but not declared
Cause: The variable name in *.pkrvars.hcl or -var is misspelled, or the variable is not declared in any .pkr.hcl.
Fix: Correct spelling; treat such warnings as failures in CI (check validate output).
1. Only do syntax checking (no plug-ins and credentials required), and check the format of the entire packer directory.
packer fmt -check -diff -recursive packer && packer validate -syntax-only packer
2. Use the value of dev.pkrvars.hcl, overwrite the app_version to 1.4.2, build only the AWS part, and save the timestamped output to a file.
packer build -timestamp-ui -var-file=dev.pkrvars.hcl -var app_version=1.4.2 \ -only='amazon-ebs.al2023' . 2>&1 | tee build-$(date +%Y%m%d%H%M).log
The team wants to "use Packer to manage the configuration of all servers, and rebuild the image and replace the instance every time the configuration is changed." What is reasonable about this idea, and what needs to be added?
Reasonable: Immutable infrastructure reduces drift, and changes can be reviewed and rolled back. Need to add: ① Confidential and environment-related configurations cannot be entered into the image and still need to be injected at startup; ② Replacement instances require stateless applications, load balancing health checks and rolling replacement mechanisms (VMSS / ASG instance refresh); ③ Stateful services (databases) usually cannot be replaced frequently and require configuration management (Ansible) or managed services; ④ Mirror construction takes 10–20 minutes, and emergency repairs may require the fast track of configuration management; ⑤ Images require version management and expiration cleaning (Module 4).
Verified teaching video
Official Documentation
- Packer Documentation · HCL templates · Variables and priorities
- Command Reference · Plugins · Packer Releases (1.16.2)
- HCP Packer · Azure VM Image Builder · EC2 Image Builder
Video storyboard script (about 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: An HCL template is expanded from the Git repository, with six blocks colored in sequence: packer, variable, locals, data, source, build.
Narration: Packer writes images as code, and the template only has six types of blocks.
Screen: In the center is the packer core, with three wires connected to the three plug-in boxes of Azure, Amazon, and Ansible, and the plug-in is extended to the temporary machine in the cloud.
Narration: The core is responsible for parsing and scheduling, and the plug-in is responsible for talking to the cloud platform. They are independently released and installed by packer init.
Screen: Variables are superimposed from four sources and finally overwritten by the value of the command line; an illegal version number is blocked by the validation rule.
Narration: Variables have clear priorities, and validation rules can block incorrect input before the build starts.
Screen: Timeline: source, provisioning, generalization, capture, release version, five nodes light up in sequence.
Narration: This is the life cycle of each build. We will actually run the next module on Azure and AWS.
Module 3 · Building Azure and AWS with Packer Golden Image
- Explain the value and cost of golden images, as well as its division of labor with cloud-init (Lesson 3/4) and configuration management (Module 6).
- Configure
source "azure-arm"andsource "amazon-ebs"(base image, specifications, certifications, product naming, IMDSv2, SSH source tightening), using abuildblock andonlyfiltering to share the provisioning script between the two clouds. - Tell what the two builders create, call, and delete in the cloud (temporary resources → SSH → provisioning → smoke test → generalization → capture → cleanup), be able to read build logs, manifests, and troubleshoot common failures.
What: Golden Mirror
Golden image (golden image) is a base image recognized by the organization: patched, hardened, pre-installed with agents (monitoring, logging, security) and application runtime, and even the application itself. New instances are started from it and services are available within tens of seconds. This module uses module 2's versions.pkr.hcl and variables.pkr.hcl, plus sources.pkr.hcl, build.pkr.hcl and two provisioning scripts. myapp (/opt/myapp/app, /opt/myapp/venv, /etc/myapp/myapp.env, myapp.service) baked into Ubuntu 26.04 (Azure) and Amazon Linux 2023 (AWS) images.
Why: Why "baking"
| Dimension | Install at startup (cloud-init / user data) | Baked into the image (Packer) |
|---|---|---|
| Boot to available | Minute level (apt/dnf download, pip installation) | Second level (only instance-related configuration) |
| Reliability | The external repository is available when the dependency is started; it is most likely to fail during the expansion peak | Dependencies are resolved and tested during the build |
| Consistency | Instances started at different times may be installed with different versions | The same image = the same software collection, traceable to the build |
| Change method | In-place modification (possible drift) | Build new image → rolling replacement (immutable) |
| Cost | No need for image pipeline | Requires image pipeline, version management, expiration cleanup, storage cost |
How: What do the two builders do in the cloud
| Phase | azure-arm(Azure Resource Manager) | amazon-ebs(EC2 API) |
|---|---|---|
| Authentication | use_azure_cli_auth Reuse az login; use OIDC / service principal in CI | AWS SDK default credential chain (environment variables, configuration files, SSO, instance roles) |
| Base image | image_publisher/offer/sku = Canonical:ubuntu-26_04-lts:server | source_ami_filter(owners=amazon, name=al2023-ami-2023.*-x86_64, most_recent) |
| Temporary resources | Temporary resource group pkr-Resource-Group-*: VNet, public network IP, NIC, OS disk, VM (or use build_resource_group_name to specify an existing RG) | Temporary key pair, temporary security group (default source 0.0.0.0/0, can be tightened), instance (run_tags) |
| Connect | SSH, Packer generates temporary key and injects through deployment template | SSH login as ec2-user; also available ssh_interface = "session_manager" |
| Provisioning | Same set of provisioners: waiting for cloud-init → Upload files/ → install-myapp.sh → smoke-test.sh → Platform-specific generalization (only filtering) | |
| Capture | Deallocate → Mark VM as generalized → Create Managed Image (or Compute Gallery version, module 4) | StopInstances → CreateImage (EBS snapshot + AMI registration) → Wait for available |
| Clean up | Delete the entire temporary resource group | Terminate the instance and delete the temporary security group and key pair |
Multiple sources in the same build are built in parallel by default; -only='azure-arm.ubuntu' selects one of them (the name format is "builder type.source name").
When: What to put in the image and what to do at startup
| Put in the image (when building) | When starting (cloud-init / user data / configuration management) |
|---|---|
| Operating system patches, basic software packages, hardening baselines, monitoring/logging agents, Python Runtime and myapp dependencies, myapp code and systemd unit | Host name, environment-related configuration (Redis address, function switches), Secrets (obtained from Key Vault / Secrets Manager via managed identity), join cluster/registration |
waagent -deprovision+user Generalize (remove build users, host keys, DHCP leases, etc.) otherwise you will have identity/networking issues with VMs booted from the image. ③ "AWS Packer temporary key will disappear automatically" - the temporary key pair will be deleted from EC2, but the public key may remain in the image authorized_keys , which should be set ssh_clear_authorized_keys = true. ④ "With golden images, there is no need for patches" - images will also become old and need to be rebuilt regularly (for example, every week) in conjunction with the automatic security updates of Module 5. The generalization of this module is only minimal, and module 4 will complete it (machine-id, host key, log, reinforcement). Architecture diagram: one template, two clouds
Flowchart: Image life cycle (build → release → consume → obsolete)
Core Animation (Part 2): source → provisioning → generalization → capture → release version
Select the cloud platform and play, observe what Packer creates in the cloud, which APIs are called, when to clean up, and how to publish the product as a version after the build is successful (Azure Compute Gallery version / AMI tag + SSM Parameter pointer, see module 4 for details). Check "Inject faults" to see how Packer rolls back temporary resources on failure (default -on-error=cleanup) and will not release any version.
Core commands and parameters
| Command | Function | Key parameters |
|---|---|---|
packer build -only='azure-arm.ubuntu' -var-file=prod.pkrvars.hcl . | Build only the Azure part | Name format "builder type.source name" |
packer build -on-error=abort . | Retain temporary resources for troubleshooting in case of failure | Be sure to manually delete (RG / instance / SG / key pair) after troubleshooting |
az vm image list --publisher Canonical --offer ubuntu-26_04-lts --sku server --all -o table | Confirm Azure base image URN | There are also server-arm64, minimal and other SKUs |
aws ec2 describe-images --owners amazon --filters 'Name=name,Values=al2023-ami-2023.*-x86_64' | Confirm AL2023 basic AMI | Equivalent to source_ami_filter |
jq -r '.builds[] | [.builder_type,.artifact_id] | @tsv' manifest.json | Read product ID | Input for subsequent release/test scripts |
PACKER_LOG=1 PACKER_LOG_PATH=packer.log | Detailed log | Troubleshooting API/SSH issues |
Template: packer/sources.pkr.hcl (versions.pkr.hcl with variables.pkr.hcl Inherit module 2)
# ---------- Azure: Ubuntu 26.04 LTS → Managed Image ----------
source "azure-arm" "ubuntu" {
use_azure_cli_auth = true # Reuse the identity of az login
subscription_id = var.azure_subscription_id
location = "canadacentral"
vm_size = "Standard_B2s"
os_type = "Linux"
image_publisher = "Canonical"
image_offer = "ubuntu-26_04-lts"
image_sku = "server"
managed_image_name = "img-myapp-${var.app_version}-${local.stamp}"
managed_image_resource_group_name = "rg-linux-lab"
azure_tags = local.tags
}
# ---------- AWS: Amazon Linux 2023 → AMI ----------
source "amazon-ebs" "al2023" {
region = "ca-central-1"
instance_type = "t3.micro"
source_ami_filter {
filters = {
name = "al2023-ami-2023.*-x86_64"
architecture = "x86_64"
virtualization-type = "hvm"
root-device-type = "ebs"
}
owners = ["amazon"]
most_recent = true
}
ssh_username = "ec2-user"
ssh_clear_authorized_keys = true
temporary_security_group_source_public_ip = true # Default 0.0.0.0/0, tightened to the local public IP
ami_name = "myapp-${var.app_version}-${local.stamp}"
imds_support = "v2.0" # Instances launched from this AMI require IMDSv2 by default
metadata_options { # Building the instance itself only allows IMDSv2
http_endpoint = "enabled"
http_tokens = "required"
http_put_response_hop_limit = 1
}
tags = merge(local.tags, { Name = "linux-lab" })
run_tags = { Name = "packer-builder-linux-lab" }
}
build {
name = "myapp"
sources = ["source.azure-arm.ubuntu", "source.amazon-ebs.al2023"]
provisioner "shell" { # Wait for cloud-init to complete, avoid lock grabbing with apt/dnf
inline = ["cloud-init status --wait >/dev/null || true"] # Exit code 2 = with recoverable warning; just "wait" here
}
provisioner "file" {
source = "files/"
destination = "/tmp/myapp-src"
}
provisioner "shell" {
execute_command = "chmod +x {{ .Path }}; sudo env {{ .Vars }} bash '{{ .Path }}'"
environment_vars = ["APP_VERSION=${var.app_version}"]
scripts = ["scripts/install-myapp.sh", "scripts/smoke-test.sh"]
}
provisioner "shell" { # Azure generalization: must be the last step
only = ["azure-arm.ubuntu"]
execute_command = "chmod +x {{ .Path }}; sudo env {{ .Vars }} sh '{{ .Path }}'"
inline = ["/usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync"]
inline_shebang = "/bin/sh -x"
}
provisioner "shell" { # AWS: cleanup cloud-init status, new instance is reinitialized
only = ["amazon-ebs.al2023"]
inline = ["sudo cloud-init clean --logs"]
}
post-processor "manifest" {
output = "manifest.json"
strip_path = true
}
}
Azure managed image name must be one that does not yet exist, so timestamp; production recommendation is to publish to Azure Compute Gallery instead (shared_image_gallery_destination block, supports version number and multi-region replication). The Azure generalized writing method given in Packer's official documentation uses sudo -E sh; this lesson is changed to sudo env {{ .Vars }}..., because Ubuntu 26.04's default sudo-rs' support for environment variable retention is not exactly the same as traditional sudo, and the env method behaves the same on both.
Provisioning script: packer/scripts/install-myapp.sh
#!/usr/bin/env bash
# Run as root. Install myapp on Ubuntu (apt) and Amazon Linux 2023 (dnf).
set -Eeuo pipefail
trap 'echo "install-myapp: line $LINENO: $BASH_COMMAND" >&2' ERR
src=/tmp/myapp-src
. /etc/os-release
echo "==> installing myapp ${APP_VERSION:?} on $PRETTY_NAME"
case $ID in
ubuntu|debian)
export DEBIAN_FRONTEND=noninteractive
apt-get update -q
apt-get -y -q -o Dpkg::Options::=--force-confold upgrade
apt-get install -y -q python3-venv redis-server curl jq
redis_unit=redis-server.service ;;
amzn|rocky|almalinux|rhel)
dnf -y -q upgrade
dnf -y -q install python3 python3-pip valkey jq # AL2023: Redis 6 successor is Valkey
redis_unit=valkey.service ;;
*) echo "unsupported distro $ID" >&2; exit 1 ;;
esac
id myapp &>/dev/null || useradd --system --home-dir /opt/myapp --shell /usr/sbin/nologin myapp
install -d -o root -g root -m 0755 /opt/myapp /opt/myapp/app # Code in app/, venv in venv/ (Lesson 1/2 layout)
cp -r "$src/app/." /opt/myapp/app/
python3 -m venv /opt/myapp/venv
/opt/myapp/venv/bin/pip install -q --no-cache-dir -r /opt/myapp/app/requirements.txt
install -d -o root -g myapp -m 0750 /etc/myapp
install -o root -g myapp -m 0640 "$src/myapp.env" /etc/myapp/myapp.env
install -o root -g root -m 0644 "$src/myapp.service" /etc/systemd/system/myapp.service
echo "$APP_VERSION" > /opt/myapp/VERSION
systemctl daemon-reload
systemctl enable "$redis_unit" myapp.service
systemctl start "$redis_unit" myapp.service
#!/usr/bin/env bash
# Verify before image capture: service activity, port listening, /healthz returns 200
set -Eeuo pipefail
for i in {1..30}; do
if curl -fsS -o /dev/null http://127.0.0.1:5000/healthz; then
echo "==> smoke test OK after ${i}s ($(cat /opt/myapp/VERSION))"; break
fi
(( i == 30 )) && { journalctl -u myapp.service -n 50 --no-pager; exit 1; }
sleep 1
done
systemctl is-enabled myapp.service
systemctl stop myapp.service # Stop before capture to avoid entering the image with runtime status
rm -rf /tmp/myapp-src
How to verify:packer validate . Output The configuration is valid.; smoke test OK appears in the build log. Common mistakes: Adding other provisioners after Azure generalization (deprovision deletes the build user, SSH will fail in subsequent steps). Production use: Add packer fmt -check and packer validate to the CI of module 1 (module 2 experiment has been demonstrated); the build itself is run in the release pipeline with cloud credentials (OIDC).
Lab 3: Baking myapp into Azure image with AL2023 AMI (~15–25 minutes build time)
build_resource_group_name Points to an existing RG; AWS requires EC2 RunInstances/CreateImage/CreateKeyPair/CreateSecurityGroup, etc. (Packer documentation lists minimum IAM policies). Risk: The build instance temporarily opens port 22 - the default source of the amazon-ebs temporary security group is 0.0.0.0/0, which is set in the template of this lesson temporary_security_group_source_public_ip = true Only the current public IP of the build machine is allowed; available on Azure allowed_inbound_ip_addresses Restrictions. Be sure to perform the final cleanup step at the end of the experiment. cd ~/linuxlab/ops/packer mkdir -p files/app scripts sudo cp -r /opt/myapp/app/. files/app/ && sudo rm -rf files/app/__pycache__ sudo cp /etc/systemd/system/myapp.service files/ sudo cp /etc/myapp/myapp.env files/ sudo chown -R "$USER": files grep -n 'WorkingDirectory\|ExecStart\|EnvironmentFile\|SyslogIdentifier' files/myapp.service; cat files/myapp.env ls files/app
8:WorkingDirectory=/opt/myapp/app 9:EnvironmentFile=/etc/myapp/myapp.env 10:ExecStart=/opt/myapp/venv/bin/gunicorn --bind 0.0.0.0:5000 --workers 2 app:app 12:SyslogIdentifier=myapp PORT=5000 WORKERS=2 REDIS_URL=redis://127.0.0.1:6379/0 app.py requirements.txt templates
Confirm myapp.env There is no secret; if there is, delete it from the image version and inject it from Key Vault / Secrets Manager at startup (Lesson 3/4). Save the versions.pkr.hcl and variables.pkr.hcl of module 2 and the sources.pkr.hcl and build.pkr.hcl in the "Command" page of this module to the corresponding paths under ~/linuxlab/ops/packer (lab/ Subdirectories are configured independently and are not affected).
packer init . packer plugins installed packer fmt . # Align according to specifications (the pasted code alignment may be different, format it first and then submit) packer validate -var app_version=1.0.0 .
Installed plugin github.com/hashicorp/azure v2.6.5 in "/home/labadmin/.config/packer/plugins/github.com/hashicorp/azure/packer-plugin-azure_v2.6.5_x5.0_linux_amd64" Installed plugin github.com/hashicorp/amazon v1.8.4 in "/home/labadmin/.config/packer/plugins/github.com/hashicorp/amazon/packer-plugin-amazon_v1.8.4_x5.0_linux_amd64" /home/labadmin/.config/packer/plugins/github.com/hashicorp/amazon/packer-plugin-amazon_v1.8.4_x5.0_linux_amd64 /home/labadmin/.config/packer/plugins/github.com/hashicorp/azure/packer-plugin-azure_v2.6.5_x5.0_linux_amd64 The configuration is valid.
az login --use-device-code # If not logged in export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv) packer build -timestamp-ui -only='azure-arm.ubuntu' -var app_version=1.0.0 .
myapp.azure-arm.ubuntu: output will be in this color.
==> myapp.azure-arm.ubuntu: Running builder ...
==> myapp.azure-arm.ubuntu: Creating resource group ...
==> myapp.azure-arm.ubuntu: -> ResourceGroupName : 'pkr-Resource-Group-3xk9…'
==> myapp.azure-arm.ubuntu: -> Location : 'canadacentral'
==> myapp.azure-arm.ubuntu: Deploying deployment template ...
==> myapp.azure-arm.ubuntu: Waiting for SSH to become available...
==> myapp.azure-arm.ubuntu: Connected to SSH!
==> myapp.azure-arm.ubuntu: Provisioning with shell script: scripts/install-myapp.sh
myapp.azure-arm.ubuntu: ==> installing myapp 1.0.0 on Ubuntu 26.04.1 LTS
myapp.azure-arm.ubuntu: ==> smoke test OK after 3s (1.0.0)
==> myapp.azure-arm.ubuntu: Querying the machine's properties ...
==> myapp.azure-arm.ubuntu: Powering off machine ...
==> myapp.azure-arm.ubuntu: Generalizing machine ...
==> myapp.azure-arm.ubuntu: Capturing image ...
==> myapp.azure-arm.ubuntu: Deleting resource group ...
Build 'myapp.azure-arm.ubuntu' finished after 13 minutes 41 seconds.
==> Builds finished. The artifacts of successful builds are:
--> myapp.azure-arm.ubuntu: Azure.ResourceManagement.VMImage:
OSType: Linux
ManagedImageResourceGroupName: rg-linux-lab
ManagedImageName: img-myapp-1.0.0-20261117094512
ManagedImageId: /subscriptions/…/resourceGroups/rg-linux-lab/providers/Microsoft.Compute/images/img-myapp-1.0.0-20261117094512
ManagedImageLocation: canadacentralaws sts get-caller-identity --query Arn --output text packer build -timestamp-ui -only='amazon-ebs.al2023' -var app_version=1.0.0 . jq -r '.builds[] | [.builder_type, .artifact_id] | @tsv' manifest.json
==> myapp.amazon-ebs.al2023: Found Image ID: ami-0f1e2d3c4b5a69788
==> myapp.amazon-ebs.al2023: Creating temporary keypair: packer_673a…
==> myapp.amazon-ebs.al2023: Creating temporary security group for this instance: packer_673a…
==> myapp.amazon-ebs.al2023: Launching a source AWS instance...
myapp.amazon-ebs.al2023: ==> installing myapp 1.0.0 on Amazon Linux 2023…
myapp.amazon-ebs.al2023: ==> smoke test OK after 4s (1.0.0)
==> myapp.amazon-ebs.al2023: Stopping the source instance...
==> myapp.amazon-ebs.al2023: Creating AMI myapp-1.0.0-20261117100233 from instance i-0c…
==> myapp.amazon-ebs.al2023: Terminating the source AWS instance...
==> myapp.amazon-ebs.al2023: Deleting temporary security group...
==> myapp.amazon-ebs.al2023: Deleting temporary keypair...
--> myapp.amazon-ebs.al2023: AMIs were created:
ca-central-1: ami-0123456789abcdef0
azure-arm /subscriptions/…/images/img-myapp-1.0.0-20261117094512
amazon-ebs ca-central-1:ami-0123456789abcdef0AMI=$(jq -r '.builds[] | select(.builder_type=="amazon-ebs") | .artifact_id | split(":")[1]' manifest.json)
IID=$(aws ec2 run-instances --region ca-central-1 --image-id "$AMI" --instance-type t3.micro \
--metadata-options HttpTokens=required \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=linux-lab},{Key=purpose,Value=image-test}]' \
--query 'Instances[0].InstanceId' --output text)
aws ec2 wait instance-status-ok --region ca-central-1 --instance-ids "$IID"
# Check within the instance via SSM (lesson 4 when the instance profile has been configured; otherwise use SSH instead)
aws ssm send-command --region ca-central-1 --instance-ids "$IID" --document-name AWS-RunShellScript \
--parameters 'commands=["systemctl is-active myapp valkey","curl -s localhost:5000/healthz"]' \
--query Command.CommandId --output text
If The instance configuration file of lesson 4 (including AmazonSSMManagedInstanceCore) exists. You can add --iam-instance-profile Name=… to run-instances. Terminate immediately after verification: aws ec2 terminate-instances --region ca-central-1 --instance-ids "$IID".
# Azure: Delete managed image
az image list -g rg-linux-lab --query "[?tags.app=='myapp'].name" -o tsv \
| xargs -r -n1 az image delete -g rg-linux-lab -n
# AWS: Unregister AMI and delete its snapshot
for ami in $(aws ec2 describe-images --region ca-central-1 --owners self \
--filters Name=tag:app,Values=myapp --query 'Images[].ImageId' --output text); do
snaps=$(aws ec2 describe-images --region ca-central-1 --image-ids "$ami" \
--query 'Images[0].BlockDeviceMappings[].Ebs.SnapshotId' --output text)
aws ec2 deregister-image --region ca-central-1 --image-id "$ami"
for s in $snaps; do aws ec2 delete-snapshot --region ca-central-1 --snapshot-id "$s"; done
done
az group list --query "[?starts_with(name,'pkr-Resource-Group')].name" -o tsv # Should be empty
The lack of quotes here $(…) is intentional: the text output of the AWS CLI separates multiple IDs with whitespace and needs to be split (ShellCheck will prompt SC2046, you can comment out the exemption or use read -ra instead). You can also use --delete-associated-snapshots in AWS's deregister-image (supported by newer AWS CLI versions, confirm with aws ec2 deregister-image help before use).
Case 1: Cloud-init installation failed during the peak expansion period
Problem: During the major promotion period, ASG was expanded to 40 units at a time, and pip install in user data timed out due to PyPI current limiting. Half of the instances failed to pass the health check and were replaced repeatedly. Method: Bake the dependencies into the AMI, and only write environment-related configurations at startup; the image is rebuilt once a week and verified in staging. Configuration: This module template + launch template references the latest verified AMI ID (HCP Packer channel or SSM parameters read by Terraform). Restrictions: Dependencies in the image will also expire and require vulnerability scanning and regular rebuilding.
Case 2: Ungeneralized Azure image causes new VM to be unable to log in
Problem: Engineers manually installed the software in the VM and directly "captured" it, skipping deprovision. The new VM inherited the old host key and build user, and some VM network initialization exceptions occurred. Method: Only images are allowed to be produced through the Packer pipeline, and the last step is fixed to waagent -force -deprovision+user; the image definition in Azure Compute Gallery is marked as Generalized. Limitations:deprovision will delete the home directory of the last provisioned user and do not put files there that need to be retained.
Case 3: Image lineage and fast rollback
Problem: An OpenSSL update in the new image caused an old client handshake to fail, requiring a rollback and identification of all affected instances. Method: The image tag records version, base image and build pipeline run ID; use HCP Packer (hcp_packer_registry block) or self-built manifest (manifest.json uploaded to storage) to record lineage. Terraform refers to the image by "channel", and rollback = points the channel back to the previous version. Restrictions: HCP Packer is HashiCorp's hosted service (with a free tier) and requires an HCP account and service principal credentials.
Common errors and solutions
Error: Missing plugins — The following plugins are required, but not installed: github.com/hashicorp/azure ~> 2.6
Cause: packer init was not run, or the plug-in directory is different in another machine/CI.
packer init . && packer plugins installed
Fix: Each build in CI must be packer init (cacheable ~/.config/packer/plugins).
Build 'myapp.amazon-ebs.al2023' errored after …: Timeout waiting for SSH.
Cause: The built instance does not have a public IP (the default VPC is deleted and the subnet is not automatically assigned), the security group only allows the wrong source IP (the company's export NAT is inconsistent with the detected IP), or the proxy blocks port 22.
PACKER_LOG=1 packer build -only='amazon-ebs.al2023' -on-error=abort . 2>&1 | tee packer.log aws ec2 describe-subnets --region ca-central-1 --query 'Subnets[].[SubnetId,MapPublicIpOnLaunch]' --output table
Fix: Specify subnet_id and set associate_public_ip_address = true; or use ssh_interface = "session_manager" to connect over SSM (requires instance profile); explicitly allow egress IPs with temporary_security_group_source_cidrs. -on-error=abort will retain the resource for troubleshooting, and remember to delete it manually later.
Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1234 (apt)
Cause: On first startup cloud-init or unattended-upgrades is running apt, and the provisioning script is running apt at the same time.
Fixed: The first provisioner executes cloud-init status --wait (this lesson template is included); apt can add -o DPkg::Lock::Timeout=300 to wait for the lock to be released.
Azure: the managed image named img-myapp-1.0.0 already exists in the resource group rg-linux-lab
Reason: The managed image name must be unique, azure-arm will not overwrite the existing image.
Fix: Add a timestamp or build number to the name (already added to the template for this lesson); or use the Compute Gallery version number instead.
Error: Failed to prepare build: "azure-arm.ubuntu": … subscription_id must be set / AADSTS…
Reason: use_azure_cli_auth requires az login and the subscription can be confirmed; there is usually no interactive login in CI.
az account show --query '{sub:id, user:user.name}' -o table
Fix: Local settings ARM_SUBSCRIPTION_ID; use OIDC in CI (azure plugin supports client_id + oidc_request_url/oidc_request_token or client_jwt), see OIDC chapter of the GitHub/GitLab course.
1. Only build the AWS part, version number 1.4.2, retain temporary resources for troubleshooting in case of failure, and record detailed logs to files.
PACKER_LOG=1 PACKER_LOG_PATH=packer-debug.log \ packer build -only='amazon-ebs.al2023' -var app_version=1.4.2 -on-error=abort .
2. List all myapp AMIs in your account in ca-central-1, displaying the ID, name and date in reverse order of creation time.
aws ec2 describe-images --region ca-central-1 --owners self --filters Name=tag:app,Values=myapp \ | jq -r '.Images | sort_by(.CreationDate) | reverse[] | [.ImageId, .Name, .CreationDate] | @tsv'
The security team requires that "all production VMs must contain the latest security patches within 30 days", and you use golden images + immutable deployment. Please design an image and patch strategy that meets the requirements.
① The image pipeline is rebuilt regularly (for example, every week) from the latest platform base image, a complete upgrade is performed in provisioning, and after passing the CVE scan, it is published to the Compute Gallery/shared AMI, and the "channel" is updated; ② The deployment pipeline replaces instances on a weekly basis (instance refresh of VMSS/ASG) to ensure that the image age of running instances is < 30 days; ③ Between rebuilds, keep unattended-upgrades / dnf-automatic on the instance to install only security updates (module 5) as a defense in depth; ④ Use Azure Update Manager / AWS Systems Manager Patch Manager to report compliance; ⑤ Emergency CVEs take the "immediate rebuild + accelerated rolling" channel. Trade-off: Immutable replacement requires application statelessness and load balancing health checks.
Verified teaching video
Official documentation
- Packer documentation · Releases (1.16.2)
- Azure ARM builder · packer-plugin-azure
- Amazon EBS builder · packer-plugin-amazon
- Canonical: Find Ubuntu images on Azure(ubuntu-26_04-lts) · AL2023: Redis 6 → Valkey
Video storyboard script (about 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: The progress bar of a new VM on the left slowly apt install, pip install after startup; the VM started from the golden image on the right turns green in a few seconds.
Narration: The installation at startup is slow and unreliable. If the software is baked into the image in advance, the new instance can be online in a few seconds.
Screen: The HCL template is divided into four highlighted parts: packer, variable, source, build; two sources are forked to Azure and AWS.
Narration: One template, two builders: azure-arm and amazon-ebs, share the same set of provisioning scripts.
Screen: Temporary resource group, temporary key pair, and security group appear → Provision → Generalize → Capture → Temporary resources disappear, leaving only the image and AMI.
Narration: Packer creates temporary machines, provisions, generalizes, captures, and cleans up all temporary resources.
Screen: Mirror version timeline, the old version is logged out and the snapshot is deleted.
Narration: Images have versions and lifespans. They are rebuilt regularly and eliminated on time.
Module 4 · Image generalization, reinforcement and version management
- List the "instance identities and status" that must be cleared in the image (cloud-init status, machine-id, SSH host key, build user and public key, logs and history, random seeds), explain the consequences of missing each item, and write
generalize.sh. - Explains why you should do CIS style hardening (SSH, sysctl, redundant packages, auditd, journald) when baking and how to verify it in the build; full baseline link to Lesson 6.
- Use Azure Compute Gallery (Library → Image Definition → Image Version
MAJOR.MINOR.PATCH, Target Region,exclude_from_latest, End of Life Date) with AMI Naming / Tags / Deprecation / SSM Parameter pointersManage the image life cycle and understand the release and rollback of immutable infrastructure.
What: What is cleared by generalization
| Residues | Location | The consequences of not clearing | How to clear |
|---|---|---|---|
| cloud-init status and seed | /var/lib/cloud/, /var/log/cloud-init*.log | The instance-id of the new instance is different, and the per-instance module will usually rerun; but the remaining old data, logs and seeds will mislead troubleshooting, and the custom seed will even overwrite the new data source | cloud-init clean --logs --seed |
| machine-id | /etc/machine-id (/var/lib/dbus/machine-id is usually a link to it) | All clones have the same ID: systemd-networkd's DHCP DUID is derived from it, which may cause address conflicts; journald logs are distinguished by _MACHINE_ID, and the centralized log and monitoring agent will treat multiple machines as one | cloud-init clean --machine-id (write uninitialized, systemd will generate a new value at the next startup) |
| SSH host key | /etc/ssh/ssh_host_* | All instances share the same private key: leaking one can impersonate them all; client known_hosts are confused | Delete (must be in the last step); cloud-init's ssh module is rebuilt when a new instance is first started (ssh_deletekeys is enabled by default); Azure is deleted by waagent |
| Build user and temporary public key | Packer's SSH user, ~/.ssh/authorized_keys | The private key of the build machine can log in to all instances | Azure: waagent -force -deprovision+user; AWS: ssh_clear_authorized_keys = true |
| Logs, journals, shell history, temporary files | /var/log, /var/log/journal, ~/.bash_history, /tmp | The logs of the build process are mixed into the production instance; may contain build parameters or internal addresses | journalctl --rotate + --vacuum-time=1s, truncate text log, delete history |
| Random seed, package cache | /var/lib/systemd/random-seed, apt/dnf cache | The initial entropy seeds of the clones are the same (systemd New entropy will be mixed in, but should not be relied upon); the image size becomes larger | Delete the seed file; apt-get clean / dnf clean all |
Why: Why "mirror" cannot be equal to "snapshot of a certain machine"
Snapshot retains the complete identity of a machine, while the image is a template for a type of machine. A lot of identity information on Linux is generated during the first startup (machine-id, SSH host key, cloud-init instance record). Generalization is to delete these "first startup products" and let each clone go through the first startup again. Azure also requires the image to be marked Generalized (Packer does this via the API after deprovision), otherwise the normal provisioning process will not run when creating a VM from a managed image.
How: Sequence in Build
- Install myapp (
install-myapp.shfor module 3). - Hardening (
harden.sh): SSH drop-in, sysctl, removal of redundant software packages, auditd, journald storage limit; usesshd -t,sysctl --systemto verify on the spot. The complete CIS baseline, SELinux/AppArmor, nftables, auditd rules can be found in Lesson 6 · Module 1 and its subsequent modules. - Smoke test (run after hardening to prove that the hardening did not damage the application).
- Generalize (
generalize.sh, last provisioner): Package cache →cloud-init clean --logs --seed --machine-id→ Random seeds → Logs and history → SSH host keys → Last execution on Azurewaagent -force -deprovision+user. - The builder captures and then publishes the Compute Gallery version/AMI with the label and deprecation time, and updates the "latest available" pointer.
When: Version Management and Immutable Infrastructure
| Azure Compute Gallery | AWS AMI | |
|---|---|---|
| Hierarchy | Library gallinuxlab → Image Definition myapp (Publisher/Product/SKU, Linux, Generalized, Gen2) → Image Version 1.0.0 | Each AMI is an independent object: the name is unique within the region and cannot be modified, and labels are used to express version and lineage |
| Version number | Must be MAJOR.MINOR.PATCH (integer) | Write in the name myapp-1.0.0-timestamp and label version=1.0.0 |
| "latest" pointer | Quote the image definition (without version) to get the latest version; exclude_from_latest prevents a certain version from participating in the "latest" | There is no built-in pointer: use the SSM parameter (--data-type aws:ec2:image) to save the "verified AMI" and start the template with resolve:ssm: Reference |
| Multiple regions | target_region Copy and set number of copies | ami_regions Copy (one new AMI ID per region) |
| Expiration | Life cycle end date (end of life, only prompt, not automatically deleted) | deprecate_at: hidden from others after expiration, not deleted; can still be started with ID |
| Anti-accidental deletion | Resource lock | Deregistration protection (deregistration_protection) |
Immutable infrastructure: Running instances are not modified in place, and any changes (patches, configurations, application versions) are completed through "Build a new image → Verify → Release version → Rolling replacement instance (VMSS rolling upgrade / ASG instance refresh)"; rollback means pointing the pointer back to the previous version and rolling it again. It requires applications to be stateless, with health checks and load balancing, and stateful services and emergency repairs still require configuration management (Module 6).
/etc/machine-id file" - empty or missing files will cause an error in the read-only root file system at startup on some systems; use cloud-init clean --machine-id to write uninitialized More secure. ② "The host key can be deleted at any time" - after deletion, sshd cannot accept new connections and must be placed in the last step. ③ "Reinforcement should be done by a script after the instance is started" - then each instance will have an unreinforced window, and the results will be inconsistent; the identified reinforcement items should be completed during baking. ④ "AMI deprecation = delete" - deprecation is just hiding and prompting, snapshots are still being billed, and snapshots need to be logged out and deleted separately (Module 8). ⑤ "Gallery's latest is always the last one built" - it is the version with the "highest version number and not excluded". Wrong version numbers (such as 1.10.0 and 1.9.0) will directly affect new instances. Flowchart: from installation to release
Illustration: two clones of the same image
Interactive simulator: first startup of the clone
Check the cleanup items you made in generalize.sh, and then play: Start from the same image vm-a and vm-b and see what problems each missing item will cause after first boot (red). When all are checked, the identities of the two machines should be completely independent.
Core commands
| Commands | Function | Description |
|---|---|---|
cloud-init clean --logs --seed --machine-id | Clear cloud-init status, logs, seeds and reset machine-id | cloud-init 26.1; --configs can delete the generated network/SSH configuration |
waagent -force -deprovision+user | Generalization of Azure Linux Agent | Remove last provisioned users, host keys, DHCP leases, etc.; no more SSH steps can follow |
az sig create / image-definition create / image-version list|update|delete | Compute Gallery Management | Library names can only contain letters, numbers, dots, and underscores |
aws ec2 enable-image-deprecation --deprecate-at | Set deprecation time for existing AMI | Packer's deprecate_at |
aws ssm put-parameter --data-type aws:ec2:image | Save the "latest verified AMI" pointer | Check whether the value is valid when writing AMI; parameters have version history for easy rollback |
Reinforcement during baking: packer/scripts/harden.sh
#!/usr/bin/env bash
# harden.sh - Applies a small amount of CIS style hardening when baking; see Lesson 6 for full baseline. Run as root.
set -Eeuo pipefail
. /etc/os-release
echo "==> hardening $PRETTY_NAME"
# SSH: sshd takes the "first occurrence of the value" for the same option, and the 10- prefix makes this file take effect before cloud-init's 50-cloud-init.conf
install -d -m 0755 /etc/ssh/sshd_config.d
cat > /etc/ssh/sshd_config.d/10-linuxlab-hardening.conf <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
X11Forwarding no
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
EOF
sshd -t # Configuration errors fail immediately to prevent bad images from being produced
# Kernel network parameters
cat > /etc/sysctl.d/60-linuxlab-hardening.conf <<'EOF'
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.tcp_syncookies = 1
kernel.kptr_restrict = 2
EOF
sysctl --system >/dev/null
# Remove unnecessary plaintext protocol clients; install audit daemon
case $ID in
ubuntu|debian)
export DEBIAN_FRONTEND=noninteractive
for p in telnet ftp rsh-client; do
if dpkg -s "$p" &>/dev/null; then apt-get purge -y -q "$p"; fi
done
apt-get install -y -q auditd ;;
*) dnf -y -q install audit ;;
esac
systemctl enable auditd.service
# journald: persist and limit occupancy (see module 7 for log forwarding)
install -d -m 0755 /etc/systemd/journald.conf.d
printf '[Journal]\nStorage=persistent\nSystemMaxUse=500M\n' > /etc/systemd/journald.conf.d/50-linuxlab.conf
echo "==> hardening done"
Generalization: packer/scripts/generalize.sh
#!/usr/bin/env bash
# generalize.sh - Generalize before capture. Must be the last provisioner (no further SSH connections can be established).
# Environment variable CLOUD: azure-arm | amazon-ebs (source.type passed in by Packer)
set -Eeuo pipefail
echo "==> generalizing for ${CLOUD:?}"
if command -v apt-get >/dev/null; then
apt-get -y -q autoremove --purge; apt-get -q clean; rm -rf /var/lib/apt/lists/*
else
dnf -q clean all
fi
cloud-init clean --logs --seed --machine-id # /etc/machine-id → "uninitialized"
rm -f /var/lib/systemd/random-seed
journalctl --rotate
journalctl --vacuum-time=1s
find /var/log -path /var/log/journal -prune -o -type f \
\( -name '*.gz' -o -name '*.[0-9]' -o -name '*.old' \) -print0 | xargs -0 -r rm -f
find /var/log -path /var/log/journal -prune -o -type f -print0 | xargs -0 -r truncate -s 0
rm -f /root/.bash_history /home/*/.bash_history
rm -rf /tmp/* /var/tmp/*
echo "==> machine-id now: $(cat /etc/machine-id)"
rm -f /etc/ssh/ssh_host_* # Rebuilt by cloud-init when the new instance is first started
sync
if [[ $CLOUD == azure-arm ]]; then # Azure: delete the build user, etc., must be executed last
/usr/sbin/waagent -force -deprovision+user
sync
fi
build.pkr.hcl: string together three scripts (replace the last two of module 3) provisioner)
provisioner "shell" {
execute_command = "chmod +x {{ .Path }}; sudo env {{ .Vars }} bash '{{ .Path }}'"
environment_vars = ["APP_VERSION=${var.app_version}"]
scripts = ["scripts/install-myapp.sh", "scripts/harden.sh", "scripts/smoke-test.sh"]
}
provisioner "shell" { # The last step: generalization (Azure includes waagent)
execute_command = "chmod +x {{ .Path }}; sudo env {{ .Vars }} bash '{{ .Path }}'"
environment_vars = ["CLOUD=${source.type}"]
script = "scripts/generalize.sh"
}
sources.pkr.hcl: published as version (replaces Azure's managed_image_*, adds deprecation and lineage tags to AWS)
# source "azure-arm" "ubuntu": delete managed_image_name / managed_image_resource_group_name and change to
shared_image_gallery_destination {
subscription = var.azure_subscription_id
resource_group = "rg-linux-lab"
gallery_name = "gallinuxlab"
image_name = "myapp"
image_version = var.app_version # Must be MAJOR.MINOR.PATCH (verification rule of module 2)
target_region {
name = "canadacentral"
}
}
shared_gallery_image_version_end_of_life_date = timeadd(timestamp(), "4320h") # 180 days
shared_gallery_image_version_exclude_from_latest = false
# Add/replace in source "amazon-ebs" "al2023"
ami_description = "myapp ${var.app_version} on Amazon Linux 2023"
deprecate_at = timeadd(timestamp(), "2160h") # Deprecated after 90 days (not deleted)
tags = merge(local.tags, {
Name = "linux-lab"
base_ami_name = "{{ .SourceAMIName }}" # Build template data provided by the plug-in: base AMI name
})
snapshot_tags = merge(local.tags, { Name = "linux-lab" })
How to verify:packer validate . passed; machine-id now: uninitialized appears at the end of the build log. Common errors: The build will fail if the same version number already exists in Gallery - the version number must be incremented; the OS status defined by the image must be Generalized, and the Hyper-V generation must be consistent with the base image (ubuntu-26_04-lts:server is Gen2). Production use: The version number comes from the Git tag or release pipeline; deregistration_protection { enabled = true } prevents the production AMI from being accidentally deleted.
Experiment 4: Release version 1.0.0 after generalization + hardening (about 20 minutes, including build wait)
harden.sh, generalize.sh to ~/linuxlab/ops/packer/scripts/ and modify it by fragment build.pkr.hcl With sources.pkr.hcl:
cd ~/linuxlab/ops/packer shellcheck scripts/*.sh && packer fmt . && packer validate -var app_version=1.0.0 .
The configuration is valid.
az sig create -g rg-linux-lab -r gallinuxlab -l canadacentral -o none
az sig image-definition create -g rg-linux-lab -r gallinuxlab -i myapp \
--publisher linuxlab --offer myapp --sku ubuntu-26_04 \
--os-type Linux --os-state Generalized --hyper-v-generation V2 \
--features SecurityType=TrustedLaunchSupported -o none
az sig image-definition list -g rg-linux-lab -r gallinuxlab --query "[].{name:name, os:osState, gen:hyperVGeneration}" -o table
Name Os Gen ------ ----------- ----- myapp Generalized V2
export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
packer build -timestamp-ui -var app_version=1.0.0 . 2>&1 | tee build-1.0.0.log | grep -E 'generaliz|machine-id|Build|ami-|Gallery'
az sig image-version list -g rg-linux-lab -r gallinuxlab -i myapp \
--query "[].{ver:name, state:provisioningState, eol:publishingProfile.endOfLifeDate, excluded:publishingProfile.excludeFromLatest}" -o table
aws ec2 describe-images --region ca-central-1 --owners self --filters Name=tag:app,Values=myapp \
--query 'Images[].[ImageId,Name,DeprecationTime,Tags[?Key==`base_ami_name`]|[0].Value]' --output text
myapp.azure-arm.ubuntu: ==> generalizing for azure-arm
myapp.azure-arm.ubuntu: ==> machine-id now: uninitialized
myapp.amazon-ebs.al2023: ==> generalizing for amazon-ebs
myapp.amazon-ebs.al2023: ==> machine-id now: uninitialized
Build 'myapp.amazon-ebs.al2023' finished after 11 minutes 2 seconds.
Build 'myapp.azure-arm.ubuntu' finished after 17 minutes 40 seconds.
Ver State Eol Excluded
----- --------- ------------------------- ----------
1.0.0 Succeeded 2027-05-16T10:02:11+00:00 False
ami-0123456789abcdef0 myapp-1.0.0-20261117100233 2027-02-15T10:02:00.000Z al2023-ami-2023.9.20261110.0-kernel-6.12-x86_64AMI=$(jq -r '.builds[] | select(.builder_type=="amazon-ebs") | .artifact_id | split(":")[1]' manifest.json | tail -1)
aws ssm put-parameter --region ca-central-1 --name /linux-lab/myapp/ami/latest \
--type String --data-type aws:ec2:image --value "$AMI" --overwrite
aws ssm get-parameter-history --region ca-central-1 --name /linux-lab/myapp/ami/latest \
--query 'Parameters[].[Version,Value]' --output text
{
"Version": 1,
"Tier": "Standard"
}
1 ami-0123456789abcdef0--image-id "$AMI" Similarly), compare the identity information:
DEF=$(az sig image-definition show -g rg-linux-lab -r gallinuxlab -i myapp --query id -o tsv)
for n in a b; do
az vm create -g rg-linux-lab -n vm-img-$n --image "$DEF" --size Standard_B2s \
--admin-username labadmin --generate-ssh-keys --public-ip-sku Standard -o none
done
for n in a b; do
az vm run-command invoke -g rg-linux-lab -n vm-img-$n --command-id RunShellScript \
--scripts 'cat /etc/machine-id; ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub; journalctl --list-boots --no-pager | wc -l; cat /opt/myapp/VERSION; systemctl is-active myapp' \
--query 'value[0].message' -o tsv
done
[stdout] 91c0d2… 256 SHA256:a7Z… root@vm-img-a (ED25519) 1 1.0.0 active [stdout] 0be4f7… 256 SHA256:k2P… root@vm-img-b (ED25519) 1 1.0.0 active
The machine-id of the two machines is different from the host key fingerprint, there is only one startup record, and myapp is active when it is powered on, which means it has passed the acceptance. Delete the test VM immediately after verification: az vm delete -g rg-linux-lab -n vm-img-a --yes (b is the same; the associated disks, NICs, and public IPs are cleaned up in module 8). --features SecurityType=TrustedLaunchSupported makes this version of the definition available for both standard and trusted launch VMs; if your subscription policy requires other security types, adjust as per the Azure documentation.
Case 1: Only 1 of 50 clones is displayed in the monitoring
Problem: The hand-made "template VM snapshot" does not reset the machine-id. All instances reported to the monitoring and centralized log platform have the same host ID. Alarms and logs are merged, making it completely indistinguishable during troubleshooting. Some instances also have address conflicts on IPv6 due to the same DHCP DUID. Method: Images are only allowed to be produced by the Packer pipeline. generalize.sh is fixed as the last step. The acceptance use case checks that the machine-id and host key of the two clones are different. Limitations: After machine-id is reset, software that relies on it (certain licenses, agent registration) needs to be re-registered on first startup.
Case 2: Hardening is performed after startup, leaving a 5-minute window
Issue: The security baseline is pushed by configuration management after startup, new instances allow password logins before the first run, and the scanner detects a large number of brute force attempts during this time. Method: The identified hardening items (SSH, sysctl, software packages, auditd) are completed during baking and verified with sshd -t; configuration management is only responsible for "maintaining" the environment-related parts (Module 6). Restrictions: Some CIS items will affect applications (such as mount options, firewalls), and application testing must be run in the image pipeline; see Lesson 6 for complete baseline and exception management.
Case 3: The wrong "latest version" was pulled up by automatic expansion
Problem: Someone manually released a test version 2.0.0 to the production library, VMSS referenced the image definition (the latest version), and all new instances used unverified images during expansion. Method: Set exclude_from_latest when the test version is released, and then cancel it after passing the verification; or let VMSS refer to the specific version and update it by the release pipeline; AWS only updates SSM parameters after verification. Limitations: The "latest" pointer is convenient but dangerous, production usually references the version explicitly and is pushed by the pipeline.
Common errors and solutions
Build failed after generalization: ssh: handshake failed / Timeout waiting for SSH
Reason: After deleting the SSH host key or waagent -deprovision+user and then scheduling a new SSH The steps to connect (another provisioner, reconnect after expect_disconnect, etc.).
Fix: Put generalize.sh at the end; steps that require file download (direction = "download") are moved before it.
VM created from image: ssh: Connection refused, serial console shows sshd: no hostkeys available -- exiting
Reason:The host key was deleted, but the new instance was not rebuilt when it was first started: cloud-init was not running (data source identification failed), ssh_deletekeys / ssh_genkeytypes is turned off by custom configuration, or the image is used in an environment without cloud-init.
cloud-init status --long; grep -rn 'ssh_deletekeys\|ssh_genkeytypes' /etc/cloud/ sudo ssh-keygen -A && sudo systemctl restart ssh # Temporary recovery (Ubuntu service name is ssh)
Fix: Restore the default ssh module configuration of cloud-init; do not delete the host key for images without cloud-init, or provide the first unit to generate the key (RHEL system has sshd-keygen@.service).
Azure: The gallery image version 1.0.0 already exists / Conflict
Reason:The version number must be unique under the same image definition.
az sig image-version list -g rg-linux-lab -r gallinuxlab -i myapp --query "[].name" -o tsv
Fix: Increment app_version; if you really need to rebuild the same version, delete the old version first (not recommended for production).
Azure: OS state / Hyper-V generation / security type of the image version does not match the image definition
Cause:The image definition was created as Specialized or V1, which is inconsistent with the generalized Gen2 base image; or the security type defined is incompatible with the build VM.
Fix: Rebuild image definition (--os-state Generalized --hyper-v-generation V2, adjust --features if necessary); most properties cannot be modified once the definition is created.
AWS: InvalidParameterValue — deprecate_at / DeprecateAt must be in the future
Cause: The time format is incorrect (requires YYYY-MM-DDTHH:MM:SSZ, UTC), is earlier than the current time, or exceeds the 10-year upper limit.
Fixed: Use timeadd(timestamp(), "2160h") to generate; when setting manually, use date -u -d '+90 days' +%Y-%m-%dT%H:%M:%SZ.
1. Temporarily exclude version 1.1.0 from the Gallery as "latest", and then list all versions and their exclusion status.
az sig image-version update -g rg-linux-lab -r gallinuxlab -i myapp -e 1.1.0 \
--set publishingProfile.excludeFromLatest=true -o none
az sig image-version list -g rg-linux-lab -r gallinuxlab -i myapp \
--query "[].{ver:name, excluded:publishingProfile.excludeFromLatest}" -o table2. AWS rollback: Change the SSM pointer back to the previous version of the AMI.
PREV=$(aws ssm get-parameter-history --region ca-central-1 --name /linux-lab/myapp/ami/latest \ --query 'Parameters[-2].Value' --output text) aws ssm put-parameter --region ca-central-1 --name /linux-lab/myapp/ami/latest \ --type String --data-type aws:ec2:image --value "$PREV" --overwrite
Audit requirements "Be able to answer when any production instance was built, which base image, and which Git submitted the output." Please design the metadata scheme of the image.
① When building, write app_version, Git commit SHA, pipeline run ID, and basic image name into the image tag (AMI tags / snapshot_tags, Azure version tag) and the file in the image (such as /etc/myapp-image.json, module 6 It is also used as a drift baseline); ② manifest.json and build logs are archived as pipeline products; ③ On the instance side: Azure's VM properties have storageProfile.imageReference (including Gallery version), AWS instances have ImageId, and then press the image tag to check; ④ Optional HCP Packer records the pedigree in a unified way; ⑤ Disable hand-made images (policy: only allow images from specified Gallery/account).
Verified teaching video
Official document
- cloud-init CLI(clean) · machine-id(5) · Azure Linux VM Agent(deprovision)
- Azure Compute Gallery · az sig image-version
- EC2: AMI Deprecation · AMI ID in SSM parameters (aws:ec2:image)
- Plugin parameters: packer-plugin-azure(shared_image_gallery_destination) · packer-plugin-amazon (deprecate_at, deregistration_protection) · Reinforcement in depth: Lesson 6
Video storyboard script (about 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: One machine was copied into two, with the same machine-id and the same key on their foreheads. Only one host is displayed on the large monitoring screen.
Narration: An image is not a snapshot of a certain machine, but a template for a type of machine. No generalization, all clones share the same identity.
Screen: The cleanup list is ticked one by one: cloud-init status, machine-id, logs, history, and finally the host key and build user, with the words "last step" flashing.
Narration: Generalization is the last provisioning step. After the host key is deleted, no new connections can be established.
Screen: Version shelves lined with 1.0.0, 1.1.0, 1.2.0, a "latest" pointer moving between them; the AMI on the other side has a deprecation date posted in ninety days.
Narration: The image must have a version, a pointer, and a lifespan. Publishing means moving the pointer, and rolling back means pointing the pointer back.
Module 5 · Patch Automation: unattended-upgrades, dnf-automatic and maintenance windows
- Understand Ubuntu automatic update link:
apt-daily.timer→apt-daily-upgrade.timer→unattended-upgrade(source filtering, blacklisting) → needrestart → Optional automatic restart. - Configure "install only security updates + fixed restart window + exclude critical packages + logs can be checked", and use
--dry-runto verify; use dnf-automatic or cloud patch service on RHEL system/AL2023 to achieve equivalent goals. - Develop restart strategy: service restart mode of needrestart,
reboot-requiredof kernel update, automatic restart time and grouping, and what Livepatch / kpatch can and cannot do. - Use systemd timer and cloud service to implement maintenance window, distinguish between "stand-alone automatic patching" and "cloud platform patch orchestration (Azure Update Manager / SSM Patch Manager), Configuration Management (Module 6), and Image Rebuilding (Modules 3–4).
What: Automatic updates that come with the distribution
| Ubuntu(linuxlab) | Rocky / RHEL(rhellab) | Amazon Linux 2023 | |
|---|---|---|---|
| Component | unattended-upgrades (Server is installed and enabled by default) | dnf-automatic (requires installation) | dnf; defaultLock repository version (deterministic upgrade) |
| Scheduling | apt-daily.timer (update list/download), apt-daily-upgrade.timer (installation) | dnf-automatic.timer (by configuration) or -install / -download / -notifyonly variant | Requires self-arrangement (SSM Patch Manager recommended) |
| Configuration | /etc/apt/apt.conf.d/20auto-upgrades, 50unattended-upgrades | /etc/dnf/automatic.conf | /etc/dnf/vars/releasever, dnf check-release-update |
| Install only security updates | Allowed-Origins Keep only -security (this is the default) | upgrade_type = security | dnf upgrade --security (requires the repository to provide security advisory metadata) |
| Reboot | Automatic-Reboot + Automatic-Reboot-Time | reboot = when-needed (automatic.conf of dnf 4) | needs-restarting -r Restart automatically after judgment |
| Log | /var/log/unattended-upgrades/, /var/log/dpkg.log, journalctl -u apt-daily-upgrade | journalctl -u dnf-automatic*, dnf history | dnf history |
Why: Most intrusions exploit disclosed and fixed vulnerabilities
The window from patch release to large-scale exploitation is often only a few days. Manual patching once a month cannot keep up; but "fully automatic installation of everything" may upgrade the database to an incompatible major version in the early morning. The compromise is: Automatically install security updates, Function updates go through the change process (or through image reconstruction, modules 3–4), Restart in a fixed window, Key packages can be excluded, and The results can be audited.
How: Ubuntu execution chain
apt-daily.timer(twice a day, with a large random delay to disperse the pressure on the mirror site) triggersapt-daily.service:apt update, and pre-downloads upgradeable packages according to configuration.apt-daily-upgrade.timer(every morning, with a random delay) triggersapt-daily-upgrade.service, runningunattended-upgrade.unattended-upgradeRead the configuration, select only packages whose sources matchAllowed-Origins/Origins-Patternand are not inPackage-Blacklist, and call dpkg after calculating dependencies Installation; configurable batching (MinimalSteps) to safely stop when a shutdown signal arrives.- After a library update, needrestart detects services still using the old library and restarts them (automatically/listed by configuration in non-interactive mode); kernel or core library updates create
/var/run/reboot-required. - If
Automatic-Reboot "true", plan a restart atAutomatic-Reboot-Time(you can setAutomatic-Reboot-WithUserswhether to restart when there is a logged-in user).
How (continued): Restart strategy
| What is updated | When does it take effect | How to do |
|---|---|---|
| Normal programs (such as curl) | Next time you run | No need to process |
| Shared libraries (libraries other than OpenSSL and glibc) | Use its service restart after | needrestart to detect processes still mapping old libraries: $nrconf{restart} lists only for 'l', 'i' for interactive queries, 'a' Automatic restart; it is recommended to explicitly set it to 'a' on the server, and use $nrconf{override_rc} to exclude services that cannot be restarted at will |
| core components such as kernel, glibc, systemd | After host restart | Appears /var/run/reboot-required; automatically restarts in the maintenance window according to the policy (Automatic-Reboot / dnf-automatic reboot = when-needed) or leaves it to the platform for orchestration |
| Some high-risk vulnerabilities in the kernel | Immediately (without restarting) | Livepatch (Ubuntu Pro: pro enable livepatch, free for up to 5 individuals), kpatch (RHEL subscription; AL2023 also provides Kernel Live Patching). They only cover selected vulnerabilities and have a support period, not a replacement for regular reboots to the new kernel |
When: Maintenance windows and division of labor
| Hierarchies | Tools | How to implement maintenance window | Suitable |
|---|---|---|---|
| Single-machine automatic patch | unattended-upgrades / dnf-automatic | systemd timer drop-in (OnCalendar=) determines the installation time, Automatic-Reboot-Time Determine restart time; stagger different host groups at different times | Baseline protection for all servers; the main means for small-scale environments |
| Platform patch orchestration | Azure Update Manager (maintenance configuration: schedule, classification, restart settings IfRequired / Never / Always) · AWS SSM Patch Manager (patch baseline + maintenance window run AWS-RunPatchBaseline, RebootOption = RebootIfNeeded / NoReboot) | The platform is installed and restarted uniformly within the window, and a compliance report is generated | Compliance, batching, approval across subscriptions/accounts |
| Configuration and change management | Ansible (rolling serial, remove it from load balancing, and continue after health check) | Playbook is executed in batches within the window | Need to arrange sequential upgrades (cluster, database), and uniformly deliver the configuration file of this module (module 6) |
| Mirror reconstruction | Packer (modules 3–4) + rolling replacement | Build new versions weekly, replace instances according to release cadence | Immutable deployment; feature updates and major version upgrades |
Do not let two sets of mechanisms "responsible for installation and restart" on the same host at the same time (such as local unattended-upgrades automatic restart + Update Manager scheduled restart), otherwise a restart will occur outside the window. Common combination: The machine only installs security updates but does automatically restart. The restart is orchestrated by the platform maintenance window or Ansible.
/var/run/reboot-required and schedule a restart. ② "Automatic updates will upgrade to the new Ubuntu version" - No, the release upgrade is the responsibility of do-release-upgrade . ③ “AL2023 on dnf upgrade Can get all the latest patches" - AL2023 is locked to a certain repository version by default. Updates in the new version repository require --releasever=latest or update releasever; this is the deterministic upgrade design of AL2023. ④ "The configuration file is directly changed 50unattended-upgrades Just fine" - a configuration conflict prompt may occur during package upgrade; it is easier to maintain if you put the customization in a later file (such as 52unattended-upgrades-local), and the same option will be read later to take effect.Architecture diagram: Ubuntu automatic security update link
Hierarchical diagram: stand-alone → platform → configuration management
Interactive Simulator: A Day in the Life of Autopatch
Select the type of update released that day and play the complete systemd timer-driven process. The terminal below displays the corresponding log (/var/log/unattended-upgrades/unattended-upgrades.log, journald).
Core commands and parameters
| Command | Function | Description |
|---|---|---|
systemctl list-timers 'apt-daily*' | View the next trigger time | Override time: systemctl edit apt-daily-upgrade.timer |
sudo unattended-upgrade --dry-run --debug | Preview, do not install | Show allowed sources, candidate packages, excluded packages |
apt-config dump | grep -i unattended | View the effective configuration after merging | Merging results of multiple conf.d files |
cat /var/run/reboot-required.pkgs | Which packages require restarting | A restart is required if the file exists |
sudo needrestart -b / -r l | Batch mode lists services/kernels that need to be restarted | Suitable for scripting and monitoring |
sudo dnf install dnf-automatic, systemctl enable --now dnf-automatic.timer | RHEL system automatically updates | dnf updateinfo list --security View security bulletins |
dnf check-release-update(AL2023) | Is there an updated repository version | sudo dnf upgrade --releasever=latest |
Ubuntu: only install security updates, exclude redis-server, restart at 03:30
sudo tee /etc/apt/apt.conf.d/20auto-upgrades >/dev/null <<'EOF'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
EOF
sudo tee /etc/apt/apt.conf.d/52unattended-upgrades-local >/dev/null <<'EOF'
// Local coverage: read order after 50unattended-upgrades
Unattended-Upgrade::Package-Blacklist { "redis-server"; };
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-WithUsers "false";
Unattended-Upgrade::Automatic-Reboot-Time "03:30";
Unattended-Upgrade::SyslogEnable "true";
EOF
apt-config dump | grep -E 'Unattended-Upgrade::(Automatic-Reboot|Package-Blacklist|Allowed-Origins)' | head
Unattended-Upgrade::Allowed-Origins "";
Unattended-Upgrade::Allowed-Origins:: "${distro_id}:${distro_codename}";
Unattended-Upgrade::Allowed-Origins:: "${distro_id}:${distro_codename}-security";
Unattended-Upgrade::Allowed-Origins:: "${distro_id}ESMApps:${distro_codename}-apps-security";
Unattended-Upgrade::Allowed-Origins:: "${distro_id}ESM:${distro_codename}-infra-security";
Unattended-Upgrade::Package-Blacklist "";
Unattended-Upgrade::Package-Blacklist:: "redis-server";
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-WithUsers "false";
Unattended-Upgrade::Automatic-Reboot-Time "03:30";
How to verify:apt-config dump What is shown is the merged result. Allowed-Origins defaults to ${distro_codename} (main repository, basically unchanged after release) and -security, as well as the Ubuntu Pro ESM source (will not match when Pro is not enabled); -updates is commented by default, that is, "only security updates are installed". Common errors: The comments in the APT configuration file are //, and lines starting with # will cause parsing errors in some places. Production use: Give these two files as templates to Ansible for unified distribution.
needrestart: Automatically restart affected services on the server, but exclude redis-server
sudo tee /etc/needrestart/conf.d/50-linuxlab.conf >/dev/null <<'EOF'
# Perl syntax: 'a' = automatically restart affected services; exclude services that should not be restarted unattended
$nrconf{restart} = 'a';
$nrconf{override_rc}->{qr(^redis-server)} = 0;
EOF
sudo needrestart -b
NEEDRESTART-VER: 3.11 NEEDRESTART-KCUR: 7.0.0-42-generic NEEDRESTART-KEXP: 7.0.0-43-generic NEEDRESTART-KSTA: 3 NEEDRESTART-SVC: myapp.service
-b is a batch output suitable for scripting/monitoring: KSTA is 1, which means that the running kernel is the latest, and 3 means that an updated kernel has been installed and needs to be restarted; SVC List services that are still using the old library. The configuration items and values are subject to the comments in the local /etc/needrestart/needrestart.conf.
Livepatch / kpatch (understanding, subscription or additional configuration required)
# Ubuntu (requires Ubuntu Pro, up to 5 units are free for individuals) sudo pro attach <token> && sudo pro enable livepatch canonical-livepatch status --verbose # RHEL (subscription): Install the dnf plug-in of kpatch and automatically subscribe to the live patch of the current kernel sudo dnf install -y kpatch-dnf && sudo dnf kpatch auto sudo kpatch list
RHEL system / Rocky 10 (rhellab): dnf-automatic
sudo dnf install -y dnf-automatic
sudo sed -i -e 's/^upgrade_type *=.*/upgrade_type = security/' \
-e 's/^apply_updates *=.*/apply_updates = yes/' \
-e 's/^#\? *reboot *=.*/reboot = when-needed/' /etc/dnf/automatic.conf
grep -E '^(upgrade_type|apply_updates|reboot|emit_via)' /etc/dnf/automatic.conf
sudo systemctl enable --now dnf-automatic.timer
systemctl list-timers 'dnf-automatic*'
upgrade_type = security apply_updates = yes reboot = when-needed emit_via = stdio NEXT LEFT LAST PASSED UNIT ACTIVATES Wed 2026-11-18 06:41:12 EST 21h left - - dnf-automatic.timer dnf-automatic.service
dnf-automatic.timer Press automatic.conf determines whether to just download or install; variants such as dnf-automatic-install.timer will overwrite the apply_updates in the configuration file (the RHEL 10 documentation clearly states the priority of timers and configurations). Do not enable multiple at the same time. The specific availability of the reboot option and reboot_command is subject to the local man dnf-automatic.
Patch status inspection script (stand-alone or batch via SSH/SSM)
#!/usr/bin/env bash
# Output a line of JSON: number of security updates to be installed, whether a restart is required, and the last automatic update time
set -euo pipefail
. /etc/os-release
reboot=false; pending=0; last=""
case $ID in
ubuntu|debian)
[[ -f /var/run/reboot-required ]] && reboot=true
pending=$(apt-get -s -o Debug::NoLocking=1 upgrade 2>/dev/null | grep -c '^Inst .*-security' || true)
last=$(stat -c %y /var/log/unattended-upgrades/unattended-upgrades.log 2>/dev/null | cut -d. -f1 || true) ;;
rocky|almalinux|rhel|amzn|fedora)
needs-restarting -r >/dev/null 2>&1 || reboot=true
pending=$(dnf -q updateinfo list --security 2>/dev/null | wc -l || true)
last=$(dnf -q history list 2>/dev/null | awk -F'|' 'NR==2 {gsub(/^ +| +$/,"",$3); print $3}' || true) ;;
esac
jq -cn --arg host "$(hostname)" --arg os "$PRETTY_NAME" --argjson pending "$pending" \
--argjson reboot "$reboot" --arg last "$last" \
'{host:$host, os:$os, security_pending:$pending, reboot_required:$reboot, last_auto_update:$last}'
{"host":"linuxlab","os":"Ubuntu 26.04.1 LTS","security_pending":0,"reboot_required":true,"last_auto_update":"2026-11-17 06:24:51"}
apt-get -s simulates upgrade and lists Inst lines, with -security sources that are security updates (heuristic, suitable for inspection; accurate judgment is based on unattended-upgrade --dry-run shall prevail). needs-restarting from dnf-utils/dnf-plugins-core, returns 1 when restarting is required.
Lab 5: Configure and verify automatic security updates (about 6 minutes)
systemctl is-enabled unattended-upgrades.service apt-daily.timer apt-daily-upgrade.timer systemctl list-timers 'apt-daily*' --no-pager cat /etc/apt/apt.conf.d/20auto-upgrades
enabled enabled enabled NEXT LEFT LAST PASSED UNIT ACTIVATES Tue 2026-11-17 18:03:44 UTC 8h left Tue 2026-11-17 06:12:01 UTC 3h ago apt-daily.timer apt-daily.service Wed 2026-11-18 06:21:37 UTC 20h left Tue 2026-11-17 06:24:40 UTC 3h ago apt-daily-upgrade.timer apt-daily-upgrade.service APT::Periodic::Update-Package-Lists "1"; APT::Periodic::Unattended-Upgrade "1";
tee, and then preview:
sudo unattended-upgrade --dry-run --debug 2>&1 | grep -E 'Allowed origins|Initial blacklist|Packages that will be upgraded|No packages found'
Allowed origins are: o=Ubuntu,a=resolute, o=Ubuntu,a=resolute-security, o=UbuntuESMApps,a=resolute-apps-security, o=UbuntuESM,a=resolute-infra-security Initial blacklist: redis-server No packages found that can be upgraded unattended and no pending auto-removals
sudo systemctl edit apt-daily-upgrade.timer --stdin <<'EOF' [Timer] OnCalendar= OnCalendar=*-*-* 02:00 RandomizedDelaySec=30m EOF systemctl cat apt-daily-upgrade.timer | tail -4 systemctl list-timers apt-daily-upgrade.timer --no-pager
The empty first line OnCalendar= is used to clear the original value (override rule for list-type settings). systemctl edit --stdin requires newer systemd (systemd 259 of 26.04 supports it; please remove --stdin interactive editing for older versions). Upgrade 02:00–02:30, restart 03:30, leaving a buffer in between.
sudo needrestart -b | grep -E 'KSTA|SVC' || echo "no restart needed" ls -l /var/run/reboot-required 2>/dev/null && cat /var/run/reboot-required.pkgs || echo "no reboot required" apt-config dump | grep -E 'Automatic-Reboot(-Time)? '
NEEDRESTART-KSTA: 1 no reboot required Unattended-Upgrade::Automatic-Reboot "true"; Unattended-Upgrade::Automatic-Reboot-Time "03:30";
Install 02:00–02:30, restart 03:30, leave a buffer between the two; set different settings by group when multiple hosts Automatic-Reboot-Time, or turn off the automatic restart of the machine and use Update Manager / Patch Manager to restart in the maintenance window.
chmod +x ~/linuxlab/ops/bin/patch-status.sh && ~/linuxlab/ops/bin/patch-status.sh sudo tail -5 /var/log/unattended-upgrades/unattended-upgrades.log # rhellab (optional): Execute the dnf-automatic section of the "command" pagination
Cleanup: If you want to restore the default, delete /etc/apt/apt.conf.d/52unattended-upgrades-local and sudo systemctl revert apt-daily-upgrade.timer. It is recommended to keep automatic security updates on the lab VM.
Case 1: Automatic restart hits batch task
Problem: All hosts automatically restarted at 03:30, and the simultaneous restart caused all load balancing backends to go offline for 2 minutes. Method: Stagger the restart time by host group (Ansible delivers different Automatic-Reboot-Time by group), or turn off the automatic restart of a single machine and instead use Azure Update Manager maintenance configuration / SSM maintenance period to restart in batches; Kubernetes nodes use coordination tools such as kured. Limitations: The more groups there are, the more dispersed the patch's effective time will be, which requires a balance between compliance requirements and availability.
Case 2: The blacklist prevents critical services from being "never updated"
Problem: For stability, the team added redis-server to the blacklist. A year later, multiple unfixed CVEs were discovered through missed scanning. Practice: The blacklist is just "don't update unattended" and must be accompanied by a responsible change process: monthly rolling upgrade by Ansible during the maintenance window (first remove from load balancing, upgrade, health check, put back); or through mirror reconstruction (Modules 3–4). Limitations: Requires clear ownership and tracking of tickets.
Case 3: AL2023 instance "patched" but still vulnerable
Problem:Operation and maintenance thought that dnf upgrade was already the latest, but the instance was still locked in the AL2023 repository version at startup, and the security updates in the new version repository were not installed. Method: Use the AL2023 patch baseline of SSM Patch Manager; or execute dnf check-release-update and explicitly --releasever upgrade in the patch process; it is recommended to regularly use the latest AL2023 AMI to rebuild the golden image. Restrictions: Cross-repository version upgrades also require testing. The original intention of deterministic upgrades is to avoid "unexpected changes."
Common errors and solutions
E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 2211 (unattended-upgr)
Cause: Manual apt conflicts with running automatic updates.
systemctl status apt-daily-upgrade.service --no-pager ps -o pid,etime,cmd -C unattended-upgrade
Fix: Wait for it to complete (don't kill dpkg, it may leave a semi-configured package); use apt-get -o DPkg::Lock::Timeout=600 in the script. If it does break, run sudo dpkg --configure -a.
*** System restart required *** has been shown for several weeks
Reason: Automatic restart is not performed by default.
cat /var/run/reboot-required.pkgs; uname -r; dpkg -l 'linux-image-*' | awk '/^ii/{print $2,$3}'
Fix: Configure Automatic-Reboot or include it in a maintenance window; Ubuntu Pro Livepatch can patch some kernel vulnerabilities without rebooting (subscription required), but it is not a substitute for regular reboots.
unattended-upgrades.log: Package xxx has conffile prompt and needs to be upgraded manually
Reason: The new version of the package has modified the configuration file that you have modified locally. The unattended mode will not overwrite or skip the package by default.
Fixed: Manually sudo apt-get install --only-upgrade package name and process the configuration merge; put the local configuration into the conf.d fragment for a long time to avoid directly changing the main configuration that comes with the package.
dnf-automatic: The timer is running but nothing is installed
Cause:apply_updates = no (default download only), or dnf-automatic-notifyonly.timer is enabled -download.timer, they override configuration files.
systemctl list-unit-files 'dnf-automatic*'; journalctl -u dnf-automatic.service -n 20 --no-pager
Fix: Enable only one timer; if you need to install it, use dnf-automatic.timer + apply_updates = yes, or dnf-automatic-install.timer.
1. Preview the packages that will be upgraded unattended, and only display the package name list.
sudo unattended-upgrade --dry-run --debug 2>&1 | sed -n 's/^Packages that will be upgraded: //p'
2. List all packages that "need to be restarted to take effect" on Ubuntu, if not, print none.
cat /var/run/reboot-required.pkgs 2>/dev/null || echo none
The company has 200 Ubuntu and 50 Rocky hosts, distributed in Azure and AWS. Audit requirements: Security patches installed within 14 days, compliance reports provided monthly, and production databases restarted only during the Sunday window. Please design a plan.
① Baseline: All hosts enable unattended-upgrades / dnf-automatic, only install security updates, and non-database hosts stagger and automatically restart by group; ② Database: add to the blacklist or turn off automatic restart, Ansible presses serial: 1 in the Sunday window for rolling upgrade and restart (cut master-slave first, health check); ③ Compliance: Azure The host is connected to Azure Update Manager for periodic assessment, and the AWS host uses SSM Patch Manager patch baseline + compliance report, or uses Ansible to run this module's patch-status.sh daily and summarizes it to the log platform (module 7); ④ The configuration itself (apt.conf.d, needrestart, automatic.conf) is managed by Ansible to prevent drift (module 6); ⑤ The mirror is rebuilt every week (module 7) 3-4), reduce the patch debt of running instances; ⑥ Only one mechanism is responsible for restarting the same host to avoid restarts outside the window.
Verified instructional video
Official documentation
- Ubuntu Server: Automatic updates
- RHEL 10: Automating software updates(dnf-automatic) · DNF Automatic
- AL2023: Deterministic upgrades · AWS Systems Manager Patch Manager
- Azure Update Manager (this course Lesson 3 · Module 6) · SSM Patch Manager (Lesson 4 · Module 6) · Configuration Management: Ansible 8 hours
- needrestart · Ubuntu Livepatch · RHEL: kernel live patching(kpatch)
Video Storyboard Script (~80 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: There are only a few spaces between the date the vulnerability was announced and the date it was exploited on the calendar, and the arrow for manual patching is far behind.
Narration: Vulnerabilities can be exploited within days after they are made public, and security updates must be automated.
Screen: Two timer icons ring one after another, and the package enters the system through the "safe sources only" filter and the "blacklist" barrier.
Narration: Ubuntu uses two systemd timers to drive unattended-upgrades, allowing only safe sources and excluding critical packages.
Screen: The kernel update lights up the "restart required" red light, the clock reaches 3:30, and the health check turns green after the server restarts; the three layers of Update Manager, Patch Manager, and Ansible are superimposed above.
Narration: The kernel patch needs to be restarted to take effect. The three-layer cooperation capabilities of stand-alone autonomy, platform orchestration, and configuration management are both safe and controllable.
Module 6 · Configuration Drift and Ansible Connection
- Discuss common sources of configuration drift (manual hot fixes, temporary packaging, automatic updates, partially failed deployments) and the difference between "anticipated changes" and "drift".
- Use image list comparison,
dpkg --verify/debsums/rpm -Va, permission check andsshd -Teffective configuration to detect drift, and writedrift-checkthat returns a clear exit code. - Determine whether a configuration should be baked, injected at startup, or configuration management based on "frequency of change, whether it varies from instance to instance, whether it is confidential, whether it requires continuous enforcement"; use a minimal Ansible playbook's
--check --diffto detect and correct drift.
What: What is configuration drift
Configuration drift (configuration drift) is the gradual deviation of the actual state of the machine from the expected state (image baseline or statement in configuration management). Drift on a single machine is not terrible. What is terrible is that no one knows: the behavior of machines in the same role is inconsistent, faults cannot be reproduced, and audits cannot tell "who changed what when". In the end, each machine becomes a "snowflake server" that can only be maintained carefully.
| Source | Example | Is expected |
|---|---|---|
| Automatic security update | openssl version changed from 3.x.1 in the image 3.x.2 | Expected (module 5), only report list changes, not version changes |
| Hot fix on duty | SSH up to change the configuration, chmod, add a sshd_config.d/05-hotfix.conf | Drift: must be written back to the image or playbook, otherwise it will be lost in the next rebuild |
| Temporary package | Forgot to delete after apt install tcpdump figlet during troubleshooting | Drift: Expanding attack surface |
| Partially failed deployment | Half of the hosts' configurations were updated successfully, while the other half failed | Drift: Two behaviors appear in the same character |
| The software rewrites itself | The application or agent writes the runtime configuration in /etc | Depending on the situation: such paths should be excluded or managed separately |
Why: three governance ideas
- Detection: Regularly compare baselines and report (this module's
drift-check,ansible-playbook --check --diff, Azure Machine Configuration / AWS Config and SSM Inventory on the cloud). - Correction: Configuration management tools continue to pull the declared state back to the expected value (Ansible scheduled runs, AWX/AAP scheduled tasks). Note: It only cares about what it declares, and undeclared changes can only be detected.
- Elimination: Immutable infrastructure - in-place modification is prohibited, any changes are made through new image versions + rolling replacement (modules 3–4), drifting machines are directly replaced.
How: Four levels of detecting drift
- Software package list: When building the image, write the list of installed packages into the image (such as
/etc/myapp-image/packages.txt), and usecommto compare which packages are "more/less" during runtime. - Files in the package:
dpkg --verify(Debian/Ubuntu, verify MD5 of the files in the package, configuration file tagc),debsums -c; RHEL systemrpm -Va. Files that do not belong to any package can be used as an integrity baseline with AIDE (Lesson 6 Auditing related content). - Key attributes and effective configuration:
statpermissions and owners (such as/etc/myapp/myapp.envmust be root:myapp 0640);sshd -Toutputs the effective SSH configuration, and you can find that "another drop-in has overwritten your settings". - Declarative comparison:
ansible-playbook --check --diffdoes not make changes, only reports which tasks will bechanged- each changed is a drift.
When: Baking, injection at startup, or configuration management?
| Determining the problem | Baking into the image (Packer) | Injection at startup (cloud-init / user data / managed identity) | Configuration Management (Ansible) | |
|---|---|---|---|---|
| How often does it change? | With mirroring version (weekly) | Once per instance | Anytime, possibly more often than mirroring | |
| Does it vary by instance/environment? | No: The same role is the same | Yes: host name, environment address, cluster member | Divided by group/environment variable | |
| Is it confidential? | Never | Yes: Fetched from Key Vault / Secrets Manager at runtime | Can be searched and distributed through Vault/confidential | |
| Is continuous enforcement required? | No (identical at birth) | No | Yes: Prevent drift, uniformly modify existing machines | |
| Example of myapp | Python venv, code, unit file, reinforcement, agent | REDIS_URL, function switch, certificate private key | sshd/patch policy file, myapp.env permissions, user and public key, stateful host (database) |
Packer and Ansible are not alternatives: Packer's ansible The provisioner (plugin v1.1.6) can run the same playbook while baking and then use it to maintain state on the running machine - same declaration, used in two places. The complete Ansible learning path is available at Ansible in 8 hours.
--check are completely accurate" - Tasks (such as command, shell) that rely on the results of the previous task may be skipped or falsely reported in the check mode and need to be cooperated with check_mode: false and changed_when . ③ "The version changes brought about by automatic updates are also drifts" - if the alarm is reported every time, everyone will learn to ignore the alarm; version changes are handed over to patch compliance (module 5), Drift detection focuses on "list and configuration". ④ "Immutable infrastructure does not require detection" - still needed: detection is a means to prove "no one secretly changed SSH" Architecture diagram: three sources of expected state and drift detection
Decision diagram: where should a configuration be placed
Interactive simulator: A life of drift - generation, detection, disposal
Select a disposal method and play: A VM started by image 1.0.0 undergoes automatic updates and an on-duty hot fix, daily drift-check After discovering the problem, take a look at "Using Ansible" What will be the consequences of "correct", "rebuild the image and replace" and "only record without processing".
Core command
| Command | Function | Description |
|---|---|---|
dpkg-query -W -f='${db:Status-Abbrev}${Package}\n' | List packages and their status | Fetch only ii (installed) line as list |
sudo dpkg --verify [package name] | Verify files in package | Bit 3 5 = Content (MD5) change; c = Configuration file |
sudo debsums -c / -ce | List modified files / only view configuration files | Requires installation debsums |
sudo rpm -Va | RHEL system verifies all packages | S.5....T. c /etc/… |
sudo sshd -T | grep -i passwordauthentication | View SSH Effective configuration | "First appears in drop-in takes effect" |
ansible-playbook PB --check --diff | Only report what will be changed | Drift detection; remove --check to correct |
sudo apt-get install --reinstall -o Dpkg::Options::=--force-confmiss package | Restore deleted package configuration file | Delete the modified files before executing |
Drift detection script: bin/drift-check
#!/usr/bin/env bash
# drift-check - Compare the local and image baselines; 0 means no drift, 1 means drift. Requires root. Output key=value.
set -Eeuo pipefail
BASE=${BASE:-/etc/myapp-image/packages.txt}
drift=0
report() { printf 'drift=%s %s\n' "$1" "$2"; drift=1; }
pkgs() { dpkg-query -W -f='${db:Status-Abbrev}${Package}\n' | awk '$1 == "ii" {print $2}' | sort -u; }
# 1) Package list: only look at "more/less", version changes are left to patch compliance (module 5)
if [[ -r $BASE ]]; then
while IFS= read -r line; do
if [[ $line == $'\t'* ]]; then report package "change=added name=${line#$'\t'}"
else report package "change=removed name=$line"; fi
done < <(comm -3 "$BASE" <(pkgs))
else
report baseline "missing=$BASE"
fi
# 2) Files in the package: c = configuration file is modified
while read -r flags rest; do
kind=file; [[ $rest == "c "* ]] && kind=conffile
report file "kind=$kind flags=$flags path=${rest##* }"
done < <(dpkg --verify 2>/dev/null)
# 3) Key file attributes
want='root:myapp 640'; got=$(stat -c '%U:%G %a' /etc/myapp/myapp.env)
[[ $got == "$want" ]] || report mode "path=/etc/myapp/myapp.env want=\"$want\" got=\"$got\""
# 4) SSH effective configuration
sshd -T 2>/dev/null | grep -qx 'passwordauthentication no' || report sshd "key=passwordauthentication want=no"
if (( drift )); then exit 1; fi
echo "drift=none"
The baseline is generated when building the image (you can add a line at the end of harden.sh pkgs > /etc/myapp-image/packages.txt Equivalent command); this experiment was manually generated on linuxlab. The script follows the convention of Module 1: the exit code is meaningful, key=value is output, and can be run daily by the systemd timer and the results are sent to the centralized log (Module 7). RHEL system replaces steps 1 and 2 with rpm -qa --qf '%{NAME}\n' and rpm -Va.
Minimal playbook: ansible/baseline.yml
- name: linuxlab baseline (detect and correct drift)
hosts: all
become: true
tasks:
- name: myapp env file ownership and mode
ansible.builtin.file:
path: /etc/myapp/myapp.env
owner: root
group: myapp
mode: "0640"
- name: SSH hardening drop-in (same content as the image, module 4)
ansible.builtin.copy:
dest: /etc/ssh/sshd_config.d/10-linuxlab-hardening.conf
owner: root
group: root
mode: "0644"
content: |
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
X11Forwarding no
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
notify: Reload ssh
- name: Unattended-upgrades local policy (module 5)
ansible.builtin.copy:
src: files/52unattended-upgrades-local
dest: /etc/apt/apt.conf.d/52unattended-upgrades-local
mode: "0644"
- name: Read effective sshd configuration
ansible.builtin.command: sshd -T
register: sshd_effective
changed_when: false
check_mode: false
- name: No undeclared override may re-enable password login
ansible.builtin.assert:
that: "'passwordauthentication no' in sshd_effective.stdout_lines"
fail_msg: "Drift: an undeclared sshd_config.d file overrides PasswordAuthentication"
- name: myapp is enabled and running
ansible.builtin.systemd_service:
name: myapp.service
enabled: true
state: started
handlers:
- name: Reload ssh
ansible.builtin.systemd_service:
name: ssh
state: reloaded
The first three tasks correct asserted states; the assert task detects something it cannot assert (any other drop-in may override the setting). check_mode: false makes the read-only sshd -T also executed when --check; starting from ansible-core 2.19, the condition must be a Boolean value, and the in expression meets the requirements. Ubuntu's SSH service unit name is ssh (RHEL system is sshd). Reuse in Packer: provisioner "ansible" { playbook_file = "../ansible/baseline.yml" } (need to add github.com/hashicorp/ansible to required_plugins).
Experiment 6: Manufacturing drift, detection, and correction (about 6 minutes, completed locally, zero cost)
cd ~/linuxlab/ops
mkdir -p ansible/files && cp /etc/apt/apt.conf.d/52unattended-upgrades-local ansible/files/ # File of module 5
# After saving the baseline.yml and drift-check of the "Command" page:
sudo ansible-playbook -i localhost, -c local ansible/baseline.yml
sudo install -d -m 0755 /etc/myapp-image
dpkg-query -W -f='${db:Status-Abbrev}${Package}\n' | awk '$1 == "ii" {print $2}' | sort -u \
| sudo tee /etc/myapp-image/packages.txt >/dev/null
chmod +x bin/drift-check && shellcheck bin/drift-check && sudo bin/drift-check; echo "rc=$?"
PLAY RECAP ********************************************************************* localhost : ok=7 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 drift=none rc=0
If it is run for the first time drift-check reports the items of kind=file, indicating that linuxlab has changed some package files in the previous lessons - this is drift; record it and determine whether it is expected.
sudo apt-get install -y -q figlet # Temporarily install the package sudo chmod 0644 /etc/myapp/myapp.env # Relax permissions for troubleshooting echo 'PasswordAuthentication yes' | sudo tee /etc/ssh/sshd_config.d/05-hotfix.conf sudo sed -i 's/rotate 4/rotate 1/' /etc/logrotate.d/rsyslog # Modify the configuration file that comes with the package
sudo bin/drift-check; echo "rc=$?" sudo ansible-playbook -i localhost, -c local ansible/baseline.yml --check --diff
drift=package change=added name=figlet
drift=file kind=conffile flags=??5?????? path=/etc/logrotate.d/rsyslog
drift=mode path=/etc/myapp/myapp.env want="root:myapp 640" got="root:myapp 644"
drift=sshd key=passwordauthentication want=no
rc=1
TASK [myapp env file ownership and mode] ***************************************
--- before
+++ after
@@ -1,4 +1,4 @@
{
- "mode": "0644",
+ "mode": "0640",
"path": "/etc/myapp/myapp.env"
}
changed: [localhost]
…
TASK [No undeclared override may re-enable password login] *********************
fatal: [localhost]: FAILED! => {"assertion": "'passwordauthentication no' in sshd_effective.stdout_lines", "changed": false, "evaluated_to": false, "msg": "Drift: an undeclared sshd_config.d file overrides PasswordAuthentication"}
Compare two tools: drift-check found all 4; playbook can correct permissions and discover SSH coverage, but for figlet Nothing is known about logrotate files - since they are not declared.
sudo rm /etc/ssh/sshd_config.d/05-hotfix.conf sudo apt-get purge -y -q figlet sudo rm /etc/logrotate.d/rsyslog && sudo apt-get install -y -q --reinstall -o Dpkg::Options::=--force-confmiss rsyslog sudo ansible-playbook -i localhost, -c local ansible/baseline.yml --diff | tail -3 sudo bin/drift-check; echo "rc=$?" git add ansible bin/drift-check && git commit -m "feat: drift-check and ansible baseline"
PLAY RECAP ********************************************************************* localhost : ok=7 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 drift=none rc=0
If the hot fix is correct (for example, a certain parameter really needs to be adjusted), the correct approach is to write it back to harden.sh/playbook, and release a new image version instead of just leaving it on this machine. Cleanup: All changes in this experiment have been undone; /etc/myapp-image/packages.txt can be retained.
Case 1: The hot fix "disappeared" during the next expansion
Problem:The engineer on duty manually increased the number of gunicorn workers on 3 VMs to solve the peak problem; a week later, the new instances expanded by VMSS came from the old image, and the problem recurred, and no one remembered what had been changed. Practice: Daily drift-check + centralized log alert; hot fixes must be written back to the myapp.env template/image and release a new version within 24 hours; production SSH access must be approved and audited (Lesson 6 auditd). Limitations: Testing can only tell you "changed", and people are still needed to judge "should it change".
Case 2: Ansible runs every night, but no backdoor account is found
Problem: The playbook manages 10 known users, the 11th user added by the attacker is not in the statement, and Ansible reports "ok" every night. Method: Perform reverse detection on "collection" resources (list users with UID ≥ 1000 in /etc/passwd and compare them with statements); use AIDE for file integrity; immutable deployment regularly replaces instances. Limitations: Reverse detection requires maintaining an allow list, otherwise it will be very noisy.
Case 3: Automatic updates make drift alarms meaningless
Problem: Drift detection comparison package version reported dozens of changes every day after automatic security updates, and the team began to ignore the alarms. Method: Drift detection only compares the list with the configuration. Version compliance is handed over to the patch report (patch-status.sh of module 5, Update Manager / Patch Manager); the image is rebuilt every week to refresh the baseline. Limitations: List comparison cannot detect "downgrade to a vulnerable version". This type of problem is handled by vulnerability scanning.
Common errors and solutions
drift-check reports dozens of drift=files on the first run
Cause:The machine has already deviated from the original file of the package (previous manual modification, some packages rewrite their own files in the post-installation script), or dpkg --verify Also list the configuration files that are expected to be modified.
sudo dpkg --verify | awk '{print $NF}' | xargs -r dpkg -S 2>/dev/null | sort | head
Fixed: Confirm item by item; create an exclusion list for expected modified paths (such as grep -vFf /etc/myapp-image/verify-allow.txt), and update it synchronously when the image is built.
ansible-playbook: [WARNING]: Unable to parse localhost, as an inventory source / skipping: no hosts matched
Cause: -i localhost Missing comma - Ansible treats it as a manifest file path.
Fixed:Write -i localhost, (comma indicates host list), and add -c local.
--The assert error in check mode: 'sshd_effective' is undefined
Reason: command module is skipped by default in check mode, and there is no registration result.
Fix: Add check_mode: false and changed_when: false to the read-only command (this lesson playbook has already processed it).
sshd -T: Missing privilege separation directory: /run/sshd
Cause: When sshd is running in socket activation mode on Ubuntu, /run/sshd may not have been created yet.
sudo install -d -m 0755 /run/sshd && sudo sshd -T | head -3
Fix: Create the directory and try again; or use sudo systemctl start ssh and check again.
1. List all modified "package configuration files" on Ubuntu (as long as the path).
sudo dpkg --verify | awk '$2 == "c" {print $3}'
# or: sudo debsums -ce2. Only check (not modify) and display differences only for myapp.env related tasks.
# First add to the task: tags: [env] sudo ansible-playbook -i localhost, -c local ansible/baseline.yml --check --diff --tags env
You have 100 stateless myapp VMs (VMSS/ASG) and 2 PostgreSQL VMs. Please design "anti-drift" strategies for the two types of hosts.
myapp: Immutable as main - all changes are mirrored (modules 3–4), production SSH modifications are prohibited (or only approved break-glass is allowed); daily drift-check is only used to find violations, and instances are replaced and repaired when found; configuration management is only responsible for a small amount of environment configuration or is not used at all. PostgreSQL: variable-based - Ansible manages configuration files, users, patch windows and backup tasks, regularly reports drifts with --check --diff and applies them after approval; major version upgrades are subject to planned changes; also run drift-check and AIDE to detect undeclared changes. The logs and drift reports of both types of hosts enter the centralized log platform (Module 7).
Verified instructional video
Official documents and extensions
- Ansible: Check mode and diff mode · assert module
- dpkg(1)(--verify) · debsums(1) · sshd(8)(-T)
- Packer Ansibleopener"> Plugins · Cloud: Azure Machine Configuration · AWS Config
- System learning: Ansible 8 hours (1st hour idempotent and handler, 2nd hour check/diff and Molecule)
Video storyboard script (about 75 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: A row of identical servers was born from the mirror. After a few days, the color of several of them slowly changed: one had an extra package, one had changed permissions, and one had an extra configuration file.
Narration: The image is only guaranteed to be consistent at birth, and the running machine will slowly lose shape. This is configuration drift.
Screen: drift-check scans layer by layer like a scanner: package list, files in the package, permissions, SSH effective configuration; Ansible's check mode lists changed next to it.
Narration: There are four levels of detection. Configuration management can only correct what it has declared, and undeclared changes can only be discovered through detection.
Screen: Three forked roads: injection at startup, baking into the image, and configuration management; each configuration card is sorted into its own path.
Narration: Secrets and instance differences are injected at startup. The same things for the same role are baked into the image and need to be continuously and forcefully handed over to Ansible.
Module 7 · Log centralization: journald forwarding, rsyslog and cloud collection
- Write
myapp-healthcheck: multi-layer checks (unit status, HTTP, Redis), limited number of self-healing restarts (anti-shake), structured logs, clear exit codes. - Replace cron with
.service(Type=oneshot) +.timer(OnBootSec / OnUnitActiveSec / RandomizedDelaySec), and useOnFailure=template unit to send notifications. - Understand and configure log paths: program stderr → journald (
ForwardToSyslog) → rsyslog (imuxsock/imjournal) →omfwd(TCP + disk queue) → centralized server; know whensystemd-journal-upload/-remoteis more appropriate. - Name the cloud equivalents and course locations: Azure Monitor Agent + DCR (Lesson 3 · Module 5), CloudWatch Agent (Lesson 4 · Module 5), and the practice of baking agents into images (modules 3–4).
What: Scheduled health check and log concentration
myapp-healthcheck is a one-time service triggered every minute by the systemd timer. It makes up for the situation that Restart=on-failure cannot control: the process is still alive but has "suspended death" (gunicorn worker is stuck, Redis connection is exhausted, and 500 is returned). Log centralization Copies the logs of each host to a central location in real time. Even if the host goes down, is hacked, or is replaced (immutable deployment), it can still be traced back.
Why: systemd timer vs cron
| Capability | cron | systemd timer + service |
|---|---|---|
| Log | Output sent by email or lost | Automatically enter journald, journalctl -u query, with exit code |
| Anti-overlap | Required flock | The timer will not start it again while the service is still running |
| Missed execution | No catch-up (except anacron) | Persistent=true (OnCalendar) catch-up after booting |
| Resources and security | Run naked as user | CPUQuota=, MemoryMax=, ProtectSystem=, PrivateTmp= and other sandboxes |
| Failure handling | None | OnFailure= Trigger notification unit |
| Observable | Hard | systemctl list-timers Show last/next execution |
How: Log from program to centralized server
- Service stdout/stderr is directly connected to journald (Lesson 2) by systemd, with fields such as
_SYSTEMD_UNIT,SYSLOG_IDENTIFIER(SyslogIdentifier=in the unit, myapp.service ismyapp),PRIORITY;logger/systemd-catalso writes to journald. - rsyslog obtains logs: Debian/Ubuntu's rsyslog uses
imuxsockto receive messages forwarded by journald to the syslog socket (the default configuration of the distribution version has been opened); RHEL usesimjournalto read logs directly. The default value of upstream journald is "only forward to the wall", so when changing the distribution or customizing the configuration, you need to usesystemd-analyze cat-config systemd/journald.confto confirmForwardToSyslog. - rsyslog rules are filtered by
$programname, facility, and level, andomfwdactions are sent to the center through TCP (TLS can be added); after configuring Disk Auxiliary Queue, the logs are queued first when the center is unreachable, and reissued after recovery. - Central server
imtcpreceives, writes files by host/program, or continues forwarding to Elasticsearch/Loki/SIEM. - Alternative path:
systemd-journal-upload→systemd-journal-remote(retain journald's structured fields); systemd 256+ journald'sForwardToSocket=; use Azure Monitor Agent + data collection rules on the cloud (Lesson 3 · Module 5, Collect syslog by DCR facility and level) or CloudWatch Agent (Lesson 4 · Module 5, Collect files or journald by configuration). Both agents are suitable for baking into images (Modules 3–4), and "what to collect" is determined by cloud rules or configurations issued at startup.
When: Select the log concentration method
| Scenario | Recommended |
|---|---|
| Traditional data centers, existing syslog infrastructure, and network equipment should also be summarized | rsyslog omfwd (TCP + TLS + disk queue) |
| Pure systemd environment, want to preserve structured fields | systemd-journal-upload / remote |
| VM on Azure / AWS | Azure Monitor Agent + DCR → Log Analytics; CloudWatch Agent → CloudWatch Logs |
| Kubernetes / Modern Observability Platform | Fluent Bit / OpenTelemetry Collector → Loki / Elasticsearch (see Prometheus & Grafana Course) |
Restart=always there is no need for health checks" - Restart only takes effect when the processexit, and suspended processes will never be restarted. ② "Restart infinitely if the health check fails" - Restart storms will cover up the root cause and amplify the fault (for example, it is meaningless to restart myapp repeatedly when Redis is down); you need to rely on checks and the upper limit of times. ③ "UDP 514 forwarding is enough" - UDP packet loss is imperceptible and clear text; production uses TCP/RELP + TLS + queue. ④ "The local logs can be turned off after the logs are centralized" - the local journald is still the first scene, and will be the first to take care of the situation when the network is interrupted; it is necessary to set up a reasonable SystemMaxUse=. architecture diagram: Discovery → Self-healing → Notification → Centralization
Flowchart: Decision of health check script
Interactive simulator: a health check from triggering to centralized log
Select the fault scenario and play it, and observe what systemd, script, journald, rsyslog and the central server do respectively. The terminal below displays the corresponding journald / rsyslog real log format.
Core commands and parameters
| Commands | Function | Description |
|---|---|---|
systemctl list-timers --all | Last/next execution of all timers | systemctl status x.timer Display trigger |
systemd-analyze calendar 'Mon..Fri 02:00' | Verify OnCalendar Expression | --iterations=5 Show next 5 times |
systemd-analyze verify x.service | Check unit file | Typos, missing executables |
systemd-run --on-active=30s --unit=probe /usr/local/bin/myapp-healthcheck | Temporary scheduled tasks | Does not write unit files, suitable for one-time tasks |
journalctl -t myapp-healthcheck -p warning --since today | Query by identity and level | -o json / -o cat; -f Follow |
logger -t tag -p user.err, systemd-cat -t tag -p err | Write log | The latter writes the entire command output to journald |
rsyslogd -N1 | Verify rsyslog configuration | Verify first after modification and then systemctl restart rsyslog |
Health check script: /usr/local/bin/myapp-healthcheck
#!/usr/bin/env bash
# myapp-healthcheck [--restart] —— 0 healthy/self-healed; 1 myapp unhealthy; 2 dependency (Redis) failure
set -Eeuo pipefail
URL=${HEALTH_URL:-http://127.0.0.1:5000/healthz}
MAX_RESTARTS=${MAX_RESTARTS:-3} # Maximum number of self-healing restarts per hour
STATE=${STATE_DIRECTORY:-/var/lib/myapp-healthcheck}/restarts
restart=0; [[ ${1:-} == --restart ]] && restart=1
log() { printf '%s%s\n' "$1" "${*:2}" >&2; } # In systemd, stderr enters journald
# Use the prefix to tell journald the priority (sd-daemon convention): 3=err 4=warning 6=info
info() { log "<6>" "$@"; }; warn() { log "<4>" "$@"; }; err() { log "<3>" "$@"; }
http_ok() {
local i code
for i in 1 2 3; do
code=$(curl -s -o /dev/null -m 3 -w '%{http_code}' "$URL") || true
[[ $code == 200 ]] && return 0
sleep 2
done
last_code=${code:-000}; return 1
}
recent_restarts() { # Count the number of restarts in the last 3600 seconds
local now; now=$(date +%s)
[[ -f $STATE ]] || { echo 0; return; }
awk -v now="$now" '$1 > now - 3600' "$STATE" | wc -l
}
if ! systemctl is-active --quiet redis-server.service valkey.service 2>/dev/null \
&& ! redis-cli -t 2 ping >/dev/null 2>&1; then
err "check=redis status=down action=none msg=\"dependency down, not restarting myapp\""
exit 2
fi
if http_ok; then
info "check=http status=ok url=$URL"; exit 0
fi
warn "check=http status=fail code=${last_code} unit_state=$(systemctl is-active myapp.service || true)"
(( restart )) || exit 1
n=$(recent_restarts)
if (( n >= MAX_RESTARTS )); then
err "action=restart skipped=true restarts_last_hour=$n limit=$MAX_RESTARTS"; exit 1
fi
mkdir -p "$(dirname "$STATE")"; date +%s >> "$STATE"
warn "action=restart unit=myapp.service restarts_last_hour=$((n + 1))"
systemctl restart myapp.service
sleep 3
if http_ok; then info "check=http status=recovered"; exit 0; fi
err "check=http status=fail_after_restart code=${last_code}"; exit 1
<3>/<4>/<6> The prefix is systemd's convention for service stderr (unit default SyslogLevelPrefix=yes), journald Set PRIORITY accordingly, so journalctl -p warning and rsyslog level filtering will work. The key=value format facilitates parsing in centralized logging platforms. systemctl is-active A B As long as one unit is active, it returns 0 (Ubuntu is redis-server, AL2023 image is valkey). If it is unavailable, use redis-cli ping to find out.
systemd unit
[Unit] Description=myapp health check and self-healing After=network-online.target myapp.service Wants=network-online.target OnFailure=notify-failure@%n.service [Service] Type=oneshot ExecStart=/usr/local/bin/myapp-healthcheck --restart SyslogIdentifier=myapp-healthcheck StateDirectory=myapp-healthcheck TimeoutStartSec=90 Environment=MAX_RESTARTS=3 # Moderate hardening: systemctl restart needs to be called as root ProtectSystem=full ProtectHome=yes PrivateTmp=yes NoNewPrivileges=yes
[Unit] Description=Run myapp health check every minute [Timer] OnBootSec=2min OnUnitActiveSec=1min AccuracySec=5s RandomizedDelaySec=5s [Install] WantedBy=timers.target
[Unit] Description=Failure notification for %i [Service] Type=oneshot EnvironmentFile=-/etc/myapp/notify.env ExecStart=/usr/local/bin/notify-failure %i
#!/usr/bin/env bash
# notify-failure UNIT - record crit log, send JSON if WEBHOOK_URL is configured
set -euo pipefail
unit=${1:?unit}
detail=$(journalctl -u "$unit" -n 5 -o cat --no-pager 2>/dev/null || true)
logger -t notify-failure -p user.crit -- "unit=$unit failed on $(hostname)"
if [[ -n ${WEBHOOK_URL:-} ]]; then
jq -n --arg host "$(hostname)" --arg unit "$unit" --arg detail "$detail" \
'{text: "[\($host)] \($unit) failed\n\($detail)"}' \
| curl -fsS -m 10 -H 'Content-Type: application/json' -d @- "$WEBHOOK_URL" >/dev/null
fi
OnFailure=notify-failure@%n.service In %n expands to the full name of the failed unit, which is passed to %i as the template instance name. The minus sign in EnvironmentFile=- means that the file does not exist and no error will be reported. The webhook address (Teams/Slack, etc.) is confidential and file permissions are set to 0600.
rsyslog: client forwarding and server reception
# Only forward logs from myapp related programs and crit and above; the disk auxiliary queue prevents log loss when the center is unreachable
if ($programname startswith "myapp" or $programname == "drift-check"
or $programname == "notify-failure" or $syslogseverity <= 2) then {
action(type="omfwd" target="127.0.0.1" port="10514" protocol="tcp"
template="RSYSLOG_SyslogProtocol23Format"
queue.type="LinkedList" queue.filename="fwd_central"
queue.maxDiskSpace="256m" queue.saveOnShutdown="on"
action.resumeRetryCount="-1" action.resumeInterval="10")
}
module(load="imtcp")
template(name="PerHostProgram" type="string"
string="/var/log/remote/%HOSTNAME%/%PROGRAMNAME%.log")
ruleset(name="remote") {
action(type="omfile" dynaFile="PerHostProgram" createDirs="on"
dirCreateMode="0750" fileCreateMode="0640")
stop
}
input(type="imtcp" port="10514" ruleset="remote")
This lesson is intended to be done on a single machine. The client sends it to 127.0.0.1:10514, and the server listens on the same machine - the mechanism is exactly the same as across hosts; when crossing hosts, put target Change the centralized server address and open the port in its firewall. For production, be sure to enable TLS (rsyslog's gtls/ossl network stream driver) or use RELP, and configure logrotate for the remote log directory.
journald: Confirm forwarding to syslog
[Journal] ForwardToSyslog=yes # Native retention: persistence and caps are set in 50-linuxlab.conf of the image (module 4)
systemd-analyze cat-config systemd/journald.conf | grep -E '^\s*#?\s*ForwardToSyslog' sudo systemctl restart systemd-journald logger -t myapp "forward-test"; sudo tail -1 /var/log/syslog
The release version may be different from the upstream default value: first use cat-config to see the effective value after the merger, and then decide whether drop-in is needed. RHEL system's rsyslog uses imjournal to read journal files directly and does not rely on ForwardToSyslog.
Optional: systemd-journal-upload → systemd-journal-remote (retaining structured fields)
# Receiver (HTTP for local demo; default HTTPS and certificate for production) sudo apt-get install -y systemd-journal-remote sudo systemctl edit systemd-journal-remote.service --stdin <<'EOF' [Service] ExecStart= ExecStart=/usr/lib/systemd/systemd-journal-remote --listen-http=-3 --output=/var/log/journal/remote/ EOF sudo install -d -o systemd-journal-remote -g systemd-journal-remote /var/log/journal/remote sudo systemctl enable --now systemd-journal-remote.socket # Listening 19532 # Sender printf '[Upload]\nURL=http://127.0.0.1:19532\n' | sudo tee /etc/systemd/journal-upload.conf sudo systemctl enable --now systemd-journal-upload.service journalctl --directory=/var/log/journal/remote -t myapp -n 3 --no-pager
Compared with rsyslog, journal-remote retains all fields such as _SYSTEMD_UNIT, PRIORITY, and can be used directly with journalctl --directory query; the disadvantage is that the ecosystem (SIEM, network equipment) is not as versatile as syslog. The executable file path and user name are subject to the distribution package (systemctl cat systemd-journal-remote.service to confirm).
Experiment 7: Deploy health check timer and centralized log (about 8 minutes)
cd ~/linuxlab/ops sudo install -m 0755 bin/myapp-healthcheck bin/notify-failure /usr/local/bin/ sudo install -m 0644 systemd/myapp-healthcheck.service systemd/myapp-healthcheck.timer \ 'systemd/notify-failure@.service' /etc/systemd/system/ sudo systemd-analyze verify /etc/systemd/system/myapp-healthcheck.service sudo systemctl daemon-reload sudo systemctl enable --now myapp-healthcheck.timer systemctl list-timers myapp-healthcheck.timer --no-pager sudo systemctl start myapp-healthcheck.service; journalctl -t myapp-healthcheck -n 3 --no-pager
NEXT LEFT LAST PASSED UNIT ACTIVATES Tue 2026-11-17 10:21:07 UTC 54s - - myapp-healthcheck.timer myapp-healthcheck.service Nov 17 10:20:14 linuxlab myapp-healthcheck[5120]: check=http status=ok url=http://127.0.0.1:5000/healthz
sudo systemctl kill --signal=SIGSTOP myapp.service systemctl is-active myapp.service # Still active —— Restart= Nothing can be done sudo systemctl start myapp-healthcheck.service journalctl -t myapp-healthcheck -n 4 --no-pager curl -fsS http://127.0.0.1:5000/healthz; echo
active
Nov 17 10:23:02 linuxlab myapp-healthcheck[5301]: check=http status=fail code=000 unit_state=active
Nov 17 10:23:02 linuxlab myapp-healthcheck[5301]: action=restart unit=myapp.service restarts_last_hour=1
Nov 17 10:23:08 linuxlab myapp-healthcheck[5301]: check=http status=recovered
{"status":"ok"}
systemctl kill By default, signals are sent to all processes in the unit control group. When stopping the service, systemd sends SIGCONT immediately after SIGTERM (see systemd.kill(5)), so the process frozen by SIGSTOP can also be terminated normally, and restart can be completed smoothly.
sudo systemctl stop redis-server.service sudo systemctl start myapp-healthcheck.service; echo "rc=$?" journalctl -t myapp-healthcheck -t notify-failure -n 4 --no-pager systemctl status 'notify-failure@*' --no-pager | head -5 sudo systemctl start redis-server.service
Job for myapp-healthcheck.service failed because the control process exited with error code. See "systemctl status myapp-healthcheck.service" and "journalctl -xeu myapp-healthcheck.service" for details. rc=1 Nov 17 10:25:40 linuxlab myapp-healthcheck[5402]: check=redis status=down action=none msg="dependency down, not restarting myapp" Nov 17 10:25:40 linuxlab notify-failure[5410]: unit=myapp-healthcheck.service failed on linuxlab ○ notify-failure@myapp-healthcheck.service.service - Failure notification for myapp-healthcheck.service
sudo rsyslogd -N1 && sudo systemctl restart rsyslog logger -t myapp-healthcheck "check=http status=ok source=manual-test" sleep 1; sudo ls /var/log/remote/; sudo tail -2 /var/log/remote/*/myapp-healthcheck.log # Queue when the center is unreachable: temporarily block the port and then restore it sudo iptables -I INPUT -p tcp --dport 10514 -j REJECT logger -t myapp "queued while central is down"; sleep 2 sudo ls -l /var/spool/rsyslog/ 2>/dev/null | grep fwd_central || echo "(in the memory queue, not yet placed)" sudo iptables -D INPUT -p tcp --dport 10514 -j REJECT; sleep 12 sudo grep -h "queued while" /var/log/remote/*/myapp.log
rsyslogd: version 8.2512.0, config validation run (level 1), master config /etc/rsyslog.conf rsyslogd: End of config validation run. Bye. linuxlab 2026-11-17T10:30:02.114583+00:00 linuxlab myapp-healthcheck[5480]: check=http status=ok url=http://127.0.0.1:5000/healthz 2026-11-17T10:30:05.871203+00:00 linuxlab myapp-healthcheck: check=http status=ok source=manual-test (In memory queue, not yet placed) 2026-11-17T10:30:09.410022+00:00 linuxlab myapp: queued while central is down
LinkedList + queue.filename It is a "disk-assisted" queue: put the memory first, write to the disk to the rsyslog working directory (Ubuntu is /var/spool/rsyslog) when the memory is full or shutdown (saveOnShutdown). If Ubuntu 26.04 uses the nftables backend, the iptables command is provided by iptables-nft and has the same effect.
sudo rm /etc/rsyslog.d/10-central-receiver.conf /etc/rsyslog.d/90-forward-myapp.conf && sudo systemctl restart rsyslog sudo rm -rf /var/log/remote # It is recommended to keep the health check timer; to disable it: sudo systemctl disable --now myapp-healthcheck.timer git add bin systemd && git commit -m "feat: myapp-healthcheck timer, notify-failure"
Case 1: Health check triggers restart storm
Problem: During the failover of the Redis master node (about 40 seconds), the health check of all application hosts determined that myapp was unhealthy and restarted. The cold start after the restart slowed down the recovery, forming a cascading failure. Method: Check the dependencies first. When dependencies fail, only an alarm will be issued and no restart will occur (exit 2 of this module script); the maximum number of restarts per hour; add RandomizedDelaySec to prevent all hosts from executing at the same second. Limitations: Dependency check itself may also misjudge, and it needs to be cross-verified with monitoring alarms (Prometheus).
Case 2: The replaced instance took away the accident scene
Problem:ASG replaced the instance due to a health check failure, the local journald was destroyed along with the instance, and the cause of the OOM could not be located. Method: Real-time forwarding of rsyslog / CloudWatch Agent; forwarding of key events (OOM, segfault, notify-failure) priority based on crit level; enable serial console logs / startup diagnostics on the cloud at the same time (Lesson 3/4). Limitations: Real-time forwarding has network and storage costs, and is filtered by program and level.
Case 3: cron "forgot the time zone" after migrating to systemd timer
Problem: The original cron ran at 02:00 in the local time zone. After the migration, OnCalendar=02:00 became a business peak on the UTC host. How to do it:OnCalendar supports explicit time zone: OnCalendar=*-*-* 02:00 America/Toronto, and verify it with systemd-analyze calendar. Limitations: The daylight saving time switch may be skipped or repeated, and critical tasks need to be idempotent.
Common errors and solutions
myapp-healthcheck.timer: Refusing to start, unit myapp-healthcheck.service to trigger not loaded.
Cause: The .service with the same name does not exist or has a syntax error; the timer triggers the service with the same name by default (can be specified with Unit=).
systemctl status myapp-healthcheck.service; systemd-analyze verify /etc/systemd/system/myapp-healthcheck.*
Fix: Correct the unit file and restart the timer after daemon-reload.
The timer shows that the LAST time is being updated, but there is no output from journalctl -t myapp-healthcheck
Cause: The script writes the log to stdout and is redirected, or SyslogIdentifier is inconsistent with the query label; it is also possible that the log is rate limited by journald.
journalctl -u myapp-healthcheck.service -n 20 --no-pager journalctl -u systemd-journald --since -1h | grep -i suppressed
Fixed: Query by unit with -u to confirm; align SyslogIdentifier=; adjust RateLimitIntervalSec=/RateLimitBurst= if necessary (journald.conf or LogRateLimit* in the unit).
rsyslogd: action 'action-0-builtin:omfwd' suspended (module 'builtin:omfwd'), retry 0. There should be messages before this one giving the reason for suspension.
Cause: The central server is unreachable, the port is not open, and the TLS handshake failed.
ss -tnp | grep 10514; nc -vz 127.0.0.1 10514 journalctl -u rsyslog -n 30 --no-pager
Fix: Repair the network/firewall; when there is a disk auxiliary queue, it will be automatically reissued after recovery (the action status changes to resumed).
OnFailure notification never fires, despite failed health check
Cause: The script eventually exit 0 (e.g. the last line was echo, or || true swallowed the failure); or the notification unit itself failed to start.
systemctl show myapp-healthcheck.service -p Result,ExecMainStatus systemctl list-units 'notify-failure@*' --all
Fix: Make sure the failure path is explicit exit 1 (available for bats test coverage); check logs for notify-failure.
1. Verify the next 3 trigger times of the expression "02:30 every weekday (Toronto time)".
systemd-analyze calendar --iterations=3 'Mon..Fri *-*-* 02:30 America/Toronto'
2. Count how many self-healing restarts myapp-healthcheck has performed today, and the latest time.
journalctl -t myapp-healthcheck --since today -o short-iso | grep 'action=restart unit=' | tee /dev/stderr | wc -l
Management requires that "any exception in myapp must be automatically recovered and notified within 1 minute." What are the limitations of your health screening program? What else do you need?
Limitations: ① Single-machine self-check cannot find "the entire host is unreachable" (downtime, network isolation) - external detection is required (load balancing health check, Blackbox exporter, cloud availability test); ② Just looking at /healthz cannot detect performance degradation and error rate increase - requires indicators and alarms (Prometheus' RED indicator); ③ Self-healing is only applicable to faults that can be "solved by restarting". Dependency faults, configuration errors, and data problems require manual labor; ④ Notifications require deduplication and upgrade (alarm platform instead of every minute webhook). Supplement: Load balancing layer health check + automatic removal; Prometheus + Alertmanager; centralized logs for post-analysis; clear whitelist and upper limit of "automatic repair", as well as operation manual.
Verified teaching video
Official documentation
- systemd.timer(5) · systemd.unit(5)(OnFailure=) · systemd.time(7)
- journald.conf(5)(ForwardToSyslog, ForwardToSocket) · systemd-journal-upload
- rsyslog omfwd · rsyslog queue
- Cloud: Azure Monitor Agent · CloudWatch Agent
Video storyboard script (about 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: The myapp process icon is still there, but it is frozen by ice; systemd's Restart switch has no response.
Narration: The process is still alive, but is no longer responding. Automatic restart cannot handle this "suspended death".
Screen: The stopwatch timer strikes once every minute. The health check first looks at Redis and then healthz. After failure, restart and review. The counter shows "1st time this hour".
Narration: Use the systemd timer to run a health check every minute. Check dependencies first, then the application. There is an upper limit on the number of restarts.
Screen: Log entries flowing from journald into rsyslog, piling up in queues during network outages, and flooding to the central server upon recovery.
Narration: rsyslog uses a disk queue to forward logs to the center without losing them even if the network is interrupted.
Screen: On failure the OnFailure arrow triggers the notification unit and the phone receives the message.
Narration: If it really cannot be repaired, leave it to the person on duty to notify OnFailure.
Module 8 · Summary, self-test and cleanup in the first five hours
- Use a knowledge map to review Lessons 1–5: Core Basics → System Management → Azure → AWS → Automated Operation and Maintenance, and describe the key mechanisms and products of each lesson.
- Identify the ten most common types of errors in the first five lessons, and use the interactive troubleshooting tree to locate "operation and maintenance scripts/image construction/image startup/patch/drift/log" issues.
- Use the cleanup script with dry-run to delete all cloud resources (VMs, disks, managed images, Compute Gallery versions, AMIs, snapshots, SSM parameters) created in Lessons 3–5 and confirm that the charges are reset to zero.
What: Five hours of knowledge map
| Lesson | Topic | Core Mechanism | The product you made |
|---|---|---|---|
| Lesson 1 | Core basics | Kernel/user space, Shell parsing → PATH → fork/exec, permission determination (owner/group/other/ACL), process and signal, apt/dnf, grep/sed/awk | Experimental machine linuxlab, manual operation myapp |
| Lesson 2 | System management and production readiness | systemd unit and dependencies, journald, LVM and file system, network and DNS, SSH Reinforcement, scheduled tasks | myapp.service (/opt/myapp, /etc/myapp/myapp.env, port 5000) |
| Lesson 3 | Towards the cloud platform (Azure) | First boot: Firmware → Kernel → cloud-init Read IMDS in each stage → Agent registration; Managed identity; Entra ID login; AMA + DCR; Update Manager | rg-linux-lab / vm-linux-lab(canadacentral) |
| Lesson 4 | Towards the Cloud Platform (AWS) | AL2023, user data, IMDSv2 token, instance profile credentials, SSM Session Manager, CloudWatch Agent, Patch Manager | EC2(ca-central-1, Name=linux-lab) |
| Lesson 5 | Automated operation and maintenance | Operation and maintenance script convention (link to Bash course), Packer build life cycle, generalization and reinforcement, image version and deprecation, automatic patching and restart strategy, drift detection and Ansible, timer self-healing and log forwarding | ops repository + CI, Gallery version/AMI, drift-check, health check timer, centralized log configuration |
Why: Why do we need to summarize and clean up in Lesson 5
The first five lessons constitute a complete closed loop of "single Linux host from zero to production"; Chapter 6 The lesson begins with security hardening and kernel mechanisms (SELinux/AppArmor, nftables, auditd, namespaces/cgroups), and lesson 7 is in-depth troubleshooting. Before moving to the next stage, connect scattered knowledge and clean up cloud resources that generate costs.
How: The ten most common types of errors in the first five lessons
| # | Error | Appear in | Memory points |
|---|---|---|---|
| 1 | Variables are not quoted, || true Swallow failed | Lessons 1 and 5 | Write "$var" by default; the provisioning script must exit non-zero if it fails (Bash lesson) |
| 2 | Hot fix does not write back, configuration drift | Lesson 5 | drift-check, --check --diff, write back image or playbook |
| 3 | Permissions are too wide (777, private key 644) | Lessons 1 and 2 | Minimum permissions; SSH rejects overly wide key permissions |
| 4 | I changed the unit file and forgot daemon-reload | Lessons 2 and 5 | systemctl cat See the effective content |
| 5 | Fstab is written incorrectly and cannot be started | Lesson 2 | findmnt --verify, nofail |
| 6 | cloud-init / user data fails without knowing | Lesson 3 and 4 | cloud-init status --long, /var/log/cloud-init-output.log |
| 7 | Putting long-term credentials on the instance | Lesson 3, 4 | Managed Identity/Instance Profile + IMDS |
| 8 | Image not generalized (machine-id, host key, build user) | Lesson 5 | cloud-init clean --machine-id, deprovision, put it in the last step |
| 9 | Only install the patch without restarting | Lessons 3, 4, and 5 | /var/run/reboot-required |
| 10 | Forgot to clean up cloud resources (especially snapshots, images, public IP) | Lesson 3, 4, 5 | Clean and review by tag/resource group |
When: Timing and sequence of cleanup
If you continue to lesson 6 immediately, local linuxlab reserved (section 6 Lessons will be done on it and rhellab for reinforcement); Cloud resources are now cleaned (Lessons 6 and 7 do not rely on Azure/AWS resources and can be recreated when needed). Sequence: first delete the consumer (VM/instance), then delete the product (image, AMI → snapshot), and finally delete the container (resource group) and network/security group.
az group delete --no-wait Return immediately, actual deletion is performed in the background, please review. Knowledge Map: From a command to a service that can be automatically operated and maintained
Cleaning the map: which resources will be continuously billed
Interactive Knowledge Map: Five Lessons Flash Cards
Click on a lesson to randomly select a "Mechanism Question", answer it mentally first, and then click "Show Answer". The verification command corresponding to this question is shown below.
Cleaning command
| Command | Function | Description |
|---|---|---|
az resource list -g rg-linux-lab -o table | List all resources in the resource group | Run once before and after cleanup |
az group delete -n rg-linux-lab --yes --no-wait | Delete the entire resource group | az group wait --deleted -n rg-linux-lab Wait for completion |
aws resourcegroupstaggingapi get-resources --tag-filters Key=Name,Values=linux-lab | Find all AWS resources by tag | Across services (EC2, volumes, snapshots...) |
aws ec2 terminate-instances, deregister-image, delete-snapshot | Delete instance, AMI, snapshot | The root volume is deleted by default when the instance is terminated (DeleteOnTermination) |
multipass stop linuxlab / multipass delete --purge linuxlab | Stop or completely delete the local lab VM | Lesson 6 still requires linuxlab, it is recommended to only stop |
Cleanup script with dry-run: bin/cleanup-lab.sh
#!/usr/bin/env bash
# cleanup-lab.sh [-y] - List and (when -y is added) delete the cloud resources for Lessons 3–5. Default dry-run.
set -Eeuo pipefail
REGION=ca-central-1 RG=rg-linux-lab GAL=gallinuxlab PARAM=/linux-lab/myapp/ami/latest yes=0
[[ ${1:-} == -y ]] && yes=1
act() { if (( yes )); then echo "+ $*" >&2; "$@"; else echo "DRY-RUN: $*" >&2; fi; }
echo "== Azure"
if command -v az >/dev/null && az account show >/dev/null 2>&1; then
if [[ $(az group exists -n "$RG") == true ]]; then
az resource list -g "$RG" -o json | jq -r '.[] | " \(.type)\t\(.name)"'
mapfile -t vers < <(az sig image-version list -g "$RG" -r "$GAL" -i myapp --query '[].name' -o tsv 2>/dev/null || true)
for v in "${vers[@]}"; do act az sig image-version delete -g "$RG" -r "$GAL" -i myapp -e "$v"; done
act az group delete -n "$RG" --yes --no-wait
else echo " $RG not found"; fi
az group list -o json | jq -r '.[] | select(.name|startswith("pkr-Resource-Group")) | .name' \
| while read -r g; do act az group delete -n "$g" --yes --no-wait; done
else echo " az not logged in, skipped"; fi
echo "== AWS ($REGION)"
if command -v aws >/dev/null && aws sts get-caller-identity >/dev/null 2>&1; then
mapfile -t iids < <(aws ec2 describe-instances --region "$REGION" \
--filters Name=tag:Name,Values=linux-lab,packer-builder-linux-lab \
Name=instance-state-name,Values=pending,running,stopping,stopped \
| jq -r '.Reservations[].Instances[].InstanceId')
if (( ${#iids[@]} )); then
printf ' instance %s\n' "${iids[@]}"
act aws ec2 terminate-instances --region "$REGION" --instance-ids "${iids[@]}"
fi
if aws ssm get-parameter --region "$REGION" --name "$PARAM" >/dev/null 2>&1; then
act aws ssm delete-parameter --region "$REGION" --name "$PARAM"
fi
aws ec2 describe-images --region "$REGION" --owners self --include-deprecated --filters Name=tag:app,Values=myapp \
| jq -r '.Images[] | [.ImageId, (.BlockDeviceMappings | map(.Ebs.SnapshotId // empty) | join(","))] | @tsv' \
| while IFS=$'\t' read -r ami snaps; do
echo " ami $ami snapshots $snaps"
act aws ec2 deregister-image --region "$REGION" --image-id "$ami"
IFS=, read -ra sarr <<< "$snaps"
for s in "${sarr[@]}"; do act aws ec2 delete-snapshot --region "$REGION" --snapshot-id "$s"; done
done
else echo " aws not configured, skipped"; fi
(( yes )) || echo "Dry-run only. Re-run with -y to delete."
== Azure Microsoft.Compute/virtualMachines vm-linux-lab Microsoft.Compute/disks vm-linux-lab_OsDisk_1_… Microsoft.Network/publicIPAddresses vm-linux-labPublicIP Microsoft.Compute/images img-myapp-1.0.0-20261117094512 Microsoft.Compute/galleries gallinuxlab Microsoft.Compute/galleries/images gallinuxlab/myapp … DRY-RUN: az sig image-version delete -g rg-linux-lab -r gallinuxlab -i myapp -e 1.0.0 DRY-RUN: az group delete -n rg-linux-lab --yes --no-wait == AWS (ca-central-1) instance i-0a1b2c3d4e5f60718 DRY-RUN: aws ec2 terminate-instances --region ca-central-1 --instance-ids i-0a1b2c3d4e5f60718 DRY-RUN: aws ssm delete-parameter --region ca-central-1 --name /linux-lab/myapp/ami/latest ami ami-0123456789abcdef0 snapshots snap-0aa11bb22cc33dd44 DRY-RUN: aws ec2 deregister-image --region ca-central-1 --image-id ami-0123456789abcdef0 DRY-RUN: aws ec2 delete-snapshot --region ca-central-1 --snapshot-id snap-0aa11bb22cc33dd44 Dry-run only. Re-run with -y to delete.
The script follows the operation and maintenance script convention of module 1 (strict mode, default dry-run, clear exit code); delete the Gallery version first and then delete the resource group, so the deletion order is more controllable. --include-deprecated ensures that deprecated AMIs in module 4 are also listed. Language details such as arrays, mapfile, and TSV reading can be found in Bash hour 2 and Hour 5. If you created security groups, key pairs, IAM roles/instance configuration files, and CloudWatch log groups in Lesson 4, please delete them according to the commands of the "Cost, Cleanup, and Self-Test" module in Lesson 4 (most of them are not billed, but they are remnants that need to be cleaned up).
Experiment 8: Self-test + Cleanup (about 8 minutes)
cd ~/linuxlab/ops git log --oneline | head shellcheck -x bin/* packer/scripts/*.sh && (cd packer && packer fmt -check . && packer validate -syntax-only .) && echo "checks ok" sudo bin/drift-check | tail -1 systemctl list-timers myapp-healthcheck.timer apt-daily-upgrade.timer --no-pager
c3d9e10 feat: myapp-healthcheck timer, notify-failure 8a71f42 feat: drift-check and ansible baseline … checks ok drift=none
chmod +x bin/cleanup-lab.sh && bin/cleanup-lab.sh
bin/cleanup-lab.sh -y az group wait --deleted -n rg-linux-lab 2>/dev/null; az group exists -n rg-linux-lab aws ec2 describe-instances --region ca-central-1 --filters Name=tag:Name,Values=linux-lab \ --query 'Reservations[].Instances[].[InstanceId,State.Name]' --output text
false i-0a1b2c3d4e5f60718 terminated
az image list -o table; az disk list --query "[?diskState=='Unattached'].name" -o tsv aws ec2 describe-snapshots --region ca-central-1 --owner-ids self --query 'Snapshots[].SnapshotId' --output text aws ec2 describe-volumes --region ca-central-1 --filters Name=status,Values=available --query 'Volumes[].VolumeId' --output text aws ec2 describe-addresses --region ca-central-1 --query 'Addresses[].PublicIp' --output text
It is completed when all are empty. Local linuxlab please keep (continued in Lesson 6); multipass stop linuxlab when not in use.
Case 1: Long-term billing of orphan snapshots
Problem: The mirror pipeline produces AMIs every week, old AMIs are deregistered, but snapshots are not deleted, hundreds of snapshots accumulate in a year, and storage costs exceed computing costs. How to do it: The cleanup script also deletes the AMI associated snapshot; enable Amazon Data Lifecycle Manager's AMI policy or EC2 recycle bin rules; use Compute Gallery's end_of_life_date on the Azure side with the "Exclude latest" policy and delete old versions regularly. Limitations: Verify that no instances or launch templates are still referencing the AMI before deleting it.
Case 2: Use tags and resource groups to make cleanup easy
Problem: Experimental resources are scattered in the default resource group and default VPC. There are no unified tags, and you can only rely on memory when cleaning. How to: This course has agreed on the rg-linux-lab and Name=linux-lab tags since Lesson 3. Packer products also carry app=myapp; at the organizational level, Azure Policy "requires tags" and AWS tag policies are used to enforce them, and budget alerts are set. Restrictions: Some resources (such as some automatically created network interfaces and log groups) will not inherit labels and need to be reviewed separately.
Case 3: Maturity improvement from manual operation and maintenance to "automated operation and maintenance"
Problem: Every time the team goes online, they have to SSH to each machine to execute a long list of commands. How to do it: Follow the path of this lesson: Command → Robust scripting (strict mode, trap, log) → Testing and CI → Mirroring (Packer) → Automatic patching and health check → Centralized log → Configuration management (Ansible) and IaC (Terraform). Limitations: Each step requires investment in maintenance; start with the manual tasks that fail most and frequently.
Interactive troubleshooting tree: Operation and maintenance scripts/image building/image startup/patch/drift/timer and log
Common errors in the cleanup phase
(InvalidAMIID.InUse) / The image is being used by one or more launch templates
Cause: There are still instances, launch templates or ASGs referencing the AMI (unregister the AMI Usually allowed by itself, but deleting the snapshot will fail because the AMI is still registered: InvalidSnapshot.InUse).
aws ec2 describe-instances --region ca-central-1 --filters Name=image-id,Values=ami-… --query 'Reservations[].Instances[].InstanceId'
Fix: Delete the consumer first, then unregister the AMI, and finally delete the snapshot.
The resource group still exists after az group delete (Deleting state lasts for a long time)
Cause:--no-wait Background deletion; some resources (such as locked resources, NICs in use) prevent deletion.
az group show -n rg-linux-lab --query properties.provisioningState az lock list -g rg-linux-lab -o table
Fix: Wait for or remove the resource lock; check the activity log for the failure reason.
cleanup-lab.sh: aws: error: argument --instance-ids: expected at least one argument
Cause:The array was empty but the command was still called when there was no matching instance.
Fixed:Use (( ${#iids[@]} )) in the script to judge first (the script in this lesson has been processed). These kind of edge cases are exactly what tests should cover (Bash hour 7 · bats).
1. List all unmounted managed disks in the Azure subscription and their sizes.
az disk list -o json | jq -r '.[] | select(.diskState=="Unattached") | [.resourceGroup, .name, .diskSizeGB] | @tsv'
2. Find the snapshots in ca-central-1 that your account owns but is not referenced by any AMI (possibly orphans).
comm -23 \ <(aws ec2 describe-snapshots --region ca-central-1 --owner-ids self --query 'Snapshots[].SnapshotId' --output text | tr '\t' '\n' | sort) \ <(aws ec2 describe-images --region ca-central-1 --owners self --query 'Images[].BlockDeviceMappings[].Ebs.SnapshotId' --output text | tr '\t' '\n' | sort)
Please use "what you learned in the first five lessons" to describe: all the key links that a new myapp production VM goes through from scratch to being automatically operated and maintained.
① Image: Packer starts a temporary VM from the Ubuntu 26.04/AL2023 official image, provisions myapp (systemd unit of Lesson 2, /opt/myapp, /etc/myapp/myapp.env), hardens and smoke tests, captures after generalization and publishes as Gallery version / with deprecation time AMI; ② Deployment: IaC uses the image to create VM, cloud-init only writes the environment configuration, and obtains secrets through IMDS through the managed identity/instance configuration file (Lesson 3/4); ③ Start: firmware → kernel → systemd and start redis and myapp.service according to dependencies (Lesson 2); ④ Run: myapp-healthcheck timer self-test and self-healing, the log enters journald and is processed by rsyslog / AMA / CloudWatch Agent centralized; ⑤ Maintenance: unattended-upgrades automatically installs security updates, restarts within the window, and Update Manager / Patch Manager reports compliance; the image is rebuilt every week and replaced on a rolling basis; ⑥ Daily drift-check and Ansible --check --diff detect drift and write back; ⑦ All scripts and templates are checked by ShellCheck + packer validate + CI.
Verified instructional video
Official documentation
- az group delete · Azure Budget
- EC2: Deregistering AMIs and Cleaning Snapshots · AWS Budgets
- Next lesson: Lesson 6: Security Hardening and Kernel Mechanism
Video storyboard script (about 70 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: Five pieces of the puzzle fall in sequence: core foundation, system management, Azure, AWS, automated operation and maintenance, forming a complete server.
Narration: In five hours, we transformed myapp from manual operation to a mirrored, automatically patched, self-healing, and centralized log service.
Screen: The entries on the bill are grayed out line by line with the cleanup script: VM, Disk, Image, AMI, Snapshot.
Narration: The final step is cleaning. Delete the instance first, then delete the image and snapshot, and finally delete the resource group, and then check again.
Screen: Shield and core chip icon appear, titled "Lesson 6".
Narration: In the next lesson, we will enter security hardening and kernel mechanisms.
Command Cheat Sheet
Operation and maintenance script convention (see Bash class for details)
#!/usr/bin/env bash set -Eeuo pipefail tmp=$(mktemp -d); trap 'rm -rf -- "$tmp"' EXIT trap 'echo "<3>failed line=$LINENO" >&2' ERR exec 9>/run/lock/x.lock; flock -n 9 || exit 75 printf '<6>status=ok key=v\n' >&2 # systemd service logger -t tag -p user.err -- "msg" # Manually run systemd-run --wait --collect -p SyslogIdentifier=tag /usr/local/bin/x journalctl -t tag -p warning -o short-iso shellcheck -x bin/* packer/scripts/*.sh
Packer command
packer init . # required_plugins packer fmt -check -diff -recursive . packer validate [-syntax-only] -var-file=prod.pkrvars.hcl . packer inspect . ; echo 'var.x' | packer console . packer build -only='azure-arm.ubuntu' -var app_version=1.1.0 . packer build -on-error=abort -timestamp-ui . PACKER_LOG=1 PACKER_LOG_PATH=p.log packer build . packer plugins installed jq -r '.builds[] | [.builder_type,.artifact_id] | @tsv' manifest.json
HCL key points
variable "app_version" {
type = string
validation {
condition = can(regex("^[0-9]+[.][0-9]+[.][0-9]+$", var.app_version))
error_message = "must look like 1.2.3"
}
}
# Priority: default < PKR_VAR_x < *.auto.pkrvars.hcl < -var-file/-var
# env() can only be used in default; sensitive = true hide output
provisioner "shell" { only = ["azure-arm.ubuntu"] … }
environment_vars = ["CLOUD=${source.type}"]Generalization (last step)
apt-get -y autoremove --purge; apt-get clean cloud-init clean --logs --seed --machine-id rm -f /var/lib/systemd/random-seed journalctl --rotate; journalctl --vacuum-time=1s rm -f /root/.bash_history /home/*/.bash_history rm -f /etc/ssh/ssh_host_* # Cannot SSH again /usr/sbin/waagent -force -deprovision+user # Azure, finally # AWS: ssh_clear_authorized_keys = true
Image version
az sig create -g rg-linux-lab -r gallinuxlab
az sig image-definition create … --os-state Generalized --hyper-v-generation V2
az sig image-version list -g rg-linux-lab -r gallinuxlab -i myapp -o table
az sig image-version update … -e 1.1.0 --set publishingProfile.excludeFromLatest=true
aws ec2 describe-images --owners self --include-deprecated --filters Name=tag:app,Values=myapp
aws ec2 enable-image-deprecation --image-id ami-… --deprecate-at 2027-02-15T00:00:00Z
aws ssm put-parameter --name /linux-lab/myapp/ami/latest \
--type String --data-type aws:ec2:image --value ami-… --overwrite
# Packer: shared_image_gallery_destination{} · deprecate_at = timeadd(timestamp(),"2160h")Patch
systemctl list-timers 'apt-daily*' sudo unattended-upgrade --dry-run --debug apt-config dump | grep -i unattended sudo dnf install dnf-automatic; systemctl enable --now dnf-automatic.timer dnf updateinfo list --security; needs-restarting -r dnf check-release-update # AL2023 bin/patch-status.sh # One line of JSON
Restart strategy and maintenance window
cat /var/run/reboot-required.pkgs
sudo needrestart -b # KSTA / SVC
# /etc/needrestart/conf.d/*.conf: $nrconf{restart} = 'a';
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "03:30";
sudo systemctl edit apt-daily-upgrade.timer # OnCalendar= Clear first
sudo pro enable livepatch; canonical-livepatch status
sudo dnf kpatch auto; sudo kpatch list # RHELDrift and Ansible
comm -3 /etc/myapp-image/packages.txt <(dpkg-query -W -f='${db:Status-Abbrev}${Package}\n' | awk '$1=="ii"{print $2}' | sort -u)
sudo dpkg --verify # ??5?????? c /etc/…
sudo debsums -ce ; sudo rpm -Va
sudo sshd -T | grep -i passwordauthentication
sudo ansible-playbook -i localhost, -c local baseline.yml --check --diff
sudo apt-get install --reinstall -o Dpkg::Options::=--force-confmiss PKGTimer and log concentration
systemctl list-timers --all
systemd-analyze calendar --iterations=3 'Mon..Fri 02:30'
systemd-analyze verify x.service
OnFailure=notify-failure@%n.service
systemd-analyze cat-config systemd/journald.conf | grep -i forward
rsyslogd -N1 && systemctl restart rsyslog
action(type="omfwd" target="logsrv" port="514" protocol="tcp"
queue.type="LinkedList" queue.filename="fwd")
journalctl --directory=/var/log/journal/remote -t myappQuick troubleshooting table
| Phenomena | Check first | Common causes |
|---|---|---|
| The script triggered by the timer is "nothing" | systemctl show X -p Result,ExecMainStatus | SyslogIdentifier is inconsistent and the failure is swallowed by || true |
Packer Missing plugins | packer plugins installed | No packer init |
Packer Timeout waiting for SSH | PACKER_LOG=1 | No public network IP, security group source, proxy; or there are steps after generalization |
| Packer apt lock conflict | First provisioner | cloud-init / automatic update is still running |
| Clone machine-id / The host key is the same | cat /etc/machine-id, ssh-keygen -lf | generize.sh is not running or the order is wrong |
| New VM sshd cannot be started | Serial console, cloud-init status --long | The host key was deleted and the first boot was not rebuilt |
| Gallery version conflict | az sig image-version list | The version number was not incremented |
| The patch was installed but the vulnerability is still there | reboot-required, needrestart -b | No service/host restart; AL2023 Warehouse version lock |
| Drift detection is all noise | Report content | Compared versions instead of lists; no allow list created |
| Remote log not received | rsyslogd -N1, nc -vz | Port, firewall, rule filtering, ForwardToSyslog |
Recommended configuration fragment
*.sh text eol=lf bin/* text eol=lf *.hcl text eol=lf
PermitRootLogin no PasswordAuthentication no KbdInteractiveAuthentication no X11Forwarding no MaxAuthTries 3
[Service] Type=oneshot ExecStart=/usr/local/bin/task SyslogIdentifier=task TimeoutStartSec=10min Nice=10 IOSchedulingClass=idle ProtectSystem=full PrivateTmp=yes
Comprehensive experiment + final test
packer fmt -check and packer validate; ② Image 1.1.0 is pre-installed with health check timer, journald forwarding configuration and drift baseline, which has been reinforced and generalized; ③ Published as Gallery version 1.1.0 (1.0.0 is reserved for rollback) or AMI with deprecation time, and the "latest" pointer is updated only after passing the acceptance; ④ Instances started from the image run myapp upon startup and health checks,drift-check No drift, logs reach a centralized location; ⑤ practice a rollback; ⑥ clean up all cloud resources. Either just do Azure or just do AWS. cd ~/linuxlab/ops for c in shellcheck jq packer ansible; do command -v "$c" >/dev/null || echo "missing $c"; done shellcheck -x bin/* packer/scripts/*.sh && (cd packer && packer init . && packer fmt -check . && packer validate -var app_version=1.1.0 .)
myapp-healthcheck, notify-failure, drift-check, three systemd units and 60-forward.conf Copy to packer/files/, add at the end of install-myapp.sh :
install -m 0755 "$src/myapp-healthcheck" "$src/notify-failure" "$src/drift-check" /usr/local/bin/ install -m 0644 "$src/myapp-healthcheck.service" "$src/myapp-healthcheck.timer" \ "$src/notify-failure@.service" /etc/systemd/system/ install -D -m 0644 "$src/60-forward.conf" /etc/systemd/journald.conf.d/60-forward.conf systemctl daemon-reload systemctl enable myapp-healthcheck.timer # Only enable, do not start on the build machine
Add drift baseline after package cleanup in generalize.sh (Ubuntu): install -d /etc/myapp-image && dpkg-query -W -f='${db:Status-Abbrev}${Package}\n' | awk '$1=="ii"{print $2}' | sort -u > /etc/myapp-image/packages.txt (On AL2023, you can use rpm -qa --qf '%{NAME}\n' instead, or skip the package list check).
cd packer && packer build -timestamp-ui -var app_version=1.1.0 -only='azure-arm.ubuntu' . | tee build-1.1.0.log
az sig image-version list -g rg-linux-lab -r gallinuxlab -i myapp --query "[].{ver:name, excluded:publishingProfile.excludeFromLatest}" -o table
# Exclude 1.1.0 from "latest" before acceptance
az sig image-version update -g rg-linux-lab -r gallinuxlab -i myapp -e 1.1.0 --set publishingProfile.excludeFromLatest=true -o nonerun-instances, refer to the module 3 experiments), then within the instance:
cat /opt/myapp/VERSION; systemctl is-active myapp.service cat /etc/machine-id; journalctl --list-boots --no-pager | wc -l systemctl list-timers myapp-healthcheck.timer --no-pager journalctl -t myapp-healthcheck -n 2 --no-pager sudo /usr/local/bin/drift-check; echo "rc=$?"
1.1.0 active 5d8e… (different from other instances) 1 NEXT LEFT LAST PASSED UNIT ACTIVATES Tue 2026-11-17 12:05:41 UTC 31s Tue 2026-11-17 12:04:41 UTC 28s ago myapp-healthcheck.timer myapp-healthcheck.service Nov 17 12:04:41 vm-img-test myapp-healthcheck[1803]: check=http status=ok url=http://127.0.0.1:5000/healthz drift=none rc=0
sudo unattended-upgrade --dry-run with sudo needrestart -b; AL2023 running dnf check-release-update; running both patch-status.sh (copied to the instance), recording the number of security updates and whether a restart is required. logger -t myapp "final-lab" to verify that the logs arrive at the centralized location. # Acceptance passed: 1.1.0 participates in "latest" az sig image-version update -g rg-linux-lab -r gallinuxlab -i myapp -e 1.1.0 --set publishingProfile.excludeFromLatest=false -o none # Problem found: eliminated again, new instance returns to 1.0.0 (AWS: Change SSM parameters back to the previous version) az sig image-version update -g rg-linux-lab -r gallinuxlab -i myapp -e 1.1.0 --set publishingProfile.excludeFromLatest=true -o none
~/linuxlab/ops/bin/cleanup-lab.sh # dry-run first ~/linuxlab/ops/bin/cleanup-lab.sh -y
Acceptance Checklist
Open self-test (answer yourself first, then expand the reference answer)
1. app_version in variables.pkr.hcl defaults to 1.0.0, environment variable PKR_VAR_app_version=1.0.5, prod.auto.pkrvars.hcl is 1.1.0, command line -var app_version=1.1.1, what is the final value? What about removing the command line parameters?
The latter overrides the former: default < environment variables < *.auto.pkrvars.hcl < -var-file / -var. When there are command line parameters, it is 1.1.1; when removed, it is 1.1.0 (the auto file overwrites the environment variables).
2. Why generalize.sh must be the last provisioner? What happens if there is a file download step later?
It removes the SSH host key and on Azure the build user (waagent deprovision). Any subsequent steps that require a new SSH connection or rely on the build user will fail (handshake failure or authentication failure), and the build will report an error and roll back. Files that need to be downloaded should be completed before generalization.
3. If 50 clones share the same machine-id, what specific problems will occur?
systemd-networkd uses it to derive DHCP DUID, which may get conflicting addresses (especially IPv6); journald and centralized logs distinguish sources according to _MACHINE_ID, and logs from multiple machines are mixed together; some monitoring/security agents are registered according to machine-id, and only one is displayed; other identifiers generated by it (such as some licenses) will also be repeated.
4. What is the difference between AMI deprecation and deregistration? What are the functions of Gallery's exclude_from_latest and end-of-life dates respectively?
Deprecation (deprecate_at) just stops the AMI from appearing in other people's search results and gives a prompt. It can still be started with the ID, and the snapshot is still billed; it cannot be started again after logging out, and the snapshot still needs to be deleted separately. exclude_from_latest excludes this version from "latest" resolution (it will not be selected when referencing the image definition); the end-of-life date is an informative life cycle mark and will not be automatically deleted.
5. What problems do needrestart, /var/run/reboot-required and Livepatch solve respectively?
needrestart: Restart services that still map the old library after library update; reboot-required: Signal for kernel, glibc and other updates that require host restart to take effect; Livepatch / kpatch: patch some kernel high-risk vulnerabilities without restarting, and cannot replace regular restarting to the new kernel.
6. In the experiment of module 6, why did Ansible find the SSH coverage but not the figlet? How to make up for it?
Ansible only evaluates tasks declared in the playbook: SSH is explicitly checked via assert, while the figlet package and logrotate file are not declared. Compensation: Cover undeclared changes with baseline-based detection (package list comparison, dpkg --verify, AIDE); immutable deployment regularly replaces instances.
Final exam (12 questions, covering all modules)
Source and version description
| Topic | Verification conclusion | Source (Accessed 2026-11-17) |
|---|---|---|
| Ubuntu LTS | Current LTS is 26.04 (resolute), point version 26.04.1; 26.04 kernel package linux-image-generic 7.0.0-42 | meta-release-lts · packages.ubuntu.com |
| Ubuntu 26.04 packages | cloud-init 26.1-0ubuntu2, walinuxagent 2.15.0.1-0ubuntu2, needrestart 3.11-1ubuntu2, unattended-upgrades 2.12ubuntu9, systemd 259.5, systemd-journal-remote 259.5, rsyslog 8.2512.0, ansible-core 2.20.1-1, ansible 13.1.0, debsums 3.0.2.3, aide 0.19.2, jq 1.8.1, shellcheck 0.11.0; ubuntu-server Metapackage (1.570) relies on needrestart and unattended-upgrades; default sudo-rs and Rust coreutils | packages.ubuntu.com(resolute) |
| Bash course comparison | Strict mode, trap, mktemp, flock, log, and retry are Bash hour 4 modules 1–6 respectively; cron and systemd timer, CI are hour 6 modules 6–7; ShellCheck and bats are the 7th hour module 2 and 4; the exit status is the 1st hour module 6, the exit code is agreed to be the 3rd hour module 6 | This repository bash (README and sidebar of each lesson) |
| systemd and journald | Set $INVOCATION_ID in the service; SyslogLevelPrefix= is enabled by default (parse prefix); systemctl edit --stdin (v256); journald supports ForwardToSyslog / ForwardToSocket; journal-upload default port 19532 | systemd.exec · journald.conf(5) · systemd-journal-upload |
| Packer | 1.16.2 (2026-10-22); HashiCorp apt repository provides resolute package; BUSL 1.1 license (since 1.10); core built-in null / file builder, shell / file / shell-local provisioner, manifest and other post-processors; variable priority default < PKR_VAR_ < *.auto.pkrvars.hcl < -var-file/-var; env() can only be used for variable default values | Packer releases · HCL variables |
| Packer Azure plugin | v2.6.5 (2026-10-28); shared_image_gallery_destination (subscription, resource_group, gallery_name, image_name, image_version, target_region (replaces the deprecated replication_regions), storage_account_type, use_shallow_replication); shared_gallery_image_version_end_of_life_date, shared_gallery_image_version_exclude_from_latest; one of the managed image or Gallery targets must be specified; Linux generalization waagent -force -deprovision+user is the last step | packer-plugin-azure (builder/azure/arm/config.go for v2.6.5) |
| Packer Amazon Plugin | v1.8.4 (2026-11-02); deprecate_at (UTC YYYY-MM-DDTHH:MM:SSZ, no later than 10 years), deregistration_protection { enabled, with_cooldown }, ami_regions, imds_support, temporary_security_group_source_public_ip; SDK communicator ssh_clear_authorized_keys | packer-plugin-amazon (builder/common/ami_config.go for v1.8.4) |
| Packer Ansible plugin | v1.1.6(2026-07-14) | packer-plugin-ansible |
| cloud-init clean | Upstream latest 26.2; options --logs, --machine-id (write uninitialized, next boot by systemd Build), --seed, --configs, --reboot | cloudinit/cmd/clean.py · cloud-init CLI |
| Azure Ubuntu Image | Canonical:ubuntu-26_04-lts:server:latest (also server-arm64, minimal, etc.) | Canonical: Find Ubuntu images on Azure |
| AL2023 Redis/Valkey | AWS documentation provides Redis 6 → Valkey migration, dnf install valkey; this lesson AL2023 image uses Valkey | AL2023: Redis 6 to Valkey |
| dnf-automatic | RHEL 10: variant timer overrides automatic.conf apply_updates/download_updates; DNF: upgrade_type (default/security), reboot (never/when-changed/when-needed) | RHEL 10 · DNF Automatic |
| actions/checkout | v7.0.1 = 3d3c42e5aac5ba805825da76410c181273ba90b1 | actions/checkout |
| Others | myapp Conventions (/opt/myapp/app, /opt/myapp/venv, /etc/myapp/myapp.env root:myapp 0640, Type=exec, SyslogIdentifier=myapp, port 5000) are consistent with Lessons 1–4 | Lessons 1–4 of this course |
Video Verification Instructions
The following videos are via YouTube oEmbed The interface (https://www.youtube.com/oembed?url=…&format=json, 2026-11-17) verified the title and channel: Fireship "Bash in 100 Seconds" (I4EWvMFj37g), "Linux in 100 Seconds" (rrB13utjYV4); TechTooniya "Bash trap Command Explained: Catch SIGINT, SIGTERM, and Clean Up on EXIT" (SzSCsSV77q0); Nick Janetakis "Linting and Improving Your Bash Scripts with ShellCheck" (28Ygo05cLmo); Learn Linux TV "journalctl Basics: How to Easily Check Your Linux Logs" (0dG3vUYt7Uk), "Getting Started with cloud-init" (exeuvgPxd-E), "Ubuntu 24.04: How to Automate Updates with Unattended Upgrades" (y5_wPaHlcHQ), "Getting started with Ansible 01 - Introduction" (3RiVKs8GHYQ), "Automate Your Tasks with systemd Timers: A Step-by-Step Guide" (n6BuUgkZ5T0), "10 Tips for Hardening your Linux Servers" (Jnxx_IAC0G4); KodeKloud "HashiCorp Packer Tutorial: Building Custom Images for AWS, Azure, and Docker" (OmQRpi3CSjU); HashiCorp, an IBM Company "Learn Lab: HCP Packer: Build a golden image pipeline" (Im0YZr__bIw); Mike's Cloud Solutions "Fully Automated Azure VM Image Builds with Packer - A Complete Solution" (bhxAOsNLO9o); Red Hat Enterprise Linux "How to Achieve CIS Benchmark Compliance to Harden Linux Systems | Into the Terminal 120" (TVTQcEWMQa0); Thecornelis Training "Automatic Security Updates on Ubuntu with unattended-upgrades" (8HY7a1KUQ4M); John Savill's Technical Training "Azure Update Manager 2023 Edition" (LVmNh5YgBOQ), "Microsoft Azure Monitor Agent (AMA) and Data Collection Rule (DCR) Overview" (Z1zDlXCwI9k); Amazon Web Services "Back to Basics: Automating Patching of EC2 Instances Using Systems Manager" (MhfKh35fols); TechWorld with Nana "What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners" (1id6ERvfozo); Jeff Geerling "Ansible 101 - Episode 4 - Your first real-world playbook" (SLW4LX7lbvE); Better Stack "Setup Centralized Logging with Rsyslog" (JocDslKu3j4); Digital Cloud Training "Install the Amazon CloudWatch Agent and Log to CloudWatch Logs" (7UlFuwONrvQ). What is verified is the title and channel. The length and specific content of the video have not been viewed one by one. The description is based on the title and public information. There is no specifically explained and verifiable video on image generalization (machine-id, host key) and configuration drift detection. A storyboard script has been provided.
Voice explanation instructions
The "Voice" page uses the browser's Web Speech API (speechSynthesis, en-US) to read the explanation script in real time. English terms are pronounced in en-US. The effect depends on the voice installed on the system. This courseware generation environment cannot call the TTS service, so there is no embedded MP3; when offline audio is needed, the lecture notes can be generated by TTS services such as Azure AI Speech.
Known limitations
- The experimental commands, Packer templates and scripts in this lesson are not actually executed in the production environment (including
packer validate/build, Ansible playbook and cloud CLI); IP, instance/AMI/snapshot in "Expected Output" ID, machine-id, fingerprint, time, count, kernel iteration, and tool log wording are all example values. Please refer to the actual output during the experiment. - Packer plugin parameter names have been verified against v2.6.5 / v1.8.4 source code, but used in combination (e.g. publishing to Gallery only, end-of-life time format generated by
timeadd(), image definitionSecurityType=TrustedLaunchSupportedand untrusted launch build VM Compatibility) has not been verified by the actual build; when encountering incompatibility, refer to the plug-in documentation and error messages. - After deleting the SSH host key in
generalize.sh, this lesson assumes that subsequent internal steps of Packer (such asssh_clear_authorized_keys) reuse the existing connection; if you encounter connection problems, you can remove the explicit deletion and instead rely onssh_deletekeyswhen cloud-init is first started. - Needrestart's configuration keys (
$nrconf{restart},$nrconf{override_rc}) and-boutput field meanings are written according to upstream documentation and common usage, please refer to the localneedrestart.confcomments; Livepatch / kpatch requires subscription and is not actually enabled. - The output format of
dpkg --verify, the default content of/etc/logrotate.d/rsyslogin Ubuntu 26.04 (rotate 4), the distribution default of ForwardToSyslog and the executable path of systemd-journal-remote are not in Practical verification on 26.04, the inspection methods are given in the lesson. - sudo-rs' support for environment retention options such as
sudo -Ehas not been verified one by one. This lesson uniformly uses the writing method ofsudo env VAR=… cmd; the availability and price of HCP Packer are subject to the official HashiCorp, and this lesson does not rely on it. aws ec2 deregister-image --delete-associated-snapshotsThe availability depends on the AWS CLI version. In this lesson, deleting snapshots separately is the main method.- The time, steps and logs in the animation are schematic and used to illustrate the mechanism; the real output is subject to the actual version.