简体   繁体   English

Python脚本是否可以“识别”它在哪个EC2实例上运行?

[英]Is there a way for a Python script to “recognize” which EC2 instance it is running on?

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 . 假设我的脚本在名为ec2-test1的EC2实例上运行,并且与名为s3-bucket-test1的S3存储桶通信,但是当脚本在ec2-test2上运行时,它可以识别当前是EC2实例运行,并将目录更改为引用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? 我知道对于内部路径,您可以使用os.path.dirname(os.path.realpath(__file__))但想知道是否有办法对Python中的EC2实例名称执行类似的操作?

Use the following Boto3 to get the current instance name. 使用以下Boto3获取当前实例名称。 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"]
  • Get the instance id from metadata server 从元数据服务器获取实例ID
  • Use the instance id to query Boto3 resource 使用实例ID查询Boto3资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在AWS上的现有EC2实例中运行Python脚本 - Running Python Script in an existing EC2 instance on AWS 运行 python 项目的 EC2 实例上的 HTTPS - HTTPS on EC2 instance running python project Python中的Selenium PhantomJS无法在ec2实例上运行 - Selenium PhantomJS in Python not running on ec2 instance python 中是否有办法将 RDP 转换为 windows ec2 实例? - Is there a way in python to RDP into a windows ec2 instance? 如何查看在 EC2 实例中运行的 python 脚本的打印语句? - How can I see a print statement from a python script running in an EC2 instance? 使用AWS API网关触发在EC2实例上运行的python脚本并传递参数 - Use AWS API gateway to trigger python script running on EC2 instance and pass arguments 保留一个在EC2实例上运行的tensorflow(anaconda venv)脚本 - Leave a tensorflow (anaconda venv) script running on EC2 instance Python 脚本将文件从 ec2 windows 实例复制到 ec2 linux 实例 - Python script to copy files from ec2 windows instance to ec2 linux instance 让 Django 服务器在 EC2 实例上运行的正确方法是什么? - What is the correct way to leave a Django server running on an EC2 instance? 在多个EC2实例之间自动运行相同python脚本的简单方法? - Easy way to automate running same python script across several EC2 instances?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM