python-3.xamazon-web-servicesaws-lambdaboto3

How can I get boto3 script to run as a Lambda function?


This works from the CLI but not from within AWS Lambda:

#This will list out all volumes that aren't in use or attached to instances
import boto3
import sys

ec2 = boto3.resource('ec2')
client = boto3.client('sns')
vol_array = ec2.volumes.all()
vol_avail = []

#def chk_vols(event, context):
for v in vol_array:
    if v.state == 'available':
        vol_avail.append(v.id)

response = client.publish(
    TopicArn='arn:aws:sns:us-east-1:444444444444:adm-group',
    Message=str(vol_avail),
    Subject='AWS Volumes Available'
)

I would like to convert this code to be an AWS Lambda function. I've uncommented the line: #def chk_vols(event, context): And properly shifted the For loop over to be under the 'def' statement.

This code will check if any AWS volumes are in the available state and send an SNS message to the adm-group topic. Thank you in advance!


Solution

  • I was able to get my original code to work.

    import boto3
    
    ec2 = boto3.resource('ec2')
    sns = boto3.client('sns')
    
    def chk_vols(event, context):
        vol_array = ec2.volumes.all()
        vol_avail = []
    
        for v in vol_array:
            if v.state == 'available':
                vol_avail.append(v.id)
    
        if vol_avail:
            sns.publish(
                TopicArn='arn:aws:sns:us-east-1:444444444444:adm-group',
                Message=str(vol_avail),
                Subject='AWS Volumes Available'
            )