1

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.

Micha Wiedenmann
21.1k22 gold badges96 silver badges142 bronze badges
asked Mar 1, 2019 at 13:29
1
  • 2
    This is such a tiny and simple piece of code it would probably be quicker to just rewrite it as a Python Lambda function instead of trying to get bash working in Lambda. Commented Mar 1, 2019 at 13:59

2 Answers 2

1

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

answered Mar 1, 2019 at 13:40
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Mar 1, 2019 at 21:57

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.