Monitor an SQS Queue based on your instance id

Example of monitoring an SQS queue for messages that an attribute instance_id, which is set to your EC2 instance. The python subscriber can be used to monitor a shared SQS and act upon messages targeted at a specific instance id.

#!/usr/bin/env python3

import boto3
import requests
import subprocess
import os
import time

boto3.setup_default_session(region_name="${aws.region}")

sqs = boto3.resource('sqs')

response = requests.get('http://169.254.169.254/latest/meta-data/instance-id')
instance_id = response.text
build_bucket = "${aws.s3.bucket}"

# Retrieving a queue by its name
queue = sqs.get_queue_by_name(QueueName='${aws.sqs.updateQueue}')
autoscaling = boto3.client('autoscaling')
ec2 = boto3.client('ec2')
while 1:
    messages = queue.receive_messages(WaitTimeSeconds=5, VisibilityTimeout=1, MessageAttributeNames=['instance_id'])
    for message in messages:
        if message.message_attributes is not None:
            msg_instance_id = message.message_attributes.get('instance_id').get('StringValue')
            if msg_instance_id == instance_id:
                time.sleep(30)
                # do something
                message.delete()

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: