# Copyright 2025-2026 mrveiss # SPDX-License-Identifier: Apache-2.0 --- # AutoBot - Update All Fleet Nodes (Git-Based Deploy) # Deploys committed code from a specific branch to all fleet VMs. # Pulls directly from GitHub to /opt/autobot/code_source on the SLM manager, # then uses git archive to create deploy tarballs. (#1170) # # Runs FROM: SLM Manager host (see inventory) — NOT from the dev machine. # # Usage: # ansible-playbook playbooks/update-all-nodes.yml # ansible-playbook playbooks/update-all-nodes.yml -e deploy_ref=release # ansible-playbook playbooks/update-all-nodes.yml -e skip_branch_check=true # ansible-playbook playbooks/update-all-nodes.yml --skip-tags restart -e autobot_restart_services=false # code-only, no restarts (#20743) # # Tags: # restart - all service restart tasks (skip for code-only deploys) # deps - pip install / npm ci tasks and the Node.js upgrade (skip for code-only deploys) (#1603, #19661) # backend - autobot-backend deploy + restart tasks # frontend - autobot-frontend deploy + build + nginx restart tasks # npu, npu-worker - NPU worker deploy + restart tasks # browser, browser-worker - browser worker deploy + restart tasks # slm, slm-backend, slm-frontend - SLM node deploy + build + restart tasks # slm-agent - slm_agent role redeploy (code + secrets + restart) (#11480) # shared - autobot_shared deploy tasks (all nodes) # # NOTE (#20743): restarts come from two places, and a sync without restarts has to # stop both. Restart TASKS are tagged `restart`. Restart HANDLERS (the agent's # `Restart SLM agent` among them, notified by its code, config and secrets) cannot # be: Ansible ignores tags on handlers. Each restart handler checks # `autobot_restart_services` instead. So a code-only push is # --skip-tags restart -e autobot_restart_services=false # which is what code sync passes when "restart after sync" is off # (services/sync_restart.py). Every service then keeps running its old code until # its next restart. The agent's pip install is tagged `packages` (not `deps`, #11480); # use `--skip-tags slm-agent` to exclude the agent redeploy entirely. # ============================================================================= # PLAY 0: Pre-flight Git Safety Check & Create Deploy Archives # ============================================================================= - name: "Play 0 - Pre-flight & Build Archives" hosts: localhost gather_facts: false vars: github_repo: "https://github.com/mrveiss/AutoBot-AI.git" # #15705 derived this from `autobot.base_dir`; #15731 had to take the # base_dir half back out. This play runs on `hosts: localhost`, and # referencing ANY key of the `autobot` mapping makes Ansible render the # WHOLE mapping -- including `autobot.services.frontend`, which is # "http://{{ frontend_host }}:{{ frontend_port }}". Those host vars exist # only for real inventory hosts, so on localhost the lookup dies with # "'frontend_host' is undefined" before task one, taking every self-update # with it. The four pip sites in Plays 1/2/2b keep the derived form: they # run against inventory hosts where the mapping renders. # # An explicit `code_source_dir` override still steers this; only the # fallback is a literal, and it cannot be derived until # `autobot.services` stops carrying unrendered templates (#15731). git_repo_root: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}" deploy_ref: "main" # #20214: a rollback sets this and a full commit id as `deploy_ref` (services/rollback_target.py). The id # was validated as an ancestor of the branch head before it got here, so the branch allow-list does not # apply; and the commit is NOT announced to /code-source/notify below, which would record it as the # latest commit and make every node read as current at an old commit. deploy_is_rollback: false allowed_branches: - main - release skip_branch_check: false deploy_tmp: "/tmp/autobot-deploy" tasks: - name: "[PRE-FLIGHT] Verify required host groups exist" fail: msg: >- Required groups 'slm_server' and 'infrastructure' not found. Use: ansible-playbook -i inventory/slm-nodes.yml playbooks/update-all-nodes.yml Or run against production.yml which now includes these group aliases. when: >- (groups['slm_server'] | default([]) | length == 0) or (groups['infrastructure'] | default([]) | length == 0) # #16310: no `depth:` -- a shallow clone made services/sync_deletions.py's # bootstrap plan (`git log --diff-filter=AR` over the WHOLE history) see # only the one commit this fetch kept, so it silently reported "nothing # to delete" instead of the years of genuinely-deleted files it should # have found, and the (empty, "successful") plan still wrote the marker # -- permanently locking every target into diff-mode from a bad # baseline. pre-flight-code-sync.yml and provision-fleet-roles.yml clone # the same repo without `depth:` already; this playbook was the one # inconsistent with them. - name: "[PRE-FLIGHT] Sync code from GitHub" git: repo: "{{ github_repo }}" dest: "{{ git_repo_root }}" version: "{{ deploy_ref }}" force: true # #16310: no `depth:` above stops a FUTURE clone from starting shallow, # but the checkout that is actually on disk came from initial # provisioning, before that -- it is shallow today regardless, and a # plain `git fetch` on an already-shallow repo does not deepen it. Every # component's own bootstrap plan needs full history # (services/sync_deletions.py's `git log --diff-filter=AR`), so this # runs once here, before any component's plan, through the same # scrubbed-env git helper (services/git_subprocess.py:run_git_capture) the # planner itself uses -- never an ad-hoc `git fetch` in this playbook. - name: "[PRE-FLIGHT] Ensure code_source has full history, not a shallow clone (#16310)" ansible.builtin.command: cmd: >- {{ autobot.base_dir }}/autobot-slm-backend/venv/bin/python3 {{ git_repo_root }}/autobot-slm-backend/scripts/sync_deletion_planner.py ensure-full-history --repo-root {{ git_repo_root }} # Query/fixup step, like the git-status commands around it -- ansible's # own change-tracking is not meaningful here. Failure is NOT swallowed: # the command module's default failed_when (rc != 0) still fails this # task, and the CLI's own contract (#16310) is to exit 1 with the # reason on stdout whenever it could not guarantee full history. changed_when: false - name: "[PRE-FLIGHT] Get current git branch" command: git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} branch --show-current register: git_branch changed_when: false - name: "[PRE-FLIGHT] Resolve deploy ref to commit" command: >- git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} log -1 --format='%h %s' {{ deploy_ref }} register: deploy_info changed_when: false - name: "[PRE-FLIGHT] Check for uncommitted changes" command: git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} status --porcelain register: git_dirty changed_when: false - name: "[PRE-FLIGHT] Display deployment summary" debug: msg: - "=======================================================" - " AutoBot Fleet Code Update (GitHub Pull)" - "=======================================================" - "" - " Source: {{ github_repo }}" - " Branch: {{ deploy_ref }}" - " Commit: {{ deploy_info.stdout }}" - " Method: git pull → git archive" - "" - name: "[PRE-FLIGHT] ABORT - Not on allowed branch" fail: msg: >- Branch '{{ deploy_ref }}' not in allowed list ({{ allowed_branches | join(', ') }}). Override: -e skip_branch_check=true when: - not skip_branch_check | bool - not deploy_is_rollback | bool - deploy_ref not in allowed_branches - name: "[PRE-FLIGHT] Create deploy archive directory" file: path: "{{ deploy_tmp }}" state: directory mode: '0755' - name: "[PRE-FLIGHT] Create component archives" shell: >- git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} archive {{ deploy_ref }} -- {{ item.path }} | gzip > {{ deploy_tmp }}/{{ item.name }}.tar.gz loop: - { name: slm-backend, path: autobot-slm-backend/ } - { name: slm-frontend, path: autobot-slm-frontend/ } # #20942: .python-version rides in the SAME archive as autobot_shared, so the Python # floor python_floor.py reads comes from the deploy_ref checkout that supplied the # code, lands on every node that unpacks it, and precedes every backend restart. - { name: shared, path: "autobot_shared/ .python-version" } # #15462: both frontends declare `file:` dependencies on these two # (@autobot/ui, @autobot/terminal, @autobot/vnc). npm installs them as # symlinks INTO the deployed tree, so a frontend build resolves them # from /opt/autobot/, not from the synced source. Never having shipped # them was invisible for as long as nothing new was exported from # them; #14907 moved the shared composables into @autobot/ui and the # SLM frontend build then failed on MISSING_EXPORT for a symbol that # existed in the repo and not on the host. - { name: libs, path: libs/ } - { name: plugins, path: autobot-plugins/ } - { name: backend, path: autobot-backend/ } - { name: frontend, path: autobot-frontend/ } - { name: npu-worker, path: autobot-npu-worker/ } - { name: browser-worker, path: autobot-browser-worker/ } loop_control: label: "{{ item.name }}" changed_when: true # AI Stack lives under a different path shape (nested docker dir), so it # keeps its own archive task (ported from the retired top-level playbook, # #11424 — the aiml deploy must not be lost in the canonical consolidation). - name: "[PRE-FLIGHT] Create AI Stack archive" shell: >- git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} archive {{ deploy_ref }} -- autobot-infrastructure/shared/docker/ai-stack/ | gzip > {{ deploy_tmp }}/ai-stack.tar.gz changed_when: true tags: [always, ai-stack, aiml] - name: "[PRE-FLIGHT] Archives ready" debug: msg: "8 deploy archives created from {{ deploy_ref }} ({{ deploy_info.stdout }})" # --- Dependency change detection (#1603, #15430) --- # # #15430: this used to diff HEAD~1..HEAD — a ONE-COMMIT window — while a # deploy moves the installed tree from `.deployed_commit` to HEAD, which is # usually many commits. A manifest bump merged earlier than the last commit # therefore fell outside the window: the flag read false, `npm ci` was # skipped, and the build ran against a node_modules that no longer # satisfied package.json. That took /slm/ down with a 403 (the build failed # and left dist empty). The bump was 11 commits back when it happened. # # The marker is written AFTER the unarchive (see "Record deployed commit # marker" below), so at pre-flight it still holds the PREVIOUS deployment — # which is the correct base for "what is this deploy about to change". - name: "[PRE-FLIGHT] Read the currently deployed commit (#15430)" ansible.builtin.slurp: src: "{{ autobot.base_dir }}/autobot-slm-backend/.deployed_commit" register: deployed_commit_raw failed_when: false - name: "[PRE-FLIGHT] Resolve the dependency-diff base (#15430)" set_fact: # Empty when the marker is missing, unreadable, or blank — every one of # which means "we cannot prove what is installed". deps_diff_base: >- {{ (deployed_commit_raw.content | default('') | b64decode | trim) if (deployed_commit_raw.content is defined) else '' }} - name: "[PRE-FLIGHT] Get previous commit (before pull)" command: >- git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} rev-parse HEAD~1 register: prev_commit changed_when: false failed_when: false - name: "[PRE-FLIGHT] Check if Python deps changed" shell: >- git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} diff --name-only {{ deps_diff_base }} HEAD -- '*/requirements.txt' 'requirements.txt' 'constraints/' 'autobot_shared/pyproject.toml' when: deps_diff_base | length > 0 register: python_deps_diff changed_when: false failed_when: false - name: "[PRE-FLIGHT] Check if Node.js deps changed" shell: >- git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} diff --name-only {{ deps_diff_base }} HEAD -- '*/package.json' '*/package-lock.json' when: deps_diff_base | length > 0 register: node_deps_diff changed_when: false failed_when: false # #15430 (recovery): a commit diff answers "did a manifest change in this # span", which cannot see an install that is ALREADY out of sync. The host # that went down is exactly that case — the bump sits behind the deployed # commit, so no future diff will ever reveal it, and the build would keep # failing on every subsequent deploy. # # Ask the installed tree directly instead. `npm ls` exits non-zero when # node_modules does not satisfy package.json, which is the invariant that # actually matters. - name: "[PRE-FLIGHT] Check the installed node tree satisfies package.json (#15430)" ansible.builtin.command: cmd: npm ls --depth=0 chdir: "{{ autobot.base_dir }}/autobot-slm-frontend" register: node_tree_check changed_when: false failed_when: false # #20002: the Python half of the same recovery. The marker advances even when a run's pip step then # fails, so the bump leaves the diff window and no later run installs it. Only "Would install" counts: # a dry run that fails (no network, say) must not make an offline host's update depend on pip. It runs # from the component's directory because a manifest's editable is relative (#15733), and that editable # is always listed, so it is dropped or a healthy host would run pip on every update. # Reaches the venvs on this controller; a fleet node's venv still relies on the diff. - name: "[PRE-FLIGHT] Check the installed venvs satisfy their manifests (#20002)" ansible.builtin.shell: >- for c in autobot-slm-backend autobot-backend; do [ -x "{{ autobot.base_dir }}/$c/venv/bin/pip" ] || continue; cd "{{ git_repo_root }}/$c" || continue; "{{ autobot.base_dir }}/$c/venv/bin/pip" install --dry-run --disable-pip-version-check --retries 0 -r requirements.txt 2>/dev/null | grep '^Would install' | sed -E 's/ autobot[_-]shared-[^ ]+//' | grep -v '^Would install$'; done register: python_tree_check changed_when: false failed_when: false - name: "[PRE-FLIGHT] Set dependency change flags" set_fact: # #15430: when the deployed commit is unknown — marker missing, # unreadable, or blank — there is no way to prove what is installed, so # install. Skipping is what took /slm/ down; a redundant install costs # time and nothing else. python_deps_changed: >- {{ true if (deps_diff_base | length == 0) else ((python_deps_diff.stdout | default('') | length > 0) or ('Would install' in (python_tree_check.stdout | default('')))) }} # Either the manifests changed in this deployment span, OR the tree # already on disk does not satisfy them. The second disjunct is what # makes a drifted host self-heal instead of failing every deploy. node_deps_changed: >- {{ true if (deps_diff_base | length == 0) else ((node_deps_diff.stdout | default('') | length > 0) or (node_tree_check.rc | default(0) != 0)) }} - name: "[PRE-FLIGHT] Display dependency change status" debug: msg: - " Python deps changed: {{ python_deps_changed }}" - " Node.js deps changed: {{ node_deps_changed }}" - " Changed files: {{ (python_deps_diff.stdout_lines | default([])) + (node_deps_diff.stdout_lines | default([])) }}" - name: "[PRE-FLIGHT] Get full commit hash" command: git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} log -1 --format='%H' register: deploy_commit_full changed_when: false - name: "[PRE-FLIGHT] Get commit subject" command: git -c safe.directory={{ git_repo_root }} -C {{ git_repo_root }} log -1 --format='%s' register: deploy_commit_subject changed_when: false # #20250: Play 3 waits for this many nodes. A per-node update has --limit localhost, and # needn't wait for the whole fleet. Any other limit counts, a group name included: it can't be # told from a host here, and a wait of at most 3 minutes beats reporting nothing. - name: "[PRE-FLIGHT] Count the nodes online before the update" uri: url: "https://{{ slm_host }}/slm/api/health" validate_certs: false status_code: 200 register: fleet_nodes_before failed_when: false when: >- ansible_limit is not defined or (slm_manager_inventory_host | default('')) in ansible_limit.split(',') or not ('localhost' in ansible_limit.split(',') and (ansible_limit.split(',') | length) == 2) - name: "[PRE-FLIGHT] Notify SLM of new commit" uri: url: "https://localhost/api/code-source/notify" method: POST body_format: json body: node_id: "{{ slm_manager_node_id }}" commit: "{{ deploy_commit_full.stdout }}" branch: "{{ deploy_ref }}" message: "{{ deploy_commit_subject.stdout }}" is_code_source: true changed_roles: [] validate_certs: false status_code: [200, 404] ignore_errors: true when: not deploy_is_rollback | bool # ============================================================================= # PLAY 1: Update SLM Server First # ============================================================================= # #14336: `hosts: slm_server` deliberately EXCLUDES a node whose only role is # slm-agent (#14330 — that node has no /opt/autobot/code_source or # autobot-slm-backend checkout, so this play's manager-only tasks fail on it). # Such a node still needs its agent redeployed; `services/inventory_builder.py` # (`groups_for_role_tokens`, the `is_agent_only` branch) routes it into # `infrastructure` instead, so Play 2 below reaches it via the # `slm_node_id is defined` agent-redeploy task. Do not "fix" this by adding # agent-only nodes here — that reintroduces #14330. - name: "Play 1 - Update SLM Server First" hosts: slm_server gather_facts: false serial: 1 vars: deploy_tmp: "/tmp/autobot-deploy" tasks: - name: "[PLAY 1] Starting SLM Server Update" debug: msg: - "=======================================================" - " PLAY 1: SLM Server Update (git archive)" - "=======================================================" - " Target: {{ inventory_hostname }} ({{ ansible_host }})" # #19661: every host here runs npm, so it needs node_major. This comes before any code lands # on the host, and a failure stops the update here: the build needs this Node.js anyway. - name: "[PLAY 1] Ensure Node.js is on node_major" ansible.builtin.include_role: name: nodejs apply: tags: [slm, slm-frontend, deps] tags: [slm, slm-frontend, deps] # #16522/#16566 review: see [PLAY 2] Backend's identical note further # down -- the shared TLS cert-ensure task must be reachable from the # routine fleet updater, not just full provisioning. slm_manager needs # no ownership step beyond the shared task's own root:root 0600 default # (that redundant step was removed from the role itself in #16020). - name: "[PLAY 1] SLM | Ensure the shared node TLS cert" include_tasks: "../_shared/tasks/ensure_node_tls_cert.yml" tags: [slm, slm-backend] - name: "[PLAY 1] SLM | Deploy autobot-slm-backend" unarchive: src: "{{ deploy_tmp }}/slm-backend.tar.gz" dest: "{{ autobot.base_dir }}/" become: true tags: [slm, slm-backend] - name: "[PLAY 1] SLM | Deploy autobot-slm-frontend" unarchive: src: "{{ deploy_tmp }}/slm-frontend.tar.gz" dest: "{{ autobot.base_dir }}/" become: true tags: [slm, slm-frontend] - name: "[PLAY 1] SLM | Deploy autobot_shared" unarchive: src: "{{ deploy_tmp }}/shared.tar.gz" dest: "{{ autobot.base_dir }}/" become: true tags: [slm, shared] # #15462: must land BEFORE the npm ci / build tasks below, which resolve # @autobot/ui and the plugins through symlinks into these directories. - name: "[PLAY 1] SLM | Deploy libs (workspace packages)" unarchive: src: "{{ deploy_tmp }}/libs.tar.gz" dest: "{{ autobot.base_dir }}/" become: true tags: [slm, slm-frontend, libs] - name: "[PLAY 1] SLM | Deploy autobot-plugins (workspace packages)" unarchive: src: "{{ deploy_tmp }}/plugins.tar.gz" dest: "{{ autobot.base_dir }}/" become: true tags: [slm, slm-frontend, plugins] - name: "[PLAY 1] SLM | Fix ownership (unarchive runs as root)" file: path: "{{ autobot.base_dir }}/{{ item }}" owner: autobot group: autobot recurse: true become: true loop: - autobot-slm-backend - autobot-slm-frontend - autobot_shared - libs - autobot-plugins tags: [slm] # #16310: `unarchive` above only extracts/overwrites -- it never removes a # path that dropped out of the tarball because it was deleted from # source, so deleted modules piled up here forever. One shared task file, # same contract roles/backend and roles/frontend use. - name: "[PLAY 1] SLM | Delete files removed from source: slm-backend (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "SLM Backend (self-update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot-slm-backend" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot-slm-backend" sync_deletions_owner: autobot tags: [slm, slm-backend] - name: "[PLAY 1] SLM | Delete files removed from source: slm-frontend (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "SLM Frontend (self-update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot-slm-frontend" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot-slm-frontend" sync_deletions_owner: autobot tags: [slm, slm-frontend] - name: "[PLAY 1] SLM | Delete files removed from source: autobot_shared (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "SLM autobot_shared (self-update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot_shared" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot_shared" sync_deletions_owner: autobot tags: [slm, shared] # #16310 review round 12, N3: `libs` and `autobot-plugins` are unarchived # above (#15462 -- both frontends resolve `file:` workspace deps into # these deployed trees) exactly like the three components above, and were # missing their own deletion pass -- a file dropped from either would # never be removed from a deployed host, contradicting the PR's own claim # that deletion runs after every component's sync. - name: "[PLAY 1] SLM | Delete files removed from source: libs (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "SLM libs (self-update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/libs" sync_deletions_target_dir: "{{ autobot.base_dir }}/libs" sync_deletions_owner: autobot tags: [slm, slm-frontend, libs] - name: "[PLAY 1] SLM | Delete files removed from source: autobot-plugins (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "SLM autobot-plugins (self-update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot-plugins" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot-plugins" sync_deletions_owner: autobot tags: [slm, slm-frontend, plugins] # #12223 (#12202): the self-update path deploys the SLM backend via the # unarchive above and never runs the slm_manager role — where the #12202 # marker-write lives — so without this the .deployed_commit marker is never # written and _get_slm_deployed_commit() always returns None (self-update # always fires, never skips-when-current). Record the just-deployed commit # here too, mirroring the slm_manager role, so the skip-check works. # # #15557: the write itself is defined once, in # roles/_shared/tasks/record_slm_deployed_commit.yml — this play used to # spell it out with a shell redirect and then fix the ownership that # redirect got wrong in a second task, while two of the four SLM entry # points wrote no marker at all. - name: "[PLAY 1] SLM | Record deployed commit marker (#12223, #12202, #15557)" ansible.builtin.include_tasks: ../roles/_shared/tasks/record_slm_deployed_commit.yml vars: deployed_commit_label: "[PLAY 1] SLM" deployed_commit_dir: "{{ autobot.base_dir }}/autobot-slm-backend" deployed_commit_owner: autobot tags: [slm] # #14624: render the systemd unit from the SAME task file the role uses. # # This play deploys the backend by unarchive and never runs slm_manager, so # the unit was refreshed only on a full provision. A host was found running # one from two months earlier, predating the AUTOBOT_PROJECT_ROOT line the # template has carried since #14575 -- and once #14544 raised instead of # guessing, the backend crash-looped with no in-band recovery, because the # endpoints that deploy a fix live in the service that will not start. # # `tasks_from` rather than a copied template task: a second copy is what # drifts, and the marker-write above is that mistake already made once. - name: "[PLAY 1] SLM | Refresh the backend systemd unit (#14624)" ansible.builtin.include_role: name: slm_manager tasks_from: service_units.yml tags: [slm, systemd] # #19051: the #14758 root-key back-fill, from the SAME task file the role # uses. Only the role ran it, and this play never runs the role, so a host # kept current by the updater alone never got a key: the backend rendered # `AUTOBOT_SECRETS_ROOT_KEY=` and every System vault call returned 503. It # runs here, before PLAY 2 renders the backend env from the SLM secrets # file. Add-only: an existing key is never rotated. - name: "[PLAY 1] SLM | Back-fill AUTOBOT_SECRETS_ROOT_KEY into the SLM secrets file (#19051)" ansible.builtin.include_role: name: slm_manager tasks_from: secrets_root_key.yml tags: [slm, secrets] # Issue #9225: slm-agent needs autobot_shared in PYTHONPATH - name: "[PLAY 1] SLM Agent | Create autobot_shared symlink for agent imports" ansible.builtin.import_tasks: ../roles/_shared/tasks/link_autobot_shared.yml vars: shared_link_component: autobot-slm-agent tags: [slm, slm-agent, shared] # Issue #9565: slm-backend needs autobot_shared in PYTHONPATH - name: "[PLAY 1] SLM Backend | Create autobot_shared symlink for backend imports" ansible.builtin.import_tasks: ../roles/_shared/tasks/link_autobot_shared.yml vars: shared_link_component: autobot-slm-backend tags: [slm, slm-backend, shared] # #12907/#12959: same role-owned reconciliation as PLAY 2, for the SLM # prefix. db-credentials.env is shared between both prefixes, and the parse # below takes the FIRST `DATABASE_URL=` match — so a pre-#12224 unmarked # duplicate feeds the migration a dead URL. Strip them before reading. - name: "[PLAY 1] SLM | Reconcile the SLM credential store (#12907, #12959)" ansible.builtin.include_role: name: postgresql tasks_from: credentials_reconcile apply: become: true vars: db_env_prefix: SLM tags: [slm, slm-backend, credentials] # # #19848: the role's postgresql.conf, so a change to a rendered setting (#19421's # listen_addresses) reaches an existing host. config_file skips a host without PostgreSQL, # needs no db_user and never touches pg_hba; PostgreSQL restarts only if the file changed. - name: "[PLAY 1] SLM | Apply PostgreSQL's server config (#19848)" ansible.builtin.include_role: name: postgresql tasks_from: config_file apply: become: true tags: [slm, postgresql] # --- SLM custom migrations (#1630) --- - name: "[PLAY 1] SLM | Load db credentials for migration (#2293)" slurp: src: /etc/autobot/db-credentials.env register: db_creds_file become: true failed_when: false tags: [slm, slm-backend, migrate] - name: "[PLAY 1] SLM | Parse DATABASE_URL from credentials (#2293)" set_fact: slm_db_url: "{{ (db_creds_file.content | b64decode | regex_search('DATABASE_URL=(.+)', '\\1'))[0] | default('') }}" when: db_creds_file is succeeded failed_when: false tags: [slm, slm-backend, migrate] - name: "[PLAY 1] SLM | Run database migrations (#1630)" command: cmd: >- {{ autobot.base_dir }}/autobot-slm-backend/venv/bin/python -m migrations.runner chdir: "{{ autobot.base_dir }}/autobot-slm-backend" become: true become_user: autobot environment: PYTHONPATH: "{{ autobot.base_dir }}/autobot-slm-backend" DATABASE_URL: "{{ slm_db_url | default('') }}" register: slm_migration_result failed_when: false tags: [slm, slm-backend, migrate] - name: "[PLAY 1] SLM | Warn if migration failed (#1630)" debug: msg: "WARNING: SLM migration failed: {{ slm_migration_result.stderr | default('') }}" when: - slm_migration_result is defined - slm_migration_result.rc | default(0) != 0 tags: [slm, slm-backend, migrate] # --- Dependency install (#1603) --- # #19973: pip stops at a husk (uninstall-no-record-file) and cannot reach the update that fixes it. - name: "[PLAY 1] SLM | Clear venv husks before pip (#17339)" ansible.builtin.include_tasks: file: ../roles/_shared/tasks/clear_venv_husks.yml apply: tags: [slm, slm-backend, deps] vars: repo_source_root: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}" # #20509 husk_venv_dir: "{{ autobot.base_dir }}/autobot-slm-backend/venv" when: hostvars['localhost']['python_deps_changed'] | bool tags: [slm, slm-backend, deps] - name: "[PLAY 1] SLM | Install Python dependencies" command: cmd: >- {{ autobot.base_dir }}/autobot-slm-backend/venv/bin/pip install -r {{ autobot.base_dir }}/autobot-slm-backend/requirements.txt -c {{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/constraints/shared.txt --quiet --timeout 120 become: true become_user: autobot environment: PIP_DEFAULT_TIMEOUT: "120" timeout: 600 # Issue #2835: prevent indefinite hang on dependency resolution conflicts when: hostvars['localhost']['python_deps_changed'] | bool register: slm_pip_install tags: [slm, slm-backend, deps] - name: "[PLAY 1] SLM | Install Node.js dependencies" command: cmd: npm ci --ignore-scripts chdir: "{{ autobot.base_dir }}/autobot-slm-frontend" become: true become_user: autobot when: (hostvars['localhost']['node_deps_changed'] | bool) or (_nodejs_upgraded | default(false) | bool) register: slm_npm_install tags: [slm, slm-frontend, deps] # #15430/#15557: vite empties its outDir before writing, so a build that # fails leaves `dist/` with nothing in it and nginx answers 403 for every # /slm/ path. The staged build-then-swap that prevents that is defined once, # in roles/_shared/tasks/build_publish_slm_frontend.yml, because it used to # live here and in three other entry points that never received the fix # (#15557). - name: "[PLAY 1] SLM | Build and publish the frontend (staged, #15557)" ansible.builtin.include_tasks: ../roles/_shared/tasks/build_publish_slm_frontend.yml vars: slm_frontend_publish_label: "[PLAY 1] SLM" slm_frontend_publish_dir: "{{ autobot.base_dir }}/autobot-slm-frontend" slm_frontend_publish_user: autobot tags: [slm, slm-frontend] # #11480/#11492: redeploy the slm-agent BEFORE the backend restart. The # backend restart below kills this fire-and-forget playbook (KillMode= # control-group, #11492), so anything after it never runs — the agent # deploy must land here, and flush_handlers forces the role's restart # handler to fire now (handlers otherwise run at play end, i.e. never). # Idempotent role; block/rescue keeps a failure from aborting Play 1. - name: "[PLAY 1] SLM Agent | Redeploy agent (code + secrets + restart) (#11480)" tags: [slm, slm-agent] block: # #11480: the slm_agent role's version.json/service/config templates use # ansible_facts['date_time'], but this play runs gather_facts:false — so # the role failed at "Deploy version.json" (AnsibleUndefinedVariable: # date_time) and the agent never redeployed. Gather the minimal fact set # (includes date_time) just before the import. - name: "[PLAY 1] SLM Agent | Gather minimal facts for role templates (#11480)" ansible.builtin.setup: gather_subset: ["min"] - name: "[PLAY 1] SLM Agent | Import slm_agent role" ansible.builtin.import_role: name: slm_agent - name: "[PLAY 1] SLM Agent | Flush handlers so the agent restarts before the backend self-restart" ansible.builtin.meta: flush_handlers rescue: - name: "[PLAY 1] SLM Agent | Warn on agent redeploy failure" ansible.builtin.debug: msg: >- WARNING: slm_agent redeploy failed on {{ inventory_hostname }} — agent may run stale code / miss agent-secrets.env (#11480). Continuing to backend restart. - name: "[PLAY 1] SLM | Restart backend service" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [slm, slm-backend, restart] vars: restart_unit_name: autobot-slm-backend restart_unit_daemon_reload: true tags: [slm, slm-backend, restart] # #15610: this play deploys the SLM backend by unarchive and never runs the # slm_manager role, so the nginx site config was refreshed only on a full # provision — the same gap #14624 found for the systemd unit. The served # path moved from `dist/` to the atomically-flipped `current` pointer, so a # host that publishes here and never re-renders would keep serving whatever # bundle the last provision aimed nginx at, silently, after a green deploy. # `tasks_from` rather than a copied template task: a second copy drifts. - name: "[PLAY 1] SLM | Re-render the nginx site config (#15610, #14624)" ansible.builtin.include_role: name: slm_manager tasks_from: nginx_site.yml apply: become: true tags: [slm, slm-frontend, nginx] - name: "[PLAY 1] SLM | Restart nginx" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [slm, slm-frontend, restart] vars: restart_unit_name: nginx tags: [slm, slm-frontend, restart] - name: "[PLAY 1] SLM | Wait for API to be ready" uri: url: "https://{{ ansible_host }}/slm/api/health" validate_certs: false status_code: 200 register: slm_health_check until: slm_health_check.status == 200 retries: 12 delay: 10 delegate_to: localhost tags: [always] # #19318: resolved by the one shared reader -- never a default password. Best-effort: # unresolved leaves it empty and the login below is refused, skipping sync tracking. - name: "[PLAY 1] SLM | Resolve the SLM admin password (#19318)" ansible.builtin.include_tasks: file: ../_shared/tasks/read_slm_admin_password.yml apply: tags: [always] vars: require_slm_admin_password: false tags: [always] - name: "[PLAY 1] SLM | Login to get auth token" uri: url: "https://{{ ansible_host }}/slm/api/auth/login" method: POST body_format: json body: username: "admin" password: "{{ slm_admin_password }}" validate_certs: false status_code: [200, 401, 403] register: slm_login_play1 delegate_to: localhost no_log: true failed_when: false tags: [always] - name: "[PLAY 1] SLM | Warn if login failed" debug: msg: "WARNING: SLM login failed (status {{ slm_login_play1.status }}) -- sync-tracking skipped (#2295)" when: slm_login_play1.status != 200 tags: [always] - name: "[PLAY 1] SLM | Mark node as synced in DB" uri: url: "https://{{ ansible_host }}/slm/api/code-sync/nodes/{{ slm_node_id | default(inventory_hostname) }}/mark-synced" method: POST headers: Authorization: "Bearer {{ slm_login_play1.json.access_token | default('') }}" Content-Type: "application/json" body: "{}" body_format: json validate_certs: false timeout: 30 status_code: [200, 404] register: slm_mark_synced_play1 # The SLM API is briefly slow on this endpoint right after a restart, so a # single attempt read-times-out and the node never gets marked synced # (#10634). Retry until it answers; still non-fatal if it never does. until: slm_mark_synced_play1.status | default(-1) in [200, 404] retries: 6 delay: 10 delegate_to: localhost ignore_errors: true when: slm_login_play1.status == 200 tags: [always] no_log: true # #19764: credentials in the request or response - name: "[PLAY 1] SLM Update Complete" debug: msg: - "SLM Server updated" - " Backend deployed + restarted" - " Frontend built + nginx restarted" - " SLM agent redeployed (#11480)" # ============================================================================= # PLAY 2: Update All Other Infrastructure Nodes # ============================================================================= # 11436: no longer excludes slm_server — a co-located SLM node (single-node # install) joins `infrastructure` via the registry inventory only when it also # carries app roles, so pure SLM servers still skip this play while co-located # backend/frontend/worker components finally receive updates. Ordering is # preserved: Play 1 updates the SLM components first. # #14336: an agent-only node (roles reduce to nothing but slm-agent — see # Play 1's note above) also joins `infrastructure` here, purely to reach the # "SLM Agent | Redeploy agent" task below (`when: slm_node_id is defined`, # true for every node). Every other task in this play stays gated on its own # `group_names` check, so an agent-only node runs that one task and nothing # else. - name: "Play 2 - Update Other Infrastructure Nodes" hosts: infrastructure gather_facts: false serial: 3 # A failed node update (most critically a failed backend database # migration) must abort the whole rollout instead of continuing to the # next node with a diverged fleet (#10026). any_errors_fatal: true vars: deploy_tmp: "/tmp/autobot-deploy" node_cert_dir: "{{ autobot_tls_remote_cert_dir | default('/etc/autobot/certs') }}" # #19366 pre_tasks: - name: "[PLAY 2] Resolve the SLM admin password (#19318)" ansible.builtin.include_tasks: file: ../_shared/tasks/read_slm_admin_password.yml apply: tags: [always] vars: require_slm_admin_password: false tags: [always] - name: "[PLAY 2] Login to SLM API" uri: url: "https://{{ slm_host }}/slm/api/auth/login" method: POST body_format: json body: username: "admin" password: "{{ slm_admin_password }}" validate_certs: false status_code: [200, 401, 403] register: slm_login delegate_to: localhost run_once: true no_log: true failed_when: false tags: [always] - name: "[PLAY 2] Warn if SLM login failed" debug: msg: "WARNING: SLM login failed (status {{ slm_login.status }}) -- sync-tracking skipped (#2295)" when: slm_login.status != 200 run_once: true tags: [always] - name: "[PLAY 2] Set SLM auth token" set_fact: slm_token: "{{ slm_login.json.access_token | default('') }}" delegate_to: localhost run_once: true tags: [always] tasks: # #19661: every host here runs npm, so it needs node_major. This comes before any code lands # on the host, and a failure stops the update here: the build needs this Node.js anyway. - name: "[PLAY 2] Ensure Node.js is on node_major" ansible.builtin.include_role: name: nodejs apply: tags: [frontend, browser, browser-worker, deps] when: "'frontend' in group_names or 'browser' in group_names" tags: [frontend, browser, browser-worker, deps] # #17243: the pip steps below constrain against constraints/shared.txt, but # they used to reference it inside `code_source` -- the git checkout, which # exists only on the manager. On an infrastructure node that path is absent # and pip aborts with "Could not open constraint file", the exact failure # scripts/build-filtered-requirements.sh warns about in its own header. # Stage the file onto the node and constrain against the local copy. # Tagged `always` deliberately. The staged file is a precondition for the # backend, npu/npu-worker, browser/browser-worker and deps task groups, so # a tag selection like `--tags backend` would otherwise skip the staging # and leave the pip step constraining against a file that is not there. # Enumerating the union of consumer tags would go stale the moment another # tagged consumer is added; `always` cannot, and this play already uses it. - name: "[PLAY 2] Ensure the constraints directory exists on the node (#17243)" ansible.builtin.file: path: "{{ autobot.base_dir }}/constraints" state: directory owner: autobot mode: "0755" become: true tags: [always] - name: "[PLAY 2] Stage constraints/shared.txt onto the node (#17243)" ansible.builtin.copy: src: "{{ playbook_dir }}/../../../constraints/shared.txt" dest: "{{ autobot.base_dir }}/constraints/shared.txt" owner: autobot mode: "0644" become: true tags: [always] - name: "[PLAY 2] Starting Node Update" debug: msg: - "=======================================================" - " PLAY 2: Node Update (git archive)" - "=======================================================" - " Target: {{ inventory_hostname }} ({{ ansible_host }})" # ----- Backend ----- # #16522/#16566 review: the shared TLS cert-ensure task ran only during # full provisioning (roles/backend/tasks/main.yml), never on a routine # fleet update -- an already-provisioned node whose cert expires between # provisioning runs would never get it refreshed here, and the builtin # updater is the only sanctioned path for that (CLAUDE.md: "System # updates ... go through the builtin updater only"). - name: "[PLAY 2] Backend | Ensure the shared node TLS cert" include_tasks: "../_shared/tasks/ensure_node_tls_cert.yml" when: "'backend' in group_names" tags: [backend] # #16522: EXISTENCE is consolidated in the shared task above; the backend # process reads the key as its own service user (autobot), not root like # the shared task's other consumers -- matching roles/backend/tasks/main.yml's # own "Set certificate key permissions" step. No cert-rotation condition # needed here: "[PLAY 2] Backend | Restart service" below already restarts # unconditionally on every run with the `restart` tag active. - name: "[PLAY 2] Backend | Set certificate key permissions" file: path: "{{ item }}" mode: "0600" owner: autobot group: autobot loop: - "{{ node_cert_dir }}/server-key.pem" - "{{ node_cert_dir }}/server-cert.pem" become: true when: "'backend' in group_names" tags: [backend] - name: "[PLAY 2] Backend | Deploy autobot-backend" unarchive: src: "{{ deploy_tmp }}/backend.tar.gz" dest: "{{ autobot.base_dir }}/" become: true when: "'backend' in group_names" tags: [backend] - name: "[PLAY 2] Backend | Deploy autobot_shared" unarchive: src: "{{ deploy_tmp }}/shared.tar.gz" dest: "{{ autobot.base_dir }}/" become: true when: "'backend' in group_names" tags: [backend, shared] - name: "[PLAY 2] Backend | Fix ownership" command: chown --no-dereference -R autobot:autobot {{ autobot.base_dir }}/autobot-backend become: true when: "'backend' in group_names" changed_when: true tags: [backend] # #16310 review round 6 (reachability): `unarchive` above only # extracts/overwrites -- it never removes a path deleted from source, and # this play (not roles/backend/tasks/main.yml) is what the builtin # updater actually runs for remote backend nodes (#12959 delivery # contract -- backend's role is applied only via targeted # `tasks_from`, never in full, so main.yml's own #16310 wiring never # reaches this host through Update All). - name: "[PLAY 2] Backend | Delete files removed from source: backend (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "Backend (fleet update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot-backend" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot-backend" sync_deletions_owner: autobot when: "'backend' in group_names" tags: [backend] # AC4 (#16310): same reachability gap as above -- moved to its own task # file (roles/backend/tasks/npu_workers_cleanup.yml) so it can be applied # here via `tasks_from`, the #12959-contract way, without dragging the # rest of the backend role's provisioning (apt, venv, service accounts) # onto every fleet update. - name: "[PLAY 2] Backend | Clean up legacy npu_workers.yaml duplicate (#16310)" ansible.builtin.include_role: name: backend tasks_from: npu_workers_cleanup vars: backend_code_dir: "{{ autobot.base_dir }}/autobot-backend" when: "'backend' in group_names" tags: [backend] - name: "[PLAY 2] Backend | Fix shared ownership (#1632)" file: path: "{{ autobot.base_dir }}/autobot_shared" owner: autobot group: autobot recurse: true become: true when: "'backend' in group_names" tags: [backend, shared] - name: "[PLAY 2] Backend | Delete files removed from source: autobot_shared (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "Backend autobot_shared (fleet update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot_shared" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot_shared" sync_deletions_owner: autobot when: "'backend' in group_names" tags: [backend, shared] - name: "[PLAY 2] Backend | Ensure autobot_shared symlink inside backend dir (#2651)" ansible.builtin.import_tasks: ../roles/_shared/tasks/link_autobot_shared.yml vars: shared_link_component: autobot-backend when: "'backend' in group_names" tags: [backend, shared, symlink] - name: "[PLAY 2] Backend | Remove legacy backend symlink" file: path: "{{ autobot.base_dir }}/autobot-backend/backend" state: absent become: true when: "'backend' in group_names" tags: [backend] # #19973: pip stops at a husk (uninstall-no-record-file) and cannot reach the update that fixes it. - name: "[PLAY 2] Backend | Clear venv husks before pip (#17339)" ansible.builtin.include_tasks: file: ../roles/_shared/tasks/clear_venv_husks.yml apply: tags: [backend, deps] vars: repo_source_root: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}" # #20509 husk_venv_dir: "{{ autobot.base_dir }}/autobot-backend/venv" when: - "'backend' in group_names" - hostvars['localhost']['python_deps_changed'] | bool tags: [backend, deps] - name: "[PLAY 2] Backend | Install Python dependencies" command: cmd: >- {{ autobot.base_dir }}/autobot-backend/venv/bin/pip install -r {{ autobot.base_dir }}/autobot-backend/requirements.txt -c {{ autobot.base_dir }}/constraints/shared.txt --quiet --timeout 120 # #15733: pip resolves a relative editable in a requirements file # against the CWD, not against the file. This manifest opens with # "-e ../autobot_shared", so with no chdir it resolved against the # remote user home and pip refused the entire install. chdir: "{{ autobot.base_dir }}/autobot-backend" become: true become_user: autobot environment: PIP_DEFAULT_TIMEOUT: "120" timeout: 600 # Issue #2835: prevent indefinite hang on dependency resolution conflicts when: - "'backend' in group_names" - hostvars['localhost']['python_deps_changed'] | bool register: backend_pip_install tags: [backend, deps] # #12907/#12959: the credential-store reconciliation is owned by # roles/postgresql (tasks/credentials_reconcile.yml) and this play applied # neither the role nor an inline copy — so the #12907 fix was merged, closed # and inert: duplicate keys and the month-stale legacy store survived five # full self-update runs untouched. Applying the role's own task file keeps # ONE implementation and makes the fix reach hosts. # # Must precede the credential reads below so they see the reconciled file # rather than a stale first-match duplicate. - name: "[PLAY 2] Backend | Reconcile the AUTOBOT credential store (#12907, #12959)" ansible.builtin.include_role: name: postgresql tasks_from: credentials_reconcile apply: become: true vars: db_env_prefix: AUTOBOT when: "'backend' in group_names" tags: [backend, env, credentials] # #19848: as in PLAY 1 -- the backend role installs PostgreSQL for user management (#2953), # so its postgresql.conf follows the role on every Code Sync too. - name: "[PLAY 2] Backend | Apply PostgreSQL's server config (#19848)" ansible.builtin.include_role: name: postgresql tasks_from: config_file apply: become: true when: "'backend' in group_names" tags: [backend, postgresql] # Migrations moved AFTER the .env regen so they run with the fresh # credentials and BEFORE the service restart — see the # "Database migration sequence" block below (#10001/#10026; replaces the # old #1608 task that invoked alembic without -c migrations/alembic.ini # and swallowed the guaranteed failure with failed_when: false). - name: "[PLAY 2] Backend | Read existing secret key before .env regen (#2649)" ansible.builtin.shell: cmd: grep '^SECRET_KEY=' {{ autobot.base_dir }}/autobot-backend/.env | cut -d= -f2- register: existing_secret_key become: true become_user: autobot when: "'backend' in group_names" failed_when: false changed_when: false tags: [backend, env] # #10400: align AUTOBOT_JWT_SECRET with SLM_SECRET_KEY so the backend→SLM # WebSocket service-JWT verifies (SLM verifies with SLM_SECRET_KEY). The key # is written by the slm_manager role into /etc/autobot/slm-secrets.env. - name: "[PLAY 2] Backend | Read SLM_SECRET_KEY for backend_jwt_secret (#10400)" ansible.builtin.shell: cmd: >- grep -oP '^SLM_SECRET_KEY=\K.*' /etc/autobot/slm-secrets.env 2>/dev/null || true register: existing_slm_secret_key become: true when: "'backend' in group_names" failed_when: false changed_when: false no_log: true tags: [backend, env] # Internal service API key (#10636): the one resolution install shares (#20750). The SLM's # key is canonical; a backend whose key differs keeps it, visibly, because changing it needs # the owner's approval (#17038). Sets autobot_internal_api_key for the env_only render below. - name: "[PLAY 2] Backend | Resolve AUTOBOT_INTERNAL_API_KEY (#10636, #20750)" ansible.builtin.include_tasks: file: ../_shared/tasks/resolve_internal_api_key.yml apply: tags: [backend, env] # a dynamic include's tags don't reach its tasks without apply vars: internal_api_key_current_env_files: - "{{ autobot.base_dir }}/autobot-backend/.env" - "{{ autobot_backend_env_file }}" when: "'backend' in group_names" tags: [backend, env] # #21343: loaded BEFORE the key proposal below (it was after the DB-credential reads): `backend_port` # is the one the backend's unit and env render from, so the proposal's URL cannot disagree with the # port the service listens on, and it exists on the registry-built inventory, which sets none. Tagged # `always` ONLY (not `always, env`: a skip tag matches any tag on the task), so neither `--tags` nor # `--skip-tags` of a reader's tag can run the reader without it. - name: "[PLAY 2] Backend | Load shared backend env vars (#2727)" ansible.builtin.include_vars: file: vars/backend-env.yml when: "'backend' in group_names" tags: [always] # #20750: a mismatch is proposed for approval; an approved realign is claimed here and applied by # this run's render, restart and the verify step after "Wait for API to be ready". - name: "[PLAY 2] Backend | Propose or claim re-aligning the internal key (#20750)" ansible.builtin.include_tasks: file: ../_shared/tasks/realign_internal_api_key_claim.yml apply: tags: [backend, env] vars: internal_api_key_loaded_file: "{{ autobot.base_dir }}/autobot-backend/.env" internal_api_key_backend_url: "http://127.0.0.1:{{ backend_port }}" # pragma: allowlist secret -- a URL; vars/backend-env.yml (#21343) when: "'backend' in group_names" tags: [backend, env] # Full user management requires the autobot_app DB password (#10636). # # GH#12883: this used to read ONLY /etc/autobot/autobot-db-credentials.env. # On a live host that file was a month stale and held a value PostgreSQL # rejects — that is what tried to overwrite a working credential and would # have taken the database out on the next backend restart. # # /etc/autobot/db-credentials.env is the canonical store: PLAY 1 already # slurps it for the SLM migrations above, and its value is the one that # actually authenticates. Prefer it; keep the legacy file as a fallback for # hosts provisioned before it existed. # # `tail -n 1` is load-bearing, not defensive. db-credentials.env is appended # to rather than rewritten, so this key can appear more than once with the # CURRENT value LAST. That matches `set -a; . file` semantics (last # assignment wins); a `head -1` would read the stale first copy and # reintroduce the exact outage this fixes. - name: "[PLAY 2] Backend | Read autobot_app DB password (#10636, #12883)" ansible.builtin.shell: cmd: | k=AUTOBOT_DB_PASSWORD v=$(grep -oP "^${k}=\K.*" /etc/autobot/db-credentials.env 2>/dev/null | tail -n 1) if [ -z "$v" ]; then v=$(grep -oP "^${k}=\K.*" /etc/autobot/autobot-db-credentials.env 2>/dev/null | tail -n 1) fi printf '%s' "$v" register: existing_autobot_db_password become: true when: "'backend' in group_names" failed_when: false changed_when: false no_log: true tags: [backend, env] # Initial platform-admin password — backend seeds the default admin into # autobot_users at startup ONLY when this is set (#10636). Installer writes # AUTOBOT_ADMIN_PASSWORD alongside SLM_ADMIN_PASSWORD; fall back to the SLM # admin password so the user app and SLM share one admin credential. - name: "[PLAY 2] Backend | Read admin password for full-user-management seed (#10636, #19370)" ansible.builtin.include_tasks: file: ../_shared/tasks/read_admin_seed_password.yml apply: become: true tags: [backend, env] when: "'backend' in group_names" tags: [backend, env] # GH#12883: this render was unreachable until #12871 was fixed, and the first # time it ran it overwrote a WORKING AUTOBOT_POSTGRES_PASSWORD with one # PostgreSQL rejects — the next backend restart would have lost the database. # # Two stores claimed to hold this secret and they disagreed: # /etc/autobot/autobot-db-credentials.env (legacy, observed a month stale) # /etc/autobot/db-credentials.env (canonical; authenticates) # # The read task above now prefers the canonical store (last-wins), which is # the convergence this issue asked for. This check stays as defence in depth: # it costs nothing, and it still catches any host whose stores diverge for a # reason we have not seen yet. A visibly failed update is recoverable; a dead # credential on next restart is an outage. - name: "[PLAY 2] Backend | Read the DB password currently in use (#12883)" ansible.builtin.shell: cmd: >- grep -oP '^AUTOBOT_POSTGRES_PASSWORD=\K.*' {{ autobot.base_dir }}/autobot-backend/.env 2>/dev/null || true register: current_env_db_password become: true when: "'backend' in group_names" failed_when: false changed_when: false no_log: true tags: [backend, env] - name: "[PLAY 2] Backend | Refuse to overwrite a working DB password (#12883)" vars: _current: "{{ current_env_db_password.stdout | default('') | trim }}" _incoming: "{{ existing_autobot_db_password.stdout | default('') | trim }}" ansible.builtin.fail: msg: >- Refusing to rewrite .env: the DB password in /etc/autobot/autobot-db-credentials.env differs from the one currently authenticating in {{ autobot.base_dir }}/autobot-backend/.env. Writing it would break PostgreSQL auth on the next backend restart (#12883). Reconcile the two credential stores, then re-run. The working value is the one in the live .env. when: - "'backend' in group_names" - _current | length > 0 - _incoming | length > 0 - _current != _incoming tags: [backend, env] # GH#12871: was a bare playbook-level `template:` task, which cannot see the # backend role's defaults — it died on AnsibleUndefinedVariable # 'backend_chromadb_auth_token', failing PLAY 2 so PLAY 3 never ran. That # variable was only the first of 37 the template needs and this play does # not define. include_role puts the defaults in scope at role-default # precedence, so they fill the other 32 while the secret overrides below # (read off the live host) still win. include_vars would NOT be safe here: # it outranks task vars, so it would replace those secrets with the role's # empty / "change-me-in-production" placeholders. - name: "[PLAY 2] Backend | Regenerate .env from template (#2649, #12871)" ansible.builtin.include_role: name: backend tasks_from: env_only when: "'backend' in group_names" vars: backend_model_check_warn_only: true # #19731: this play is any_errors_fatal backend_env_dest: "{{ autobot.base_dir }}/autobot-backend/.env" backend_env_owner: autobot backend_env_group: autobot # backend_secret_key uses a register var specific to this playbook backend_secret_key: "{{ existing_secret_key.stdout | default(lookup('env', 'AUTOBOT_SECRET_KEY') | default('autobot-dev-secret-' + (9999999999 | random | string), true), true) }}" # #10400: prefer SLM_SECRET_KEY when present, else keep the role default. backend_jwt_secret: "{{ (existing_slm_secret_key.stdout | default('') | trim) if (existing_slm_secret_key.stdout | default('') | trim) | length > 0 else (existing_secret_key.stdout | default('') | trim) }}" # #10636: full-user-management DB password, read from /etc/autobot above. The internal # service API key is the fact resolved above (#20750), not passed here. backend_postgres_password: "{{ existing_autobot_db_password.stdout | default('') | trim }}" # #10636: seed the default platform admin on first boot (full user mgmt). autobot_admin_password: "{{ _admin_seed_password_read | default('') }}" tags: [backend, env] - name: "[PLAY 2] Backend | Read backend user mode (#10001)" ansible.builtin.shell: "grep -oP '^AUTOBOT_USER_MODE=\\K.*' {{ autobot.base_dir }}/autobot-backend/.env" become: true register: backend_user_mode_probe changed_when: false failed_when: false # absent .env/var = not yet configured; skip until set when: "'backend' in group_names" tags: [backend, migrate] - name: "[PLAY 2] Backend | Database migration sequence (#10001)" when: - "'backend' in group_names" - backend_user_mode_probe.stdout | default('') | trim != '' tags: [backend, migrate] block: # Strict migration sequence consolidated into one shared include # (#10046): fail-closed backup -> baseline adoption -> strict # `alembic upgrade head`. Single source for both this playbook and # setup-user-backend.yml. - name: "[PLAY 2] Backend | Run strict backend migration sequence (#10001, #10026, #10046)" ansible.builtin.include_tasks: ../_shared/tasks/migrate_backend_db.yml vars: migration_code_dir: "{{ autobot.base_dir }}/autobot-backend" migration_user: autobot migration_become: true migration_name_prefix: "[PLAY 2] Backend | " # #12777/#12959: the unit template is role-owned and this play never rendered # it, so the faulthandler fix stayed in the repo and never reached a host. # Must precede the restart below so the new unit is what gets started. - name: "[PLAY 2] Backend | Render systemd unit so role changes land (#12777)" ansible.builtin.include_role: name: backend tasks_from: unit_only when: "'backend' in group_names" tags: [backend, systemd, unit] # #18324: the deployed docs/ (read by the knowledge import) was synced only by # the role's main.yml, which this playbook never runs, so it froze at the last # provision. `tasks_from` the SAME file main.yml includes -- never a second # rsync -- and it ends with a recorded-commit vs code_source check. - name: "[PLAY 2] Backend | Refresh the deployed docs/ from code_source (#18324, #4100)" ansible.builtin.include_role: name: backend tasks_from: docs_sync apply: tags: [backend, docs] when: "'backend' in group_names" tags: [backend, docs] # #18324: same class as docs/ -- the core plugins/ sync lived only in main.yml. - name: "[PLAY 2] Backend | Refresh the core plugins/ from code_source (#18324, #10294)" ansible.builtin.include_role: name: backend tasks_from: plugins_sync apply: tags: [backend, plugins] # The role's `notify: restart backend` ignores --skip-tags; this play # restarts explicitly below, so suppress the handler here (#18324). vars: backend_plugins_sync_notify_restart: false when: "'backend' in group_names" tags: [backend, plugins] # #14866: seed the access control enforcement posture on every update. # Provisioning alone is not enough: every host in the fleet was provisioned # before the seeder existed and nothing re-provisions a working box, so # without this play they would sit at the unset key -- resolved as # `disabled` -- forever. Runs BEFORE the restart so the backend comes up # with a posture already in the flag store. # # `tasks_from` per the #12959 delivery contract: enforcement_mode.yml does # no provisioning, only one idempotent SET NX that never overwrites a value # an operator set deliberately. - name: "[PLAY 2] Backend | Provision access control enforcement mode (#14866)" ansible.builtin.include_role: name: access_control tasks_from: enforcement_mode when: "'backend' in group_names" tags: [backend, access-control, enforcement] - name: "[PLAY 2] Backend | Restart service" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [backend, restart] vars: restart_unit_name: autobot-backend restart_unit_daemon_reload: true when: "'backend' in group_names" tags: [backend, restart] # #13539: celery and celery-beat import the same tree this play just synced, # but they were never restarted. The role DOES define `restart celery` / # `restart celery beat` handlers (roles/backend/handlers/main.yml) and # main.yml notifies them — and this play never includes main.yml, only # env_only/unit_only/code_only, none of which contain a single `notify:`. # So the handlers are present, correct and unreachable, and the workers # served pre-deploy modules until someone restarted them by hand. Measured # on a live host: celery ran 7 days behind the code, and any task lazily # importing a symbol added in that window raised ImportError naming a file # that visibly contained it. # # Restarting explicitly rather than notifying the handlers, for the same # reason #13144 replaced the #13143 flush_handlers attempt: a handler only # fires when its task reports `changed`, so once a file is already current # the notify never happens and the restart silently does not occur. - name: "[PLAY 2] Backend | Check which celery units are installed (#13539)" ansible.builtin.stat: path: "/etc/systemd/system/{{ item }}.service" loop: - autobot-celery - autobot-celery-beat register: celery_unit_files when: "'backend' in group_names" tags: [backend, restart, celery] - name: "[PLAY 2] Backend | Restart celery workers so they run the synced code (#13539)" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [backend, restart, celery] vars: restart_unit_name: "{{ item.item }}" restart_unit_daemon_reload: true loop: "{{ celery_unit_files.results | default([]) }}" loop_control: label: "{{ item.item }}" when: - "'backend' in group_names" - item.stat is defined - item.stat.exists tags: [backend, restart, celery] # A host that carries the backend but no celery unit is a real deployment # shape, not an error — but it must be visible, because "celery was never # restarted" is exactly the silent condition #13539 is about. - name: "[PLAY 2] Backend | Report celery units that are absent (#13539)" ansible.builtin.debug: msg: >- {{ item.item }}.service is not installed on this host; nothing to restart. If this host is expected to run it, the backend role never applied its unit template. loop: "{{ celery_unit_files.results | default([]) }}" loop_control: label: "{{ item.item }}" when: - "'backend' in group_names" - item.stat is defined - not item.stat.exists tags: [backend, restart, celery] - name: "[PLAY 2] Backend | Wait for API to be ready" uri: # uvicorn binds plain HTTP on localhost:; nginx holds # TLS on 443. There is NO 8443 listener (#957/#10378). Probe the direct # backend on the loopback — it does not depend on nginx (deployed after # this task) and needs no cert validation (#10650). # # #11455: run ON the backend node (no delegate_to) so 127.0.0.1 is the # node's own loopback. backend_port is bound to localhost, so it is unreachable # from the controller — delegating to localhost only worked for a # co-located single-node backend and spun 42×10s against the wrong host # for any remote backend, aborting the rollout via any_errors_fatal. url: "http://127.0.0.1:{{ backend_port }}/api/health" # the port the unit renders from (#21343) status_code: 200 register: backend_health_check until: backend_health_check.status == 200 retries: 42 delay: 10 when: "'backend' in group_names" tags: [backend, restart] - name: "[PLAY 2] Backend | Check the re-aligned internal key works, and report it (#20750)" ansible.builtin.include_tasks: file: ../_shared/tasks/realign_internal_api_key_verify.yml apply: tags: [backend, restart] vars: internal_api_key_backend_url: "http://127.0.0.1:{{ backend_port }}" # pragma: allowlist secret -- a URL; vars/backend-env.yml (#21343) when: - "'backend' in group_names" - internal_api_key_realign_applying | default(false) | bool tags: [backend, restart] # ----- Frontend ----- # #16522/#16566 review: see the Backend section's identical note above -- # the shared TLS cert-ensure task must be reachable from the routine # fleet updater, not just full provisioning. - name: "[PLAY 2] Frontend | Ensure the shared node TLS cert" include_tasks: "../_shared/tasks/ensure_node_tls_cert.yml" when: "'frontend' in group_names" tags: [frontend] # #16566: nginx (root) and the autobot-frontend systemd service (runs as # the autobot user/group, not root -- its dev-mode --https --key flag) # both need to read this key; 0640 root:autobot covers both without the # world-readable mode the role's own task used to set. See # roles/frontend/tasks/main.yml's "Frontend | Set TLS key permissions" # for the full reasoning. - name: "[PLAY 2] Frontend | Set TLS key permissions" file: path: "{{ node_cert_dir }}/server-key.pem" mode: "0640" owner: root group: autobot become: true when: "'frontend' in group_names" tags: [frontend] # ----- VNC ----- # #16020: a node whose only cert-consuming role is vnc (no backend, no # frontend) matches neither section above, so it never got the shared # keypair through this playbook -- the ONLY path a GUI/self-update reaches # (CLAUDE.md: "System updates ... go through the builtin updater only"). # Gated on the role_active_facts.yml fact, not a group_names membership # check: vnc has no entry in services/inventory_builder.py::_ROLE_TO_GROUPS # (the map this playbook's dynamic inventory groups come from), so testing # group_names here would silently exempt exactly this node. - name: "[PLAY 2] VNC | Ensure the shared node TLS cert" include_tasks: "../_shared/tasks/ensure_node_tls_cert.yml" when: "role_vnc_active | default(false) | bool" tags: [vnc] - name: "[PLAY 2] Frontend | Deploy autobot-frontend" unarchive: src: "{{ deploy_tmp }}/frontend.tar.gz" dest: "{{ autobot.base_dir }}/" become: true when: "'frontend' in group_names" tags: [frontend] - name: "[PLAY 2] Frontend | Fix ownership" file: path: "{{ autobot.base_dir }}/autobot-frontend" owner: autobot group: autobot recurse: true become: true when: "'frontend' in group_names" tags: [frontend] # #16310 review round 6 (reachability): roles/frontend/tasks/main.yml's # own #16310 wiring only runs when the frontend role is applied in full # (provisioning), which Update All never does for this component -- # `unarchive` above is the actual deploy mechanism on this path. - name: "[PLAY 2] Frontend | Delete files removed from source: frontend (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "Frontend (fleet update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot-frontend" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot-frontend" sync_deletions_owner: autobot when: "'frontend' in group_names" tags: [frontend] - name: "[PLAY 2] Frontend | Install Node.js dependencies" command: cmd: npm ci --ignore-scripts chdir: "{{ autobot.base_dir }}/autobot-frontend" become: true become_user: autobot when: - "'frontend' in group_names" - (hostvars['localhost']['node_deps_changed'] | bool) or (_nodejs_upgraded | default(false) | bool) register: frontend_npm_install tags: [frontend, deps] # #15603: staged build-then-swap (#15557, #15610's mechanism) — a failed # build no longer empties the served directory while nginx below still # restarts and starts answering 403 for every path. - name: "[PLAY 2] Frontend | Build and publish production dist, staged (#15603)" ansible.builtin.include_tasks: ../roles/_shared/tasks/build_publish_slm_frontend.yml vars: slm_frontend_publish_label: "Fleet update (user frontend)" slm_frontend_publish_dir: "{{ autobot.base_dir }}/autobot-frontend" slm_frontend_publish_user: autobot slm_frontend_publish_build_script: "build" slm_frontend_publish_build_env: {} when: "'frontend' in group_names" tags: [frontend] # #19661: a running process keeps the old Node.js until restarted. try-restart # leaves the unit alone on a host where it is not running. The browser worker # needs no equivalent: its restart step below runs on every update. - name: "[PLAY 2] Frontend | Restart the frontend service onto the new Node.js" ansible.builtin.command: cmd: systemctl try-restart autobot-frontend become: true register: _frontend_try_restart changed_when: _frontend_try_restart.rc == 0 # rc 5: the unit is not installed, which is normal here (roles/frontend/handlers/main.yml). failed_when: _frontend_try_restart.rc not in [0, 5] when: - "'frontend' in group_names" - _nodejs_upgraded | default(false) | bool tags: [frontend, restart] - name: "[PLAY 2] Frontend | Restart nginx" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [frontend, restart] vars: restart_unit_name: nginx when: "'frontend' in group_names" tags: [frontend, restart] - name: "[PLAY 2] Frontend | Wait for nginx to be ready" wait_for: host: "{{ ansible_host }}" port: 443 timeout: 60 delay: 5 delegate_to: localhost when: "'frontend' in group_names" tags: [frontend, restart] # ----- NPU Worker ----- - name: "[PLAY 2] NPU | Deploy autobot-npu-worker" unarchive: src: "{{ deploy_tmp }}/npu-worker.tar.gz" dest: "{{ autobot.base_dir }}/" become: true when: >- 'npu' in group_names tags: [npu, npu-worker] - name: "[PLAY 2] NPU | Fix ownership" file: path: "{{ autobot.base_dir }}/autobot-npu-worker" owner: autobot group: autobot recurse: true become: true when: >- 'npu' in group_names tags: [npu, npu-worker] # #16310 review round 6 (reachability): same gap as backend/frontend -- # `unarchive` above never deletes, and no npu-worker role's main.yml runs # on this path. - name: "[PLAY 2] NPU | Delete files removed from source: npu-worker (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "NPU worker (fleet update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot-npu-worker" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot-npu-worker" sync_deletions_owner: autobot when: >- 'npu' in group_names tags: [npu, npu-worker] - name: "[PLAY 2] NPU | Install Python dependencies" command: cmd: >- {{ autobot.base_dir }}/autobot-npu-worker/venv/bin/pip install -r {{ autobot.base_dir }}/autobot-npu-worker/requirements.txt -c {{ autobot.base_dir }}/constraints/shared.txt --quiet --timeout 120 # #15733: pip resolves a relative editable in a requirements file # against the CWD, not against the file. This manifest opens with # "-e ../autobot_shared", so with no chdir it resolved against the # remote user home and pip refused the entire install. chdir: "{{ autobot.base_dir }}/autobot-npu-worker" become: true become_user: autobot environment: PIP_DEFAULT_TIMEOUT: "120" timeout: 600 # Issue #2835: prevent indefinite hang on dependency resolution conflicts when: - >- 'npu' in group_names - hostvars['localhost']['python_deps_changed'] | bool register: npu_pip_install tags: [npu, npu-worker, deps] - name: "[PLAY 2] NPU | Restart service" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [npu, npu-worker, restart] vars: restart_unit_name: autobot-npu-worker restart_unit_tolerate_failure: true when: >- 'npu' in group_names tags: [npu, npu-worker, restart] - name: "[PLAY 2] NPU | Wait for service to stabilize (#1633)" command: systemctl is-active autobot-npu-worker become: true register: npu_status retries: 6 delay: 5 until: npu_status.rc == 0 when: >- 'npu' in group_names failed_when: false tags: [npu, npu-worker, restart] check_mode: false changed_when: false - name: "[PLAY 2] NPU | Warn if service not active (#1633)" debug: msg: "WARNING: autobot-npu-worker not active after restart: {{ npu_status.stdout | default('unknown') }}" when: - >- 'npu' in group_names - npu_status is defined - npu_status.rc | default(0) != 0 tags: [npu, npu-worker, restart] # ----- TTS Worker ----- # #12886: the TTS worker had NO update path at all — it is excluded from # per-component drift resolve (its deployed file is a rendered template, not # a 1:1 sync) and this playbook never mentioned it. So every backend update # advanced the caller while the worker stayed behind, and the streaming route # the backend calls simply 404'd. That is the #12959 pattern: the fix existed # in the role and had no route to the host. # # Applies the role's code_only task file — the service files that carry code # changes — NOT the full role. Provisioning (service account, venv, torch and # pocket-tts installs, gated-model pre-download) is slow, needs network, and # must not re-run on a box that is already installed correctly. # become is required and not inherited: this play sets no play-level become # (unlike deploy-full.yml, which the role is normally applied under), and # /opt/autobot/autobot-tts-worker is owned by the autobot-tts service # account, not the autobot user ansible connects as. Without it the very # first task fails "Destination /opt/autobot/autobot-tts-worker not # writable" — the same wrong-user ownership class as #12872. - name: "[PLAY 2] TTS | Refresh deployed TTS worker service files (#12886)" ansible.builtin.include_role: name: tts-worker tasks_from: code_only # `become` is NOT a valid task keyword on include_role (a dynamic # include) — ansible rejects the whole playbook with "'become' is not a # valid attribute for a IncludeRole", which breaks every self-update. # `apply` is how privilege is handed to the included tasks. apply: become: true when: "'npu' in group_names" tags: [tts, tts-worker, deploy] # Restart explicitly rather than via the role's notify handler, matching how # every other component in this play is restarted (NPU, Browser, backend). # # Handlers are wrong here for two compounding reasons, both observed on a # live host (#12886): # 1. they flush at END of play, and PLAY 2 has a known terminal failure in # the browser tasks below (#12912) — so the queued restart was discarded # and the worker kept serving 4-day-old code; # 2. once the file is already current, the template task reports `ok` and # never notifies at all — so a host that received the file but missed # the restart stays stale forever, with nothing left to trigger it. # # An unconditional restart is idempotent in effect and cannot be swallowed. # Deliberately NOT `failed_when: false`, unlike the NPU/Browser restarts # above. This whole issue exists because a worker kept serving stale code # while the update reported success — swallowing a failed restart here would # reintroduce exactly that: the file lands, the process never reloads, and # nothing says so. A restart that cannot complete is a real failure and # should be visible. - name: "[PLAY 2] TTS | Restart service" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [tts, tts-worker, restart] vars: restart_unit_name: autobot-tts-worker when: "'npu' in group_names" tags: [tts, tts-worker, restart] # ----- Browser Worker ----- - name: "[PLAY 2] Browser | Deploy autobot-browser-worker" unarchive: src: "{{ deploy_tmp }}/browser-worker.tar.gz" dest: "{{ autobot.base_dir }}/" become: true when: >- 'browser' in group_names tags: [browser, browser-worker] - name: "[PLAY 2] Browser | Fix ownership" file: path: "{{ autobot.base_dir }}/autobot-browser-worker" owner: autobot group: autobot recurse: true become: true when: >- 'browser' in group_names tags: [browser, browser-worker] # #16310 review round 6 (reachability): same gap as backend/frontend/npu. - name: "[PLAY 2] Browser | Delete files removed from source: browser-worker (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "Browser worker (fleet update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot-browser-worker" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot-browser-worker" sync_deletions_owner: autobot when: >- 'browser' in group_names tags: [browser, browser-worker] - name: "[PLAY 2] Browser | Install Python dependencies" command: cmd: >- {{ autobot.base_dir }}/autobot-browser-worker/venv/bin/pip install -r {{ autobot.base_dir }}/autobot-browser-worker/requirements.txt -c {{ autobot.base_dir }}/constraints/shared.txt --quiet --timeout 120 # #15733: pip resolves a relative editable in a requirements file # against the CWD, not against the file. This manifest opens with # "-e ../autobot_shared", so with no chdir it resolved against the # remote user home and pip refused the entire install. chdir: "{{ autobot.base_dir }}/autobot-browser-worker" become: true become_user: autobot environment: PIP_DEFAULT_TIMEOUT: "120" timeout: 600 # Issue #2835: prevent indefinite hang on dependency resolution conflicts when: - >- 'browser' in group_names - hostvars['localhost']['python_deps_changed'] | bool register: browser_pip_install failed_when: false tags: [browser, browser-worker, deps] # The browser worker ships no package-lock.json (git archive of a dir with # only package.json), so `npm ci` (lockfile-required) is wrong here — use # `npm install`, matching the provisioning role's `npm:` module. - name: "[PLAY 2] Browser | Install npm dependencies" command: cmd: npm install --omit=dev chdir: "{{ autobot.base_dir }}/autobot-browser-worker" become: true become_user: autobot timeout: 600 when: - >- 'browser' in group_names - (hostvars['localhost']['node_deps_changed'] | bool) or (_nodejs_upgraded | default(false) | bool) failed_when: false tags: [browser, browser-worker, deps] # #11442: a playwright version bump changes the required browser revision; # without re-running install the worker bricks on the next /navigate # ("Executable doesn't exist at .../chromium-"). Gated on node_deps_ # changed (npm install above ran first, so node_modules/.bin/playwright # exists) — playwright skips the download when the revision is present. - name: "[PLAY 2] Browser | Ensure Playwright browsers match the installed package (#11442)" command: cmd: node_modules/.bin/playwright install chromium chdir: "{{ autobot.base_dir }}/autobot-browser-worker" environment: PLAYWRIGHT_BROWSERS_PATH: /var/lib/autobot/playwright-browsers become: true timeout: 900 register: browser_playwright_install changed_when: "'downloaded' in (browser_playwright_install.stdout | default('') | lower)" failed_when: false when: - >- 'browser' in group_names - (hostvars['localhost']['node_deps_changed'] | bool) or (_nodejs_upgraded | default(false) | bool) tags: [browser, browser-worker, deps] # #5085: a root-run install produces browser files the `autobot` service # user cannot traverse/read. Symbolic a+rX adds read to all, plus traverse # to dirs and execute only to already-executable files — preserving the # chrome binary's +x (a recursive 0644 would strip it and re-brick launch). - name: "[PLAY 2] Browser | Make Playwright browsers accessible to the service user (#5085)" ansible.builtin.file: path: /var/lib/autobot/playwright-browsers mode: "a+rX" recurse: true become: true when: - >- 'browser' in group_names - (hostvars['localhost']['node_deps_changed'] | bool) or (_nodejs_upgraded | default(false) | bool) failed_when: false tags: [browser, browser-worker, deps] # #11442: surface a bricked install instead of silently restarting onto a # broken worker (pattern from "NPU | Warn if service not active"). - name: "[PLAY 2] Browser | Warn if Playwright install failed" ansible.builtin.debug: msg: >- WARNING: Playwright browser install returned rc={{ browser_playwright_install.rc | default('n/a') }} on {{ inventory_hostname }} — /navigate may fail. stderr: {{ browser_playwright_install.stderr | default('') | truncate(300) }} when: - >- 'browser' in group_names - (hostvars['localhost']['node_deps_changed'] | bool) or (_nodejs_upgraded | default(false) | bool) - browser_playwright_install.rc | default(0) != 0 tags: [browser, browser-worker, deps] - name: "[PLAY 2] Browser | Restart service" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [browser, browser-worker, restart] vars: restart_unit_name: autobot-playwright restart_unit_tolerate_failure: true when: >- 'browser' in group_names tags: [browser, browser-worker, restart] # #12912: waited on 3000, which nothing serves — autobot-playwright binds # PLAYWRIGHT_PORT (9001, roles/browser/defaults/main.yml). On a live host # 3000 is Grafana, bound to loopback only, so this timed out for 61s and # failed PLAY 2 every single run — the terminal blocker that also swallowed # other components' handlers. # # `| default(9001)` because role defaults are NOT in scope in a playbook # task (the #12871 trap); this mirrors setup-browser-worker.yml. - name: "[PLAY 2] Browser | Wait for service to be ready" wait_for: host: "{{ ansible_host }}" port: "{{ playwright_port | default(9001) }}" timeout: 60 delay: 5 delegate_to: localhost when: >- 'browser' in group_names tags: [browser, browser-worker, restart] # ----- AI Stack (LangChain/LlamaIndex agent router + ChromaDB) ----- # Ported from the retired top-level update-all-nodes.yml (#11424) so the # aiml node keeps receiving code updates through the canonical entrypoint. - name: "[PLAY 2] AI Stack | Deploy ai_api_server and requirements" unarchive: src: "{{ deploy_tmp }}/ai-stack.tar.gz" dest: "{{ autobot.base_dir }}/autobot-ai-stack/" extra_opts: ['--strip-components=4'] owner: autobot group: autobot become: true when: >- 'aiml' in group_names tags: [ai-stack, aiml] # #16310 review round 6 (reachability): same gap as the other workers. # Nonstandard source path (#12450, _NONSTANDARD_COMPONENT_PATHS): this # component has no top-level code_source/autobot-ai-stack/ -- it lives # under autobot-infrastructure/ and the archive strips 4 path components # so its contents land directly under the deployed root, matching # services/drift_checker.py's override for "autobot-ai-stack". - name: "[PLAY 2] AI Stack | Delete files removed from source: ai-stack (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "AI Stack (fleet update)" sync_deletions_source_dir: >- {{ (code_source_dir | default(autobot.base_dir ~ '/code_source')) ~ '/autobot-infrastructure/shared/docker/ai-stack' }} sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot-ai-stack" sync_deletions_owner: autobot when: >- 'aiml' in group_names tags: [ai-stack, aiml] - name: "[PLAY 2] AI Stack | Restart autobot-ai-stack service" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [ai-stack, aiml, restart] vars: restart_unit_name: autobot-ai-stack restart_unit_tolerate_failure: true when: >- 'aiml' in group_names tags: [ai-stack, aiml, restart] - name: "[PLAY 2] AI Stack | Restart autobot-chromadb service" ansible.builtin.include_tasks: file: ../_shared/tasks/restart_unit.yml apply: tags: [ai-stack, aiml, chromadb, restart] vars: restart_unit_name: autobot-chromadb restart_unit_tolerate_failure: true when: >- 'aiml' in group_names tags: [ai-stack, aiml, chromadb, restart] # ----- Shared (non-backend nodes) ----- - name: "[PLAY 2] Shared | Deploy autobot_shared" unarchive: src: "{{ deploy_tmp }}/shared.tar.gz" dest: "{{ autobot.base_dir }}/" become: true when: "'backend' not in group_names" tags: [shared] - name: "[PLAY 2] Shared | Fix ownership" file: path: "{{ autobot.base_dir }}/autobot_shared" owner: autobot group: autobot recurse: true become: true when: "'backend' not in group_names" tags: [shared] # #16310 review round 6 (reachability): the backend-colocated copy of # this same component is handled separately, right after "Backend | # Delete files removed from source: backend" above -- the two `when` # conditions are mutually exclusive, one marker file per host either way. - name: "[PLAY 2] Shared | Delete files removed from source: autobot_shared (#16310)" ansible.builtin.include_tasks: ../roles/_shared/tasks/sync_deletions.yml vars: sync_deletions_label: "Shared autobot_shared (fleet update)" sync_deletions_source_dir: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}/autobot_shared" sync_deletions_target_dir: "{{ autobot.base_dir }}/autobot_shared" sync_deletions_owner: autobot when: "'backend' not in group_names" tags: [shared] # #11480: redeploy the slm-agent (code + agent-secrets.env + restart) on # remote nodes too. block/rescue keeps a single node's agent failure from # aborting the whole fleet update (Play 2 has any_errors_fatal: true) — # consistent with the failed_when:false used by the other Play 2 tasks. # Note: a co-located SLM manager is in both slm_server (Play 1) and # infrastructure (Play 2, #11436), so it runs this idempotent role twice # per update (harmless — converges to the same state, one extra restart). # No flush_handlers here (unlike Play 1): Play 2 reaches its play end so # handlers flush normally; Play 1 needs the early flush because the backend # self-restart kills the run before play end (#11492). - name: "[PLAY 2] SLM Agent | Redeploy agent (code + secrets + restart) (#11480)" when: slm_node_id is defined tags: [slm-agent] block: - name: "[PLAY 2] SLM Agent | Gather minimal facts for role templates (#11480)" ansible.builtin.setup: gather_subset: ["min"] - name: "[PLAY 2] SLM Agent | Import slm_agent role" ansible.builtin.import_role: name: slm_agent rescue: - name: "[PLAY 2] SLM Agent | Warn on agent redeploy failure" ansible.builtin.debug: msg: >- WARNING: slm_agent redeploy failed on {{ inventory_hostname }} — agent may run stale code / miss agent-secrets.env (#11480). Continuing fleet update. # Linked after the redeploy so a freshly enrolled node (no agent tree yet) gets the # link once the role has installed it (#21035). # Issue #9225: slm-agent needs autobot_shared in PYTHONPATH - name: "[PLAY 2] SLM Agent | Create autobot_shared symlink for agent imports" ansible.builtin.import_tasks: ../roles/_shared/tasks/link_autobot_shared.yml vars: shared_link_component: autobot-slm-agent when: slm_node_id is defined tags: [slm-agent, shared] # Issue #9565: slm-backend needs autobot_shared in PYTHONPATH - name: "[PLAY 2] SLM Backend | Create autobot_shared symlink for backend imports" ansible.builtin.import_tasks: ../roles/_shared/tasks/link_autobot_shared.yml vars: shared_link_component: autobot-slm-backend when: slm_node_id is defined tags: [slm-backend, shared] # ----- Mark synced ----- - name: "[PLAY 2] Mark node as synced in SLM DB" uri: url: "https://{{ slm_host }}/slm/api/code-sync/nodes/{{ inventory_hostname }}/mark-synced" method: POST headers: Authorization: "Bearer {{ slm_token }}" Content-Type: "application/json" body: "{}" body_format: json validate_certs: false timeout: 30 status_code: [200, 404] register: node_mark_synced # Retry the briefly-slow post-restart endpoint instead of one-shot # timing out so the node actually gets marked synced (#10634). until: node_mark_synced.status | default(-1) in [200, 404] retries: 6 delay: 10 delegate_to: localhost ignore_errors: true when: slm_token | default('') | length > 0 tags: [always] no_log: true # #19764: credentials in the request or response # ========================================================================= # #12959: post-update delivery assertions # # The expensive part of #12959 was not the missing role application — it was # that the update REPORTED SUCCESS while delivering nothing, so three issues # (#12777, #12886, #12907) were closed against a mechanism that could not # deliver them and their symptoms were re-diagnosed weeks later. # # Each check below asserts an invariant that a task EARLIER IN THIS PLAY # just guaranteed, so a failure means delivery silently regressed — never a # pre-existing host condition. That is why they are fail-closed: a green run # that delivered nothing is the exact outcome this issue is about. # ========================================================================= # `executable: /bin/bash` is load-bearing (#12907): ansible.builtin.shell # runs under /bin/sh, which is dash on these hosts, and dash aborts on # `set -o pipefail` with rc=2 before the first echo. That left # delivery_evidence.stdout EMPTY, and every assert below is gated on it # being non-empty — so the delivery checks #12959 added to stop "green but # undelivered" were themselves silently skipped on every run. - name: "[PLAY 2] Verify | Collect delivery evidence (#12959)" ansible.builtin.shell: cmd: | set -uo pipefail f=/etc/autobot/db-credentials.env echo "faulthandler=$(systemctl cat autobot-backend 2>/dev/null \ | grep -c PYTHONFAULTHANDLER)" echo "cred_block=$(grep -c '^# BEGIN AUTOBOT DB CREDENTIALS' \ "$f" 2>/dev/null)" echo "cred_pw=$(grep -cE '^AUTOBOT_DB_PASSWORD=.+' "$f" 2>/dev/null)" echo "dup_cred_keys=$(grep -oE '^AUTOBOT_[A-Z0-9_]+=' "$f" 2>/dev/null \ | sort | uniq -d | wc -l)" echo "legacy_store=$(test -f /etc/autobot/autobot-db-credentials.env \ && echo 1 || echo 0)" args: executable: /bin/bash register: delivery_evidence become: true changed_when: false failed_when: false when: "'backend' in group_names" tags: [backend, verify] - name: "[PLAY 2] Verify | Backend systemd unit reached the host (#12777, #12959)" ansible.builtin.assert: that: # rendered by "Render systemd unit" above via roles/backend unit_only - "'faulthandler=0' not in delivery_evidence.stdout" fail_msg: >- #12959: the update ran green but roles/backend unit_only did not render the systemd unit — the #12777 faulthandler diagnostic is not active. Evidence: {{ delivery_evidence.stdout | default('(none)') }}. Do not close an issue against this run. success_msg: "Backend systemd unit delivered (#12777)" when: - "'backend' in group_names" - delivery_evidence.stdout | default('') | length > 0 tags: [backend, verify] # Gated on the canonical store actually holding an AUTOBOT password, NOT on # a blockinfile marker (#12907). Marker-gating suppressed this assertion on # exactly the hosts that carried the pre-#12224 duplicates — they have no # marker — so the check that was supposed to catch non-delivery went quiet # on the one host shape where delivery had failed. A host with no AUTOBOT # credentials at all has a provisioning gap, not a delivery regression, and # is still excluded so it cannot fail the fleet update for the wrong reason. - name: "[PLAY 2] Verify | Credential store reconciled (#12907, #12959)" ansible.builtin.assert: that: # Defect 1 — pre-#12224 unmarked duplicates stripped - "'dup_cred_keys=0' in delivery_evidence.stdout" # Defect 2 — superseded legacy store retired - "'legacy_store=0' in delivery_evidence.stdout" fail_msg: >- #12959: the update ran green but roles/postgresql credentials_reconcile did not apply — duplicate keys and/or the superseded autobot-db-credentials.env survive, which is how #12883 became an outage. Evidence: {{ delivery_evidence.stdout | default('(none)') }} success_msg: "Credential store reconciled (#12907)" when: - "'backend' in group_names" - delivery_evidence.stdout | default('') | length > 0 - "'cred_pw=0' not in delivery_evidence.stdout" tags: [backend, verify] - name: "[PLAY 2] Verify | TTS worker carries the streaming route (#12886, #12959)" ansible.builtin.command: cmd: grep -c '/tts/synthesize/stream' {{ autobot.base_dir }}/autobot-tts-worker/tts-worker.py register: tts_stream_route become: true changed_when: false failed_when: false when: "'npu' in group_names" tags: [tts, verify] - name: "[PLAY 2] Verify | Fail if the TTS worker was not refreshed (#12886, #12959)" ansible.builtin.assert: that: - tts_stream_route.stdout | default('0') | trim | int > 0 fail_msg: >- #12959: /opt/autobot/autobot-tts-worker/tts-worker.py lacks /tts/synthesize/stream after this update — roles/tts-worker code_only did not deliver, so backend TTS calls will 404 (#12886). success_msg: "TTS worker refreshed (#12886)" # rc != 0 also means "file absent", i.e. the worker is not installed on # this node at all — that is a provisioning gap (#12872), not a delivery # regression, so it is not this assertion's failure to report. when: - "'npu' in group_names" - tts_stream_route.rc | default(1) == 0 tags: [tts, verify] # ========================================================================= # #13460: the last four components whose role-owned files the updater could # not deliver. Each applies its role's code_only task file — the service # units, worker code and configs that carry changes — never the full role, # whose provisioning half (apt, venv, OpenVINO, Playwright downloads, npm) # must not re-run on an already-installed box. # # `apply: {become: true}` on every one: this play sets no play-level become, # and a bare `become` on include_role makes ansible reject the WHOLE playbook # ("'become' is not a valid attribute for a IncludeRole"), breaking every # self-update rather than just the task (#12886). # ========================================================================= - name: "[PLAY 2] AI Stack | Deploy role-owned service files (#13460)" ansible.builtin.include_role: name: ai-stack tasks_from: code_only apply: become: true when: "'aiml' in group_names" tags: [ai-stack, deploy] - name: "[PLAY 2] NPU | Deploy role-owned service files (#13460)" ansible.builtin.include_role: name: npu-worker tasks_from: code_only apply: become: true when: "'npu' in group_names" tags: [npu, npu-worker, deploy] - name: "[PLAY 2] Frontend | Deploy role-owned nginx config (#13460)" ansible.builtin.include_role: name: frontend tasks_from: code_only apply: become: true when: "'frontend' in group_names" tags: [frontend, nginx, deploy] - name: "[PLAY 2] Browser | Deploy role-owned service files (#13460)" ansible.builtin.include_role: name: browser tasks_from: code_only apply: become: true when: "'browser' in group_names" tags: [browser, deploy] - name: "[PLAY 2] Node Update Complete" debug: msg: "{{ inventory_hostname }} updated" # ============================================================================= # PLAY 2b: Update Database Nodes # ============================================================================= # #13535: the database role had NO builtin update route. Play 2 targets the # `infrastructure` group, and `database` is not one of its children — so nothing # code-sync / self-update ran ever touched a database host, and roles/redis had # no code-only task file for a play to apply even if it had. That is why the # #12513 chroma-auth work merged in #13462/#13537 "looked deployed" while the # host was unchanged: the #12959 failure shape, one role further along. # # A separate play rather than adding `database` to the `infrastructure` group: # that group is Play 2's host list, and Play 2 is a backend/frontend/worker # update — package installs, npm builds, alembic migrations, a backend .env # regeneration. None of it is designed for a database node, and all of it is # guarded by `'' in group_names` checks a database node would skip # anyway. Targeting `database` directly runs the one thing that node needs and # nothing else. # # Placed AFTER Play 2, deliberately. Play 2 regenerates backend.env with the # chroma CLIENT token and restarts the backend; this play then switches the # chroma SERVER to enforcing. The reverse order would enable server-side auth # while the backend still ran without the credential — every RAG call 401s for # the length of Play 2. Same ordering the ai-stack chroma unit already follows # inside Play 2 (backend tasks first, ai-stack code_only last). - name: "Play 2b - Update Database Nodes" hosts: database gather_facts: false # Consistent with Play 2: a database node that fails to take the update must # stop the rollout rather than leave the fleet diverged (#10026). any_errors_fatal: true tasks: - name: "[PLAY 2b] Starting Database Node Update" ansible.builtin.debug: msg: - "=======================================================" - " PLAY 2b: Database Node Update (role-owned files)" - "=======================================================" - " Target: {{ inventory_hostname }}" # #16020: roles/redis/tasks/main.yml ensures the shared keypair, but this # play applies the role via `tasks_from: code_only` below (see its own # comment), which never reaches that task -- only the role's full # provisioning entrypoint does. A database node maintained only through # this playbook could never repair a missing cert otherwise. - name: "[PLAY 2b] Database | Ensure the shared node TLS cert" include_tasks: "../_shared/tasks/ensure_node_tls_cert.yml" when: "role_redis_active | default(false) | bool" tags: [database, redis] # Applies the role's code_only task file — the systemd override, the backup # script and the ChromaDB credential file + unit — NEVER the full role, # whose provisioning half (the redis-stack package, service accounts, the # data directory and its recursive chown, the chroma venv and its package # installs) must not re-run on an already-installed box. # # `apply: {become: true}` because this play sets no play-level become, and a # bare `become` on include_role makes ansible reject the WHOLE playbook # ("'become' is not a valid attribute for a IncludeRole"), breaking every # self-update rather than just the task (#12886). - name: "[PLAY 2b] Database | Deploy role-owned service files (#13535)" ansible.builtin.include_role: name: redis tasks_from: code_only apply: become: true tags: [database, redis, chromadb, deploy] # #19848: as in PLAY 1 -- the database node's postgresql.conf, before the handler flush below. - name: "[PLAY 2b] Database | Apply PostgreSQL's server config (#19848)" ansible.builtin.include_role: name: postgresql tasks_from: config_file apply: become: true tags: [database, postgresql] # Flush here rather than letting the handlers fall to the end of the play. # #12886 recorded both halves of why that matters: queued handlers are # DISCARDED when a later task aborts the play, and a handler that never ran # leaves a host holding a new credential file that nothing has read yet. # Flushing immediately after the only task that notifies makes the restart # part of the delivery instead of a hope, and keeps it before the assertions # below — which check the running unit, not the file on disk. - name: "[PLAY 2b] Database | Apply pending restarts before verifying (#13535)" ansible.builtin.meta: flush_handlers # ========================================================================= # #12959 post-update delivery assertion. # # The expensive part of #13462 was not the missing fix — it was that the # update REPORTED SUCCESS while delivering nothing, so the chroma-auth work # was closed against a mechanism that could not deliver it and the symptom # was re-diagnosed later. This asserts an invariant the include above just # guaranteed, so a failure means delivery silently regressed. # # `executable: /bin/bash` is load-bearing (#12907): ansible.builtin.shell # runs under /bin/sh, which is dash on these hosts, and dash aborts on # `set -o pipefail` before the first echo — leaving the evidence empty and # every assertion gated on it silently skipped. # ========================================================================= - name: "[PLAY 2b] Verify | Collect ChromaDB delivery evidence (#12513, #13535)" ansible.builtin.shell: cmd: | set -uo pipefail envfile=$(systemctl cat autobot-chromadb 2>/dev/null \ | sed -n 's/^EnvironmentFile=//p' | head -1) echo "envfile_declared=$(test -n "$envfile" && echo 1 || echo 0)" echo "envfile_optional=$(case "$envfile" in -*) echo 1 ;; *) echo 0 ;; esac)" echo "envfile_present=$(test -n "$envfile" \ && test -f "${envfile#-}" && echo 1 || echo 0)" args: executable: /bin/bash register: chromadb_delivery_evidence become: true changed_when: false failed_when: false tags: [database, chromadb, verify] - name: "[PLAY 2b] Verify | ChromaDB unit carries its credential file (#12513, #13535)" ansible.builtin.assert: that: # rendered by roles/redis code_only above, from the unit template - "'envfile_declared=1' in chromadb_delivery_evidence.stdout" # `EnvironmentFile=-` is why a missing credential ran unauthenticated - "'envfile_optional=0' in chromadb_delivery_evidence.stdout" # written by _shared/tasks/write_chromadb_authn_env.yml - "'envfile_present=1' in chromadb_delivery_evidence.stdout" fail_msg: >- #13535: the update ran green but roles/redis code_only did not deliver the ChromaDB credential file the unit mandates — chroma is running unauthenticated or cannot start. Evidence: {{ chromadb_delivery_evidence.stdout | default('(none)') }}. success_msg: "ChromaDB unit + credential file delivered (#12513)" when: chromadb_delivery_evidence.stdout | default('') | trim | length > 0 tags: [database, chromadb, verify] - name: "[PLAY 2b] Database Node Update Complete" ansible.builtin.debug: msg: "{{ inventory_hostname }} updated" # ============================================================================= # PLAY 2c: Re-render the monitoring config (#18994) # ============================================================================= # Plays 1/2/2b deploy component code and role-owned files, but nothing here ever # applied the `monitoring` role, which owns /etc/prometheus/prometheus.yml and the # #16375 scrape-token file. The backend gates /api/metrics/prometheus on that token # (backend.env, refreshed by Play 1/2 through roles/backend), so a host updated only # through this playbook kept its install-time prometheus.yml: no `bearer_token_file` # on the autobot-backend job (every scrape 401) and none of the jobs the template # gained since. The merge was green, code_source carried the template, and the host # never received it -- the #12959 failure shape, for monitoring. # # `hosts: monitoring_vm` is the group a node's `monitoring` / `slm-monitoring` role # token maps to (services/inventory_builder.py), so a host without the role is not # touched, and `--limit` still bounds the play to the machine being updated. # # Config tasks only (`tasks_from: prometheus_config.yml`), as deploy-slm-manager.yml # does for #14337: Prometheus is already installed, and the role's install half would # restart it for no reason. Placed AFTER Plays 1/2 so the topology decision there # observes the backend unit and vhost this very update just (re)wrote. # # Token safety is the task file's own: the SLM delivers `prometheus_scrape_token` as # an extra var (services/playbook_executor.py -> fetch_deploy_secrets); when that # fetch degrades the shared keep-task adopts the value already in the backend env file, # and if neither exists an already-present token file is left alone, so an empty run # never takes a working scrape down. The value is never printed (no_log) nor rendered # into prometheus.yml, which names the file only. - name: "Play 2c - Update Monitoring Config" hosts: monitoring_vm gather_facts: false tags: [monitoring, prometheus] tasks: - name: "[PLAY 2c] Monitoring | Keep the deployed Prometheus scrape token (#16375, #18994)" # `apply.tags`: a `--tags monitoring` run selects the include but would not pass the tag # to the included tasks, finishing without rendering anything. ansible.builtin.include_tasks: file: ../_shared/tasks/keep_prometheus_scrape_token.yml apply: tags: [monitoring, prometheus] vars: scrape_token_env_files: ["{{ autobot_backend_env_file }}"] # `apply: {become: true}`, not a bare `become` -- ansible rejects the whole # playbook for the latter on include_role (#12886). - name: "[PLAY 2c] Monitoring | Render prometheus.yml and the scrape-token file (#18994)" ansible.builtin.include_role: name: monitoring tasks_from: prometheus_config apply: become: true tags: [monitoring, prometheus] # Same reasoning as Play 2b: a queued handler is discarded if a later play aborts. - name: "[PLAY 2c] Monitoring | Apply a pending Prometheus restart (#18994)" ansible.builtin.meta: flush_handlers # ============================================================================= # PLAY 2d: Grafana (#19661) # ============================================================================= # Last before Play 3: a package outage here fails this host's Grafana step visibly, after its # code and services are already updated. Hosts without Grafana are left without it. - name: "Play 2d - Move Grafana to its pinned version" hosts: slm_server:monitoring_vm gather_facts: true gather_subset: [min] tags: [monitoring, grafana] tasks: - name: "[PLAY 2d] Grafana | Upgrade an installed Grafana below grafana_version" ansible.builtin.include_role: name: monitoring tasks_from: grafana_install.yml apply: become: true tags: [monitoring, grafana] vars: grafana_fresh_install: false # ============================================================================= # PLAY 3: Verify + Cleanup # ============================================================================= - name: "Play 3 - Verify & Cleanup" hosts: localhost gather_facts: false tasks: - name: Wait for services to stabilize pause: seconds: 5 # #14701: this stage is named Verify and could not fail. `ignore_errors` # meant a run whose SLM never came back still printed "Fleet Update # Complete" with "SLM: Check manually" and exited successfully -- a check # that cannot fail is worse than no check, because the green run reads as # verified. Retried rather than probed once: Play 2 restarts services, so a # single immediate probe races the restart it follows. - name: Check SLM health uri: url: "https://{{ slm_host }}/slm/api/health" validate_certs: false status_code: 200 register: slm_health until: slm_health.status == 200 retries: 12 delay: 10 # #20250: the agents reconnect after the restarts above, so read the count once they have had # time to. Judged against the count before the update, so a node that was already down costs no # wait and isn't blamed on it. Not a failure of this task: the marker below says it. - name: Wait for the nodes to report back uri: url: "https://{{ slm_host }}/slm/api/health" validate_certs: false status_code: 200 register: fleet_nodes_health until: >- fleet_nodes_health.status == 200 and (fleet_nodes_health.json.nodes_online | default(0) | int) >= (fleet_nodes_before.json.nodes_online | default(0) | int) retries: "{{ update_nodes_online_retries | default(18) }}" delay: "{{ update_nodes_online_delay | default(10) }}" failed_when: false # /health answers 200 with 0 nodes when its database is down, which is no count to judge against. when: fleet_nodes_before.json is defined and fleet_nodes_before.json.database == 'healthy' - name: Clean up deploy archives file: path: /tmp/autobot-deploy state: absent # Read by services/self_update_log_reader.py, so the update page says so too. - name: Report nodes still offline after the update debug: msg: >- NODES OFFLINE AFTER UPDATE: {{ (fleet_nodes_before.json.nodes_online | default(0) | int) - (fleet_nodes_health.json.nodes_online | default(0) | int) }} of {{ fleet_nodes_before.json.nodes_online | default(0) | int }} when: - fleet_nodes_before.json is defined - fleet_nodes_before.json.database == 'healthy' - fleet_nodes_health.json is defined - fleet_nodes_health.json.database == 'healthy' - (fleet_nodes_health.json.nodes_online | default(0) | int) < (fleet_nodes_before.json.nodes_online | default(0) | int) - name: Say when the nodes could not be counted debug: msg: "Could not compare the nodes online before and after this update" when: >- fleet_nodes_before.json is defined and (fleet_nodes_before.json.database != 'healthy' or fleet_nodes_health.json.database | default('') != 'healthy') # #21343: where the credential re-alignment stands, from each node that reported it; the proposal # step records it and never fails the update. - name: "Collect the credential re-alignment reports (#21343)" ansible.builtin.set_fact: internal_key_realign_lines: >- {{ groups['infrastructure'] | default([]) | map('extract', hostvars, 'internal_api_key_realign_report') | select('defined') | list }} - name: Display update summary debug: msg: - "" - "=======================================================" - " Fleet Update Complete (Git-Based Deploy)" - "=======================================================" - "" - " Method: GitHub pull → git archive" - " SLM: {{ slm_health.json.status | default('Check manually') }}" - " Nodes: {{ slm_health.json.nodes_online | default('?') }}/{{ slm_health.json.nodes_total | default('9') }}" - "" - " SLM Admin: https://{{ slm_host | default('(not-deployed)') }}/" - " User Frontend: https://{{ frontend_host | default('(not-deployed)') }}/" - "" - " Credential re-alignment: {{ internal_key_realign_lines | default([]) | join(' | ') or 'nothing pending' }}" - ""