Files
Nuc_AWX/playbooks/update.yml
T

115 lines
4.6 KiB
YAML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
- name: System update for all managed hosts
hosts: all
become: yes
gather_facts: yes
vars:
# Telegram bot token (из задания)
telegram_token: "8820292312:AAECFO1AEWOJTh30zNuhyjC5C81o_qJHQcM"
# ID чата, куда отправлять уведомления (из вашего сообщения)
telegram_chat_id: "407968638"
# Прокси для Telegram API (формат для curl)
telegram_proxy: "socks5h://administrator:60NthRegT@192.168.0.218:1080"
tasks:
# 1. Показываем текущую версию ОС и ядра (для контекста)
- name: Show OS and kernel version
debug:
msg:
- "Host: {{ inventory_hostname }}"
- "OS: {{ ansible_distribution }} {{ ansible_distribution_version }}"
- "Kernel: {{ ansible_kernel }}"
# 2. Обновляем кэш apt и запоминаем, изменился ли он
- name: Update apt cache
apt:
update_cache: yes
cache_valid_time: 3600
register: apt_update_result
- name: Show apt cache update status
debug:
msg: "Apt cache was {{ 'updated' if apt_update_result.changed else 'already up to date' }}"
# 3. Получаем список пакетов, которые можно обновить (до обновления)
- name: Get list of upgradable packages
command: apt list --upgradable
register: upgradable_before
changed_when: false
ignore_errors: yes # если команда недоступна, продолжить
- name: Show upgradable packages before update
debug:
var: upgradable_before.stdout_lines
when: upgradable_before.stdout_lines | length > 0
# 4. Выполняем полное обновление (dist-upgrade)
- name: Perform dist-upgrade (full upgrade)
apt:
upgrade: dist
autoremove: yes
autoclean: yes
register: apt_upgrade_result
# 5. Показываем результат обновления (что изменилось)
- name: Show upgrade results
debug:
msg:
- "Packages upgraded: {{ apt_upgrade_result.results | default([]) | map(attribute='packages') | list | flatten | unique | join(', ') if apt_upgrade_result.results is defined else 'No package list available' }}"
when: apt_upgrade_result.changed
# 6. Если изменений не было – сообщаем об этом
- name: No packages were upgraded
debug:
msg: "All packages are up to date."
when: not apt_upgrade_result.changed
# 7. Проверяем, требуется ли перезагрузка (наличие /var/run/reboot-required)
- name: Check if reboot is required
stat:
path: /var/run/reboot-required
register: reboot_required_file
# - name: Reboot if required
# reboot:
# reboot_timeout: 600
# pre_reboot_delay: 30
# post_reboot_delay: 30
# when: reboot_required_file.stat.exists
- name: Reboot not required
debug:
msg: "No reboot required."
when: not reboot_required_file.stat.exists
# ===== ОПОВЕЩЕНИЕ В TELEGRAM =====
- name: Build notification message
set_fact:
message_text: |
<b>Host:</b> {{ inventory_hostname }}
<b>OS:</b> {{ ansible_distribution }} {{ ansible_distribution_version }}
<b>Kernel:</b> {{ ansible_kernel }}
<b>Update result:</b> {% if apt_upgrade_result.changed %}✅ Updates applied{% else %}✅ No updates needed{% endif %}
{% if apt_upgrade_result.changed and upgradable_before.stdout_lines is defined and upgradable_before.stdout_lines | length > 0 %}
<b>Upgraded packages (old → new):</b>
{{ upgradable_before.stdout_lines | select('match', '^[^/]+/') | list | join('\n') }}
{% endif %}
<b>Reboot required:</b> {% if reboot_required_file.stat.exists %}⚠️ YES{% else %}No{% endif %}
- name: Send Telegram notification
shell: |
# Экранируем текст для JSON
MESSAGE=$(cat <<'EOF' | python3 -c 'import sys, json; print(json.dumps(sys.stdin.read()))'
{{ message_text }}
EOF
)
curl -x {{ telegram_proxy }} \
-s -X POST \
-H "Content-Type: application/json" \
-d "{\"chat_id\": \"{{ telegram_chat_id }}\", \"text\": $MESSAGE, \"parse_mode\": \"HTML\"}" \
https://api.telegram.org/bot{{ telegram_token }}/sendMessage
when:
- telegram_token | default('') != ''
- telegram_chat_id | default('') != ''
ignore_errors: yes