Phil
Phil

Reputation: 3994

Script to AWS Lambda?

I have this bash script which lists all active EC2 instances across regions:

for region in `aws ec2 describe-regions --output text | cut -f3` do
 echo -e "\nListing Instances in region:'$region'..."
 aws ec2 describe-instances --region $region
done

I'd like to port this to a Lambda function on AWS. What would be the best approach today? Do I have to use a wrapper or similar? Node? I googled and found what looked like mostly workarounds.. but they were a couple of years old. Would appreciate an up-to-date indication.

Upvotes: 1

Views: 1225

Answers (2)

John Rotenstein
John Rotenstein

Reputation: 270114

You should write it in a language that has an AWS SDK, such as Python.

You should also think about what the Lambda function should do with the output, since at the moment it just retrieves information but doesn't do anything with it.

Here's a sample AWS Lambda function:

import boto3

def lambda_handler(event, context):

    instance_ids = []

    # Get a list of regions    
    ec2_client = boto3.client('ec2')
    response = ec2_client.describe_regions()

    # For each region
    for region in response['Regions']:

        # Get a list of instances
        ec2_resource = boto3.resource('ec2', region_name=region['RegionName'])
        for instance in ec2_resource.instances.all():
            instance_ids.append(instance.id)

    # Return the list of instance_ids
    return instance_ids

Please note that it takes quite a bit of time to call all the regions sequentially. The above can take 15-20 seconds.

Upvotes: 1

Julio Faerman
Julio Faerman

Reputation: 13501

Two ways to do it:

  1. Using custom runtimes and layers: https://github.com/gkrizek/bash-lambda-layer

  2. 'Exec'ing from another runtime: https://github.com/alestic/lambdash

Upvotes: 1

Related Questions