且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-05 11:45:10

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)