Skip to content

Instantly share code, notes, and snippets.

@starkers
Created July 29, 2019 09:39
Show Gist options
  • Save starkers/15be68bd2c6b6fec82960463be4e7100 to your computer and use it in GitHub Desktop.
Save starkers/15be68bd2c6b6fec82960463be4e7100 to your computer and use it in GitHub Desktop.
silence.py
#!/usr/bin/env python3
import click
import requests
from datetime import datetime, timedelta
import sys
# current_time = dt.datetime.utcnow().isoformat() + 'Z'
# expire_time = "2020-12-12T12:00:00Z"
@click.command()
@click.option("-n", "--name", default="alertname", help="Name of a matcher")
@click.option("-v", "--value", help="Value of a matcher (or regex)")
@click.option("-d", "--duration", default=1, help="Duration of silence (in hours)")
@click.option("-c", "--comment", default="", help="Enter a comment")
@click.option("-b", "--baseurl", default="http://alerts.example.com:9093", help="Base URL for alerts")
@click.option("-r", "--regex", is_flag=True, help="To enable regex use with option")
#@click.option("-s", "--start", default=current_time, help="Start time (yyyy-mm-ddThh:mm:ss.fffZ)")
#@click.option("-e", "--end", default=expire_time, help="End time (yyyy-mm-ddThh:mm:ss.fffZ)")
def set_silence(name, value, duration, comment, baseurl, regex):
if not value:
print("Enter a value (use -v or --value).")
sys.exit(1)
current_utc = datetime.utcnow()
current_time = datetime.utcnow().isoformat() + 'Z'
expire_time = (datetime.utcnow() + timedelta(hours=duration + 1 / 3600)).isoformat() + 'Z'
data = {
"matchers": [
{
"name": name,
"value": value,
"isRegex": regex
}
],
"startsAt": current_time,
"endsAt": expire_time,
"createdBy": "api",
"comment": comment,
"status": {
"state": "active"
}
}
api_url = "{}/api/v1/silences".format(baseurl)
try:
r = requests.post(api_url, json=data)
print(r.json())
except requests.exceptions.RequestException as e:
print(e)
sys.exit(1)
if __name__ == '__main__':
set_silence()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment