python - 有没有办法让 Python 脚本到 "recognize"它运行的是哪个 EC2 实例?

标签 python python-3.x amazon-web-services amazon-ec2 boto3

假设我的脚本在名为 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/

相关文章:

python - 从 Python 原始套接字接收的数据包中交换了两个字节

java - 如何以及何时在 AWS SES Java 开发工具包中使用 'Async'

python - 从某个键拆分 python 字典

python - 将方法动态绑定(bind)到python中的类实例

python-3.x - 将秒数的numpy数组转换为分钟和秒

python - 在从另一个用 C 实现的类驱动的类上使用元类

amazon-web-services - AWS Athena 查询输出格式

amazon-web-services - CloudFormation CloudTrail S3 策略错误 - 检测到存储桶的 S3 存储桶策略不正确

python - 在 Python 中 x==x 是 False 吗?

python - 在Python 3和Python 2中处理CSV中的非UTF8字符