Skip to content

Instantly share code, notes, and snippets.

@bootrino
Last active August 22, 2018 08:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bootrino/7ae38d38dabf0a4be109374247178e90 to your computer and use it in GitHub Desktop.
Save bootrino/7ae38d38dabf0a4be109374247178e90 to your computer and use it in GitHub Desktop.
Python 3.6 AWS Lambda function to create a hosts file from running EC2 instances and put it in a bucket
import boto3
import json
import jmespath
s3 = boto3.resource('s3')
ec2 = boto3.resource('ec2')
# creates a hosts file for all running ec2 instances
# you can add alias hostnames by adding a tag "hostname" to the EC2 instance
ec2_instances = []
region = 'eu-west-1'
hosts_file = ""
bucket_name = 'yourbucketname'
def lambda_handler(event, context):
# create filter for instances in running state (unused)
"""
filters = [
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
"""
filters = []
hosts = \
"""
# this is an autogenerated hosts file that includes running EC2 instances
127.0.0.1 localhost
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
# running EC2 instances:
"""
# filter the instances based on filters() above (unused)
instances = ec2.instances.filter(Filters=filters)
for instance in instances:
if instance.state.get("Name", None) != "running":
continue
tags = instance.tags or []
line = instance.private_ip_address
line = line.ljust(25, ' ')
line += instance.private_dns_name
for item in tags:
if item.get("Key", None) == "hostname":
hostname = item.get("Value", "")
line += f" {hostname}"
line += "\n"
hosts += line
# unused
state_map = {
0: 'pending',
16: 'running',
32: 'shutting-down',
48: 'terminated',
64: 'stopping',
80: 'stopped',
}
ec2_instances.append(
{
'id': instance.id or "",
'private_dns_name': instance.private_dns_name or "",
'private_ip_address': instance.private_ip_address or "",
'public_dns_name': instance.public_dns_name or "",
'public_ip_address': instance.public_ip_address or "",
'state': instance.state or "",
'subnet_id': instance.subnet_id or "",
'tags': tags or "",
'vpc_id': instance.vpc_id or "",
}
)
s3.Bucket(bucket_name).put_object(
Key=f'{region}_ec2_instances.json',
Body=bytes(json.dumps(ec2_instances, indent=4), encoding="UTF-8"),
ContentType='application/json',
)
s3.Bucket(bucket_name).put_object(
Key=f'{region}_hosts',
Body=bytes(hosts, encoding="UTF-8"),
ContentType='text/plain',
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment