检查aws实例上是否正在运行python脚本 [英] Check if python script is running on an aws instance

查看:117
本文介绍了检查aws实例上是否正在运行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个python记录器,以便在实例设置了标签的情况下记录错误时发送错误电子邮件.然后,我很快遇到了不在AWS上的本地开发计算机的问题.有没有简便快捷的方法来检查脚本是否在AWS上运行?

I'm trying to set up a python logger to send error emails when it logs an error iff the instance has a tag set. I then quickly run into the problem of local dev computers that aren't on aws. Is there an easy and fast way to check if the script is being run on aws?

我正在使用以下方式加载实例数据:

I was loading the instance data with:

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_metadata上使用超时,但是现在等待开发人员等待的时间与在生产环境中不发送错误电子邮件的可能性之间存在压力.

I can of course use a timeout on get_instance_metadata, but there is then a tension between now long to make developers wait vs the possibility of not sending an error email in production.

有人能想到一个好的解决方案吗?

Can anyone think of a nice solution?

推荐答案

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

AWS instances have metadata, so you could make a call to the metadata service and get a response, if the response is valid, you are @ AWS, otherwise you are not.

例如:

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或其他云服务,那么您当然会得到元数据响应,因此您必须相应地调整支票...

This is just a stab - there are likely better checks but this one will get you the feel for it and you can improve upon it as you see fit. IF you are using OpenStack or another cloud service locally you of course will get a metadata response, so you will have to adjust your check accordingly...

(如果您正在使用某种启动工具或管理器(例如Chef,Puppet,Homegrown等),也可以使用cloud-init的东西执行此操作.如果/ec2文件位于AWS或更高级的文件系统中,则将其拖放到文件系统中但是如果本地将一个/DEV放到盒子上

(you could also do this with cloud-init stuff if you are using some kind of launch tool or manager like chef, puppet, homegrown, etc. Drop an /ec2 file in the file system if it's in AWS, or better yet if local drop a /DEV on the box)

这篇关于检查aws实例上是否正在运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆