From 6d78e5e51d8e091c831211ed0465fc616c4e1542 Mon Sep 17 00:00:00 2001 From: datashaman Date: Wed, 17 Jan 2024 08:46:10 +0200 Subject: [PATCH] Add slack notification for start/finish --- .env.example | 4 ++++ .gitignore | 8 +++----- README.md | 2 ++ setup.py | 2 ++ terraecs/__main__.py | 29 ++++++++++++++++++++++++++++- 5 files changed, 39 insertions(+), 6 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..2b2cc97 --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +# Optional channel, default to whatever is setup on webhook +# SLACK_CHANNEL= +# Optional webhook URL. If no webhook is provided, the command will not send any messages. +# SLACK_WEBHOOK_URL= diff --git a/.gitignore b/.gitignore index 0f93c82..b62d880 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,7 @@ -/.vscode/ +/*.egg-info +/.env /.venv/ - /build/ /dist/ -/*.egg-info -__pycache__ - /output.json +__pycache__ diff --git a/README.md b/README.md index c1319af..1811229 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,9 @@ _Preview release, please do not use for anything important!_ ```bash $ pip install terraecs +$ cp .env.example .env ``` +Edit the `.env` file to your taste for Slack notifications. ## Usage diff --git a/setup.py b/setup.py index 66535dc..126c638 100644 --- a/setup.py +++ b/setup.py @@ -22,6 +22,8 @@ install_requires=[ 'boto3', 'click', + 'python-dotenv', + 'requests', ], entry_points={ 'console_scripts': [ diff --git a/terraecs/__main__.py b/terraecs/__main__.py index c8e182e..f2e84f8 100644 --- a/terraecs/__main__.py +++ b/terraecs/__main__.py @@ -2,8 +2,17 @@ import click import json import logging +import os +import requests import time +from dotenv import load_dotenv +load_dotenv() + + +SLACK_CHANNEL = os.getenv('SLACK_CHANNEL') +SLACK_WEBHOOK_URL = os.getenv('SLACK_WEBHOOK_URL') + class ContextFilter(logging.Filter): def filter(self, record): @@ -26,6 +35,19 @@ def filter(self, record): output_file = None +def notify_slack(text): + if not SLACK_WEBHOOK_URL: + return + + payload = { + 'text': text, + } + + if SLACK_CHANNEL: + payload['channel'] = SLACK_CHANNEL + + requests.post(SLACK_WEBHOOK_URL, json=payload) + def log(message, level=logging.ERROR, **context): logger.log(level, message, extra={'context': context}) @@ -62,6 +84,7 @@ def run(command): log(f'could not find the {required_key}... Aborting') exit(1) + notify_slack(f'`terraecs run {" ".join(command)}` started') ecs_client = boto3.client('ecs') logs_client = boto3.client('logs') @@ -142,7 +165,11 @@ def run(command): time.sleep(sleep_seconds) - exit(get_exit_code(response['tasks'][0]['containers'])) + exit_code = get_exit_code(response['tasks'][0]['containers']) + + notify_slack(f'`terraecs run {" ".join(command)}` finished with exit code {exit_code}') + + exit(exit_code) if __name__ == "__main__": cli(None)