Skip to content

Instantly share code, notes, and snippets.

@ijin
Last active November 24, 2015 13:39
Show Gist options
  • Save ijin/bf735efbec42e1f96d4b to your computer and use it in GitHub Desktop.
Save ijin/bf735efbec42e1f96d4b to your computer and use it in GitHub Desktop.
AWS Lambda function that returns Elastic Beanstalk instance ip address(es)
import boto3
import json
import re
print('Loading function')
def launch_time(item):
return (item.launch_time)
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
env_name = event['env_name']
server_number = event.get('server_num')
filters = [{'Name':'tag:elasticbeanstalk:environment-name','Values':[env_name]},
{'Name':'instance-state-name','Values':['running']}]
ec2 = boto3.resource('ec2', region_name='ap-northeast-1')
instances = ec2.instances.filter(Filters=filters).all()
if not len(list(instances)):
raise Exception("no instances found for: " + env_name)
instances_by_launch_time = sorted(instances, key=launch_time)
if server_number:
public_ip = instances_by_launch_time[int(server_number) - 1].public_ip_address
else:
public_ip = "\n".join(map(lambda x:x.public_ip_address, instances_by_launch_time))
print("env_name: " + env_name + ", server: " + str(server_number))
print(instances_by_launch_time)
print(public_ip)
return public_ip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment