Files
ayurishchevandClaude Opus 5.5 d0ab6b94f9 Ansible: deliver validator-agent from the artreg registry instead of building on each host
The role resolves image_tag to a digest once per run and pulls that image
on every validator before replacing the container; the git and build
steps are gone. scripts/publish-agent-image.sh builds and pushes the
agent image (<rev12> and latest tags).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:59:33 +03:00

118 lines
5.5 KiB
YAML

---
- name: Verify the new container
block:
# Агент пишет "registered" после успешной регистрации в control-api.
- name: Wait for the agent to register in control-api
ansible.builtin.command: "docker logs --tail 200 {{ container_name }}"
register: agent_logs
changed_when: false
until: agent_logs.stdout is search('msg=registered validator_id=' ~ effective_validator_id ~ '(\s|$)') or agent_logs.stderr is search('msg=registered validator_id=' ~ effective_validator_id ~ '(\s|$)')
retries: "{{ verify_retries | int }}"
delay: "{{ verify_delay | int }}"
- name: Inspect the container
ansible.builtin.command:
argv: [docker, inspect, --format, "{% raw %}{{.State.Running}} {{.RestartCount}} {{.Image}}{% endraw %}", "{{ container_name }}"]
register: container_state
changed_when: false
- name: Check the container state
ansible.builtin.assert:
that:
- container_state.stdout.split()[0] == 'true'
- container_state.stdout.split()[1] == '0'
- container_state.stdout.split()[2] == built_image.stdout
fail_msg: >-
Контейнер {{ container_name }} в состоянии «{{ container_state.stdout }}»
(ожидалось: запущен, 0 перезапусков, образ {{ built_image.stdout }}).
quiet: true
# Трассировка: пакет traceroute ставится в образе (Dockerfile).
- name: Check that traceroute exists in the container
ansible.builtin.command: "docker exec {{ container_name }} sh -c 'command -v traceroute'"
register: traceroute_bin
changed_when: false
failed_when: false
- name: Assert traceroute is installed
ansible.builtin.assert:
that: traceroute_bin.rc == 0
fail_msg: >-
traceroute не найден в контейнере {{ container_name }}: образ из старой сборки
(проверьте image_tag и что нужный образ опубликован).
quiet: true
# Итоговый конфиг рендерит docker-entrypoint.sh из шаблона образа.
- name: Read the rendered agent config
ansible.builtin.command: "docker exec {{ container_name }} cat /etc/validator-agent/validator-agent.yaml"
register: agent_config
changed_when: false
failed_when: false
- name: Assert the config has retry and traceroute settings
ansible.builtin.assert:
that:
- agent_config.rc == 0
- "'https_attempts:' in agent_config.stdout"
- "'traceroute:' in agent_config.stdout"
fail_msg: >-
В конфиге агента нет https_attempts / traceroute: запущен образ из старой сборки
(проверьте image_tag и что нужный образ опубликован).
quiet: true
- name: Extract the new settings for the summary
ansible.builtin.set_fact:
agent_https_attempts: "{{ agent_config.stdout | regex_search('https_attempts:\\s*(\\d+)', '\\1') | default(['?'], true) | first }}"
agent_traceroute_enabled: "{{ agent_config.stdout | regex_search('traceroute:\\s*enabled:\\s*(\\S+)', '\\1') | default(['?'], true) | first }}"
rescue:
- name: Collect the container log
ansible.builtin.command: "docker logs --tail 30 {{ container_name }}"
register: failed_logs
changed_when: false
failed_when: false
- name: Fail the host and stop the next waves
ansible.builtin.fail:
msg: |-
{{ inventory_hostname }}: контейнер не прошёл проверку после запуска.
Последние строки лога:
{{ failed_logs.stdout }}{{ failed_logs.stderr }}
# Очистка: образы прежнего имени (собирались на валидаторе) и старые образы
# реестра, кроме текущего. Образ работающего контейнера docker не удалит.
# docker images показывает короткий id (12 символов), built_image — полный;
# -f нужен, если у образа несколько тегов (latest и ревизия) на одном id.
- name: List legacy images
ansible.builtin.command:
argv: [docker, images, "{{ legacy_image_name }}", --format, "{% raw %}{{.ID}}{% endraw %}"]
register: legacy_images
changed_when: false
- name: List registry images
ansible.builtin.command:
argv: [docker, images, "{{ registry }}/{{ image_repo }}", --format, "{% raw %}{{.ID}}{% endraw %}"]
register: registry_images
changed_when: false
- name: Remove old images
ansible.builtin.command: "docker rmi -f {{ item }}"
loop: >-
{{ (legacy_images.stdout_lines
+ (registry_images.stdout_lines
| reject('equalto', built_image.stdout | regex_replace('^sha256:', '') | truncate(12, True, ''))
| list))
| unique | list }}
changed_when: true
failed_when: false
- name: Remove dangling images
ansible.builtin.command: docker image prune -f
changed_when: false
- name: Summary
ansible.builtin.debug:
msg: >-
{{ inventory_hostname }} ({{ effective_validator_id }}): {{ image_tag }} ({{ resolved_digest[:19] }}),
образ {{ built_image.stdout[:19] }}, контейнер {{ container_name }} запущен,
попыток HTTPS: {{ agent_https_attempts }}, трассировка: {{ agent_traceroute_enabled }}