Last active
February 7, 2018 21:42
-
-
Save alexandraj777/ab9e95a0216a75ca3c564b6324ace047 to your computer and use it in GitHub Desktop.
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 logging | |
import boto3 | |
from botocore.exceptions import ClientError, BotoCoreError | |
import requests | |
from requests import RequestException | |
def get_instance_name(): | |
try: | |
r = requests.get("http://169.254.169.254/latest/dynamic/instance-identity/document") | |
r.raise_for_status() | |
except RequestException as e: | |
logging.exception(e) | |
return None | |
try: | |
response_json = r.json() | |
except ValueError as e: | |
logging.exception(e) | |
return None | |
region = response_json.get('region') | |
instance_id = response_json.get('instanceId') | |
if not (region and instance_id): | |
logging.error('Invalid region: {} or instance_id: {}'.format(region, instance_id)) | |
return None | |
try: | |
ec2 = boto3.resource('ec2', region_name=region) | |
instance = ec2.Instance(instance_id) | |
tags = instance.tags | |
except (ValueError, ClientError, BotoCoreError) as e: | |
logging.exception(e) | |
return None | |
tags = tags or [] | |
names = [tag.get('Value') for tag in tags if tag.get('Key') == 'Name'] | |
name = names[0] if names else None | |
return name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment