假设我的脚本在名为 ec2-test1
的 EC2 实例上运行,它与名为 s3-bucket-test1
的 S3 存储桶通信,但是当脚本在 ec2-test2
上运行,它能够识别当前运行的 EC2 实例并更改目录以引用 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"]
- 从元数据服务器获取实例ID
- 使用实例id查询Boto3资源
关于python - 有没有办法让 Python 脚本到 "recognize"它运行的是哪个 EC2 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44595564/