假设我的脚本在名为的EC2实例上运行,ec2-test1
并且与名为:的S3存储桶通信s3-bucket-test1
,但是在运行脚本时,ec2-test2
它可以识别当前在其上运行的EC2实例,并将目录更改为reference s3-bucket-test2
。有没有办法做到这一点?我知道您可以使用内部路径,os.path.dirname(os.path.realpath(__file__))
但是想知道是否有办法对Python中的EC2实例名称执行类似的操作?
使用以下Boto3获取当前实例名称。警告:不包括异常处理。
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"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句