Reputation: 159
Let's say that my script is running on an EC2 instance named ec2-test1
and it communicates with an S3 bucket named: s3-bucket-test1
, but when the script is ran on ec2-test2
it's able to identify the EC2 instance it is currently running on and change the directory to reference s3-bucket-test2
. Is there a way to do that? I know that for internal paths you can use os.path.dirname(os.path.realpath(__file__))
but was wondering if there is a way to do something like that for EC2 instance name in Python?
Upvotes: 3
Views: 702
Reputation: 52383
Use the following Boto3 to get the current instance name. Warning: No exception handling is included.
import boto3
import os
def get_inst_name():
# Get Instance ID from EC2 Instance Metadata
inst_id = os.popen("curl -s http://169.254.169.254/latest/meta-data/instance-id").read()
# Get EC2 instance object
ec2 = boto3.resource('ec2')
inst = ec2.Instance(inst_id)
# Obtain tags associated with the EC2 instance object
for tags in inst.tags:
if tags["Key"] == 'Name':
#print tags["Value"]
return tags["Value"]
Upvotes: 4