检查python脚本是否正在aws实例上运行

2024-04-24 16:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图设置一个python记录器,当它记录错误时发送错误电子邮件,如果实例有一个标记集。然后我很快就遇到了不在aws上的本地开发计算机的问题。有没有一种简单快速的方法来检查脚本是否在aws上运行?在

我正在加载实例数据:

import boto.utils
from boto.ec2.connection import EC2Connection
metadata = boto.utils.get_instance_metadata()
conn = EC2Connection()
instance = conn.get_only_instances(instance_ids=metadata['instance-id'])[0]

当然,我可以在get_instance_元数据上使用超时,但是现在长时间让开发人员等待与在生产中不发送错误电子邮件的可能性之间存在紧张关系。在

有人能想出一个好的解决办法吗?在


Tags: 数据实例instanceimportawsget电子邮件错误
3条回答

我不认为这真的是个问题。EC2(以及boto)并不关心或知道您在服务器上运行的脚本。在

如果您的脚本有一个特定的签名,例如监听一个端口,这是检查的最佳方式,但又不必这样做,您可以在操作系统的进程中查找它的签名。在

使用子流程模块和您的preferred bash magic to check if it's running

command = ["ssh", "{user}@{server}", "pgrep", "-fl", "{scriptname}"]
try:
    is_running = bool(subprocess.check_output(command))
except subprocess.CalledProcessError:
    log.exception("Checking for script failed")
    is_running = False

类似于@cgseller,假设python3,可以做如下操作:

from urllib.request import urlopen

def is_ec2_instance():
    """Check if an instance is running on AWS."""
    result = False
    meta = 'http://169.254.169.254/latest/meta-data/public-ipv4'
    try:
        result = urlopen(meta).status == 200
    except ConnectionError:
        return result
    return result

AWS实例有元数据,因此您可以调用元数据服务并获得响应,如果响应有效,则您是@AWS,否则您不是。在

例如:

import urllib2
meta = 'http://169.254.169.254/latest/meta-data/ami-id'
req = urllib2.Request(meta)
try:
    response = urllib2.urlopen(req).read()
    if 'ami' in response:
        _msg = 'I am in AWS running on {}'.format(response)
    else:
        _msg = 'I am in dev - no AWS AMI'
except Exception as nometa:
    _msg = 'no metadata, not in AWS'

print _msg

这只是一个刺-可能有更好的检查,但这一个会让你的感觉,你可以改善它,因为你认为合适。如果您在本地使用OpenStack或其他云服务,您当然会得到一个元数据响应,因此您必须相应地调整您的检查。。。在

(如果您正在使用某种启动工具或管理器(如chef、puppet、homebood等),也可以使用cloud init工具来完成此操作。如果/ec2文件位于AWS中,则将其放入文件系统中,如果本地将a/DEV放在该文件系统中,则更好)

相关问题 更多 >