root access

$ cat job-board-api/part-32.md

Building a Job Board API, Part 32: The Fresh Machine Found Two Bugs

Building a Job Board API, Part 32: The Fresh Machine Found Two Bugs

Where we are

Hi, I’m Reza. In my newsletter, Root Access, I am sharing one of my projects from the very beginning: a Job Board API built with Django, Postgres, Docker, AWS and Azure. I am a junior engineer looking for my first SRE, DevOps or Cloud job, and that is why I build my projects in public. You can see how I think, what breaks, and how I fix it.

In the last three parts, I built dev-toolchain, a shared Ansible role that installs and verifies a project’s local tools. Every test so far ran on thor, my home lab machine. And thor already had almost everything. So most “install” steps only ever skipped.

The Setup’s “Done when” line is:

One command readies a fresh machine, and a second run reports changed=0.

Two things were missing for that:

  • One command. So far it was several: install uv, install Ansible, install the role, run the playbook. Ansible can’t install itself.
  • A fresh machine. I needed a clean Ubuntu 26.04 with nothing on it, which I can throw away and rebuild every time.

So this part adds a bootstrap script and a fresh-machine test. And the fresh machine did exactly what it was for: it found two real bugs that thor had been hiding.

Three fresh runs and two fixes to reach changed=0

Each bug became a tagged patch release, and the project’s pin moved with it.

scripts/bootstrap.sh: one command

Ansible can’t install itself, and ansible-galaxy must run before the playbook. So a small shell script wraps everything. It takes a bare Ubuntu machine with only sudo to a ready dev toolchain.

#!/usr/bin/env bash
# One command readies an Ubuntu machine for this project. Run from anywhere:
#   ./scripts/bootstrap.sh            (extra arguments go to ansible-playbook, e.g. --tags verify)
# Safe to run again: everything below installs only what's missing.
set -euo pipefail
  • #!/usr/bin/env bash. The script uses bash arrays, so it must not run under sh, which is dash on Ubuntu.
  • set -euo pipefail makes bash strict:
    • -e: stop at the first failing command. Without it, a failed apt-get install would let the script continue and fail later with a confusing error.
    • -u: an unset variable is an error. A typo like $UV_VERSON stops the script.
    • -o pipefail: a pipeline fails if any part fails. Without it, curl … | sh would count as a success even if curl failed.
    UV_VERSION="0.13.0"                       # same uv as the Dockerfile and the dev-toolchain role
    cd "$(dirname "$0")/.."                   # the repo root, where ansible.cfg and bootstrap.yml live
    export PATH="$HOME/.local/bin:$PATH"      # uv and ansible-core install here
    • One uv version everywhere: the Dockerfile, the role, and this script.
    • cd “$(dirname “$0″)/..” goes to the repo root, wherever you run the script from. Ansible reads ansible.cfg from the current folder, so running from somewhere else would lose roles_path and inventory.
    • export PATH. On a fresh machine, ~/.local/bin isn’t on PATH until the next login. Without this line, command -v uv would fail right after installing uv.

    Step 1: Ansible’s own prerequisites

    missing=()
    for pkg in curl git python3-apt; do
      dpkg -s "$pkg" >/dev/null 2>&1 || missing+=("$pkg")
    done
    if [ ${#missing[@]} -gt 0 ]; then
      echo "==> Installing prerequisites: ${missing[*]}"
      sudo apt-get update -qq
      sudo apt-get install -y -qq "${missing[@]}"
    fi
    • Three packages Ansible needs before the role can run: curl for the uv installer, git so ansible-galaxy can clone the role, and python3-apt for the apt module (my old trap from Part 29).
    • dpkg -s asks the package database if a package is installed. Only the exit code matters.
    • || missing+=(…) adds the package only if the check failed. The || also stops set -e from ending the script on that “failure”.
    • On a machine that has all three, nothing runs: no sudo, no apt-get update. So a rerun is fast and quiet.
    • -y means no “Do you want to continue?” prompt, which would hang a script.

    Step 2: uv, then Ansible

    if ! command -v uv >/dev/null 2>&1; then
      echo "==> Installing uv ${UV_VERSION}"
      curl -LsSf "https://astral.sh/uv/${UV_VERSION}/install.sh" | sh
    fi
    if ! command -v ansible-playbook >/dev/null 2>&1; then
      echo "==> Installing ansible-core"
      uv tool install "ansible-core>=2.17"
    fi
    • command -v is the POSIX way to ask “is this command on PATH?”.
    • curl -LsSf: -L follows redirects, -s is silent, -S still shows errors, and -f fails on HTTP errors, instead of piping an HTML error page into sh. With pipefail, a failed download stops the script.

    Step 3: the role, then the playbook

    ansible-galaxy role install -r requirements.yml
    if sudo -n true 2>/dev/null; then ask=(); else ask=(--ask-become-pass); fi
    ansible-playbook bootstrap.yml "${ask[@]}" "$@"

    The middle line answers one question: when should Ansible ask for the sudo password?

    • sudo -n true means “run true with sudo, but never prompt”. It works only if sudo needs no password, for example in a test container or with a recently cached password.
    • If it works, ask is empty, and Ansible doesn’t ask. If not, ask is –ask-become-pass (the long form of -K).
    • Why it matters: with -K always on, the container test would wait for a password that nobody types. With -K never on, a normal laptop would fail on the first sudo task. This way, the same script works in both places.
    • “$@” passes on any arguments. So ./scripts/bootstrap.sh –tags verify runs only the health check from Part 31.

    A fresh machine in a container

    A real new laptop for every test would take hours. A VM would be closer to real, but slower and more setup. So I used an ubuntu:26.04 container as a throwaway “fresh machine”. It is clean every time, and it is the same release as thor.

    # A "fresh Ubuntu 26.04" for testing scripts/bootstrap.sh: a normal user with sudo, nothing else.
    FROM ubuntu:26.04
    RUN apt-get update \
     && apt-get install -y --no-install-recommends sudo \
     && rm -rf /var/lib/apt/lists/* \
     && useradd --create-home --shell /bin/bash dev \
     && echo "dev ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/dev \
     && chmod 0440 /etc/sudoers.d/dev
    USER dev
    WORKDIR /home/dev
    • Only sudo is installed. No curl, no git, no python3-apt, no Docker. Everything the script needs, it must install itself. That is what “fresh” means.
    • –no-install-recommends. No extra suggested packages that could hide a missing prerequisite.
    • rm -rf /var/lib/apt/lists/* deletes the package index. It keeps the image small, and it makes the test honest: the script must run apt-get update itself, like on a real machine.
    • A normal user, dev, not root. The role installs things per user, in ~/.local/bin. Testing as root would hide bugs. And this detail is what exposed both bugs: dev is not in the docker group at the start.
    • NOPASSWD lets the test run unattended. It also tests the sudo -n true branch of the script, the one without -K.
    • chmod 0440 is the standard mode for sudoers files. sudo ignores files with unsafe permissions.

    Running the test

    docker build -t jobboard-fresh scripts/fresh-machine-test
    docker run -d --name jb-fresh -v /var/run/docker.sock:/var/run/docker.sock jobboard-fresh sleep infinity
    docker exec jb-fresh mkdir -p /home/dev/app
    git archive HEAD | docker exec -i jb-fresh tar -x -C /home/dev/app
    • sleep infinity keeps the container alive, so the bootstrap can run twice on the same machine. Run 2 proves idempotency only if it runs where run 1 ran.
    • The mounted Docker socket. The role installs the Docker client inside the container, and it talks to thor’s daemon through the socket. This has a limit, which I come back to at the end.
    • git archive HEAD | tar -x copies only committed files into the container. A file I forgot to commit, or .env, or roles/, won’t be there. That is why I committed every fix before each test.
    docker exec jb-fresh bash -c 'cd ~/app && time ./scripts/bootstrap.sh' > /tmp/fresh-run1.txt 2>&1; echo "run 1 exit: $?"
    grep -E "\"msg\"|fatal|^localhost|^real" /tmp/fresh-run1.txt
    docker exec jb-fresh bash -c 'cd ~/app && ./scripts/bootstrap.sh' > /tmp/fresh-run2.txt 2>&1; echo "run 2 exit: $?"
    tail -4 /tmp/fresh-run2.txt

    The full output goes to a file for debugging. Then grep shows only the lines that matter: the version messages, failures, the recap, and the time. The exit code is the real signal: set -e and the verify assert mean a non-zero exit is a failure.

    Bug 1: awslocal was broken, only on a fresh machine

    The first fresh run on v0.2.0 installed everything, and then failed, after 1m10.6s:

    awslocal: MISSING OR BROKEN (exit 1)

    Every other tool passed. And on thor, this same check had always passed. The raw output showed the reason:

    Error: Docker is not available ... permission denied ... /var/run/docker.sock

    Here is the chain:

    1. lstk aws –version checks the Docker daemon first, even when it is only printing a version.
    2. The role had just added dev to the docker group.
    3. But in Linux, a new group membership only works after the next login. So dev still couldn’t reach the Docker socket.
    4. lstk printed its error on stdout, grep aws-cli/ found nothing, and the check failed.

    On thor, my user reza has been in the docker group for a long time. That hid the bug completely. This is exactly why the fresh-machine test exists.

    Note that the verify step did its job, too: it failed loudly and named the tool.

    The fix, v0.2.1

    In Part 31, only the Azurite check ran as root. Now there is a list of every check that talks to the Docker daemon:

    # Checks that talk to the Docker daemon. They run as root: right after the role adds the user to
    # the docker group, that membership only works after the next login (lstk aws checks Docker first).
    toolchain_verify_as_root: [azurite, awslocal]

    And the verify task uses it:

    become: "{{ tool in toolchain_verify_as_root }}"

    Jinja2’s in tests list membership. So every daemon-dependent check is listed, and explained, in one place.

    The other option was to tell the user to run the bootstrap again after logging in. But then the first run would always fail on a new machine. That is not “one command”.

    The fix also adds a message, telling the user to log in again. Without it, their first docker ps after bootstrapping would fail with the same permission error, and no explanation.

    Before testing it on a fresh machine, I ran the role’s own test on thor with v0.2.1: awslocal: aws-cli/2.40.2 …, azurite: …3.37.0, and ok=46 changed=0 failed=0. The fix didn’t break the existing machine.

    Bug 2: the re-login message never appeared

    The fresh run on v0.2.1 passed: exit 0, failed=0, all 9 versions including awslocal, in 1m10.3s. Bug 1 was fixed. But the new message, dev was just added to the ‘docker’ group…, was missing.

    The cause: register keeps only the last run

    • tasks/tools/docker.yml runs twice per bootstrap: once for the docker tool, and again because azurite.yml includes it (Azurite needs Docker).
    • The first run of the group task added dev to the group. Result: changed.
    • The second run found dev already in the group. Result: ok. And register overwrote the first result.
    • So when the message task checked is changed, the saved result said “not changed”.

    The code looked correct. It only breaks when the same task runs twice.

    The fix, v0.2.2: a flag that can only be set

    - name: "docker | let {{ ansible_facts['user_id'] }} run docker without sudo"
      ansible.builtin.user:
        name: "{{ ansible_facts['user_id'] }}"
        groups: docker
        append: true
      become: true
      register: toolchain_docker_group
    
    # register keeps only the LAST run, and this file runs again via azurite. set_fact with a
    # `when` only ever SETS the flag, so a later "ok" run can't clear it.
    - name: docker | remember that the user was just added to the docker group
      ansible.builtin.set_fact:
        toolchain_docker_group_added: true
      when: toolchain_docker_group is changed
    • On the run where the group was added, the flag becomes true.
    • On any later run, is changed is false, so the task is skipped. A skipped set_fact doesn’t touch the flag. Once it is set, it stays set.
    • The comment explains why. The plain register version looks correct, and someone might “simplify” it back.

    The other option was to remove the second include from azurite.yml. But then a project that asks for azurite without docker would break.

    And the message, as the last task of the role:

    - name: Tell the user to log in again if they were just added to the docker group
      ansible.builtin.debug:
        msg: >-
          {{ ansible_facts['user_id'] }} was just added to the 'docker' group. Log out and back in
          (or run: newgrp docker) before using docker without sudo.
      when: toolchain_docker_group_added | default(false)
    • The last task, so the message shows near the end of the output, where people actually read.
    • newgrp docker starts a new shell with the group active, a shortcut instead of a full logout.
    • | default(false). A project that doesn’t ask for docker never runs docker.yml, so the flag doesn’t exist. Without default, the when would fail with “undefined variable”.
    • Not tagged verify. The health check doesn’t change groups, so the message doesn’t apply there.

    Testing a “first time” fix needs a real first time

    I couldn’t test v0.2.2 in the old container. There, dev was already in the docker group, so the message would never show. So I built a brand-new container for the final test.

    Final results

    Run 1 on v0.2.2, in a brand-new container:

    • exit 0, ok=54 changed=14 failed=0
    • all 9 version lines, plus dev was just added to the ‘docker’ group…
    • 1m9.4s from a bare Ubuntu with only sudo to a ready toolchain

    Run 2, in the same container:

    • exit 0, ok=43 changed=0 failed=0 skipped=23
    • no group message, because nothing was added

    Run 2 has fewer ok tasks (43 instead of 54), because the install steps, the flag and the message are now skipped. Everything is already there.

    Every fix is a pushed, tagged release in the role repo: v0.1.0, v0.2.0, v0.2.1 and v0.2.2. The project’s requirements.yml was bumped and committed before each test.

    Done when: “one command readies a fresh machine, and a second run reports changed=0.” Met.

    One honest note: I didn’t paste a thor role test for v0.2.2. The fresh run covers it, because the container fetched v0.2.2 from GitHub and passed.

    Known limitations

    • The container can’t prove the Docker daemon starts on a fresh install. It uses thor’s daemon through the socket. On a real new machine, the docker.io package starts the daemon with systemd.
    • “Present” means any version, except the pinned tools. lstk 1.4.5, uv 0.13.0 and the Azurite image are pinned. Everything else is whatever is current that day. I measured it: the fresh machine got aws-cli 2.40.3, while thor has 2.40.2. For a dev toolchain that is acceptable, because the app’s runtime versions are pinned in its Dockerfile and lockfile.
    • The role assumes the machine’s apt sources work.
    • The first docker use without sudo needs a re-login. The role says so, but it can’t do it for you.

    What I learned

    • A machine that already has everything can’t test your installer. thor hid both bugs. The fresh machine found them.
    • Linux reads group membership at login. Anything in the same run that needs the new group must run as root.
    • register keeps only the last run of a task. If a task can run twice, use a set_fact flag that is only ever set.
    • Test only what is committed. git archive HEAD makes forgotten files visible.
    • Strict bash: set -euo pipefail, and check-then-act with dpkg -s and command -v, so a rerun does nothing.
    • sudo -n true lets one script work both unattended and on a laptop.
    • Patch releases for bug fixes. v0.2.1 and v0.2.2, each pinned by the project.

    What is next

    The Setup phase is done: one command, a fresh machine, and changed=0 on the second run. And my next projects can use the same role, pinned to the version they want.

    $ ls -t root-access/ | head -3

    Building a Job Board API, Part 31: Installed Is Not the Same as Working job-board-api · 31/32 10 min Building a Job Board API, Part 30: Deprecated Tools and a Versioned Role job-board-api · 30/32 14 min Building a Job Board API, Part 29: One Ansible Role for Every Project job-board-api · 29/32 14 min

    Leave a comment

    Your email address will not be published. Required fields are marked *