Skip to content

Instantly share code, notes, and snippets.

@hwshim0810
Last active February 10, 2020 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hwshim0810/92cb95ce074424a88c13b73e22ea5f7e to your computer and use it in GitHub Desktop.
Save hwshim0810/92cb95ce074424a88c13b73e22ea5f7e to your computer and use it in GitHub Desktop.
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
@bastiW
Copy link

bastiW commented Feb 9, 2020

What are this lines doing?

       response = urlopen('http://169.254.169.254/latest/meta-data/local-ipv4')
        ec2_ip = response.read().decode('utf-8')

@hwshim0810
Copy link
Author

hwshim0810 commented Feb 10, 2020

What are this lines doing?

       response = urlopen('http://169.254.169.254/latest/meta-data/local-ipv4')
        ec2_ip = response.read().decode('utf-8')

@bastiW
It's getting aws ec2 instance private IP address.
I'm using for backend server health check with elb.

ref:Retrieving Metadata
ref:Instance Metadata

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment