Advertisements
Skip to content

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()

 

Advertisements

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: