【问题标题】:Is there a way for a Python script to "recognize" which EC2 instance it is running on?有没有办法让 Python 脚本“识别”它正在运行的 EC2 实例?
【发布时间】:2017-11-19 14:29:44
【问题描述】:
假设我的脚本在名为 ec2-test1 的 EC2 实例上运行,并且它与名为 s3-bucket-test1 的 S3 存储桶通信,但是当脚本在 ec2-test2 上运行时,它能够识别它所在的 EC2 实例当前正在运行并将目录更改为引用s3-bucket-test2。有没有办法做到这一点?我知道对于内部路径,您可以使用os.path.dirname(os.path.realpath(__file__)),但想知道是否有办法在 Python 中为 EC2 实例名称做类似的事情?
【问题讨论】:
标签:
python
python-3.x
amazon-web-services
amazon-ec2
boto3
【解决方案1】:
使用以下 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资源