Skip to content

Instantly share code, notes, and snippets.

@ej-acebedo
Created January 20, 2023 13:24
Show Gist options
  • Save ej-acebedo/43d0545d26b38f41ab4933a94400bec9 to your computer and use it in GitHub Desktop.
Save ej-acebedo/43d0545d26b38f41ab4933a94400bec9 to your computer and use it in GitHub Desktop.
import boto3
import json
import base64
#set up ec2 client
#adjust region_name according to your preference
ec2 = boto3.client('ec2', region_name='us-east-1')
def lambda_handler(event, context):
#Uncomment to log the event object in CloudWatch Logs
# print(event)
payload = parse_slack_payload(event["body"])
tag_name = 'Env'
tag_value = payload['text']
#filter instances by tag name and value
response = ec2.describe_instances(Filters=[{'Name': 'tag:' + tag_name, 'Values': [tag_value]}])
# get the instance id and state of each instance
instances = [ (instance['Instances'][0]['InstanceId'], instance['Instances'][0]['State']['Name'])
for instance in response['Reservations']
]
#prepare slack message
slack_message=build_slack_message(instances=instances)
#send response back to Slack
return {
"statusCode": 200,
"headers": { "Content-Type": "application/json" },
"body": json.dumps(slack_message)
}
def parse_slack_payload(data):
# decode the data using the b64decode function
decoded_data_raw = base64.b64decode(data).decode('utf-8').split('&')
decoded_data_formatted={}
for item in decoded_data_raw:
data_object = item.split('=')
decoded_data_formatted[data_object[0]] = data_object[1]
return decoded_data_formatted
def build_slack_message(instances):
slack_message = { "blocks": [
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Instance Id*"
},
{
"type": "mrkdwn",
"text": "*State*"
}
]
} ]
}
for instance_id, instance_state in instances:
block = {
"type": "section",
"fields": [
{ "type": "mrkdwn", "text": instance_id },
{ "type": "mrkdwn", "text": instance_state }
]
}
slack_message["blocks"].append(block)
return slack_message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment