Last active
February 10, 2020 04:09
-
-
Save hwshim0810/92cb95ce074424a88c13b73e22ea5f7e to your computer and use it in GitHub Desktop.
Get ec2 private ip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What are this lines doing?