欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

lambda扫描SQS后terminate EC2 instance

程序员文章站 2022-04-17 23:19:34
...

import boto3

 

REGION = 'cn-north-1'
EC2 = boto3.client('ec2', region_name=REGION)

sqs = boto3.client('sqs')
queue_url = 'https://sqs.*******'

 

def lambda_terminate_ec2(event, context):
    #message = event['message']

    response = sqs.receive_message(
        QueueUrl=queue_url,
        AttributeNames=['********'],
        MaxNumberOfMessages=1,
        MessageAttributeNames=['All'],
        VisibilityTimeout=0,
        WaitTimeSeconds=0
    )

    message = response['Messages'][0]
    receipt_handle = message['ReceiptHandle']
    msg = message['Body']
   
    instance = EC2.terminate_instances(
        InstanceIds=[msg],
        DryRun= False
    )
   
    # Delete received message from queue
    sqs.delete_message(
        QueueUrl=queue_url,
        ReceiptHandle=receipt_handle
    )
   
    return msg