Wednesday, July 2, 2025

Zabbix 7 - Twilio SMS

Using Twilio API to send SMS from Zabbix. 
 
 
cat /usr/lib/zabbix/alertscripts/twilio_sms.py
 #!/usr/bin/env python3

import sys
import os
from twilio.rest import Client

# --- Configuration ---
# These should ideally be passed as arguments or environment variables
# For simplicity in this example, they are hardcoded but it's better
# to pass them from Zabbix media type parameters for security.
# However, Zabbix passes parameters as command-line arguments.
# We'll retrieve them from Zabbix's parameters.

# Argument 1: Recipient's phone number (passed by Zabbix)
# Argument 2: Subject (passed by Zabbix - often the alert message)
# Argument 3: Message body (passed by Zabbix - often detailed alert info)

# These should be configured in Zabbix as parameters for the media type later
# or set as secure macros if your Zabbix version supports it well for scripts.
# For now, let's assume you will pass them as script parameters
# in the media type configuration.

# The script expects:
# $1 (to_number)
# $2 (subject - we'll use this as part of the message)
# $3 (message_body)
# $4 (TWILIO_ACCOUNT_SID)
# $5 (TWILIO_AUTH_TOKEN)
# $6 (TWILIO_FROM_NUMBER)

if len(sys.argv) < 7:
    print("Usage: python twilio_sms.py <to_number> <subject> <message_body> <account_sid> <auth_token> <from_number>")
    sys.exit(1)

to_number = sys.argv[1]
subject = sys.argv[2]
message_body = sys.argv[3]
account_sid = sys.argv[4]
auth_token = sys.argv[5]
from_number = sys.argv[6]

# Construct the message
full_message = f"{subject}: {message_body}"

try:
    client = Client(account_sid, auth_token)
    message = client.messages.create(
        body=full_message,
        from_=from_number,
        to=to_number
    )
    print(f"SMS sent successfully to {to_number}. SID: {message.sid}")
except Exception as e:
    print(f"Error sending SMS: {e}")
    sys.exit(1)