Telegram alerts: accept credentials from extra vars or environment, report which is missing

Semaphore variable groups can pass values as extra vars or as environment
variables, and secrets can be either type. Read telegram_bot_token,
TELEGRAM_BOT_TOKEN (extra var) or TELEGRAM_BOT_TOKEN (env), same for the
chat id, and say in the "not configured" message which of the two is
missing so a wrong box or a detached variable group is visible in the log.

Claude-Session: https://claude.ai/code/session_01XEizHawueRXUcxQELRZ8kq
This commit is contained in:
Harwinder Sekhon
2026-09-06 23:15:11 -04:00
parent 5aaa7020ac
commit 7ad388ba50
2 changed files with 24 additions and 12 deletions
+12 -6
View File
@@ -5,8 +5,8 @@
#
# Extra vars (optional):
# disk_warn_pct - default 80
# telegram_bot_token - or environment variable TELEGRAM_BOT_TOKEN
# telegram_chat_id - or environment variable TELEGRAM_CHAT_ID
# telegram_bot_token / TELEGRAM_BOT_TOKEN - extra var or environment variable
# telegram_chat_id / TELEGRAM_CHAT_ID - extra var or environment variable
# Without both Telegram values the playbook only prints the report.
- name: Check Host Availability
@@ -86,9 +86,11 @@
vars:
disk_warn_pct: 80
telegram_bot_token: "{{ lookup('env', 'TELEGRAM_BOT_TOKEN') }}"
telegram_chat_id: "{{ lookup('env', 'TELEGRAM_CHAT_ID') }}"
telegram_configured: "{{ telegram_bot_token | length > 0 and telegram_chat_id | length > 0 }}"
# Accepted from a Semaphore variable group as extra vars (telegram_bot_token
# or TELEGRAM_BOT_TOKEN) or as environment variables (TELEGRAM_BOT_TOKEN).
telegram_bot_token: "{{ TELEGRAM_BOT_TOKEN | default(lookup('env', 'TELEGRAM_BOT_TOKEN'), true) | string }}"
telegram_chat_id: "{{ TELEGRAM_CHAT_ID | default(lookup('env', 'TELEGRAM_CHAT_ID'), true) | string }}"
telegram_configured: "{{ telegram_bot_token | string | length > 0 and telegram_chat_id | string | length > 0 }}"
offline_hosts: "{{ groups['all'] | difference(groups['reachable_hosts'] | default([])) }}"
tasks:
@@ -113,7 +115,11 @@
- name: Print alerts when Telegram is not configured
ansible.builtin.debug:
msg: "ALERTS (Telegram not configured - set telegram_bot_token and telegram_chat_id):\n{{ alert_text }}"
msg: |-
ALERTS (Telegram not configured - bot token {{ 'set' if telegram_bot_token | string | length > 0 else 'MISSING' }},
chat id {{ 'set' if telegram_chat_id | string | length > 0 else 'MISSING' }};
pass TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID through the variable group attached to this template)
{{ alert_text }}
when:
- alert_text | length > 0
- not telegram_configured