Skip to content

Instantly share code, notes, and snippets.

@hwshim0810 hwshim0810/ec2_function.py
Last active Jul 10, 2019

Embed
What would you like to do?
Get ec2 private ip
import os
def is_ec2_linux():
"""Detect if we are running on an EC2 Linux Instance
See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html
"""
if os.path.isfile("/sys/hypervisor/uuid"):
with open("/sys/hypervisor/uuid") as f:
uuid = f.read()
return uuid.startswith("ec2")
return False
def get_linux_ec2_private_ip():
"""Get the private IP Address of the machine if running on an EC2 linux server"""
from urllib.request import urlopen
if not is_ec2_linux():
return None
try:
response = urlopen('http://169.254.169.254/latest/meta-data/local-ipv4')
ec2_ip = response.read().decode('utf-8')
if response:
response.close()
return ec2_ip
except Exception as e:
print(e)
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.