Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

amazon web services - How to check whether my code runs in a container on AWS EC2 or not

My (python) code runs inside a docker container.

The container is deployed on AWS EC2 for our production and testing purposes, but sometimes on our local machines or other cloud vendors for development and CICD purposes.

For some functionality, I want my python code to be able to distinguish between an EC2 deployment and non-EC2. Is this possible?

I found this answer which uses the EC2 instance metadata endpoint, But I'm wondering:

a) Would this also work from within a docker container?

b) Isn't there a more elegant solution? Issuing an HTTP request and waiting for it seems a bit too much.

(I'm aware that a simple solution is probably to add some proprietary environment variable or flag, trying to find a more native to check this)

question from:https://stackoverflow.com/questions/65917074/how-to-check-whether-my-code-runs-in-a-container-on-aws-ec2-or-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I recommend you to go with a custom environment variable. This way you will be able to easily reproduce the required behaviour outside of AWS (on your workstation or using other cloud provider).

Using curl or checking for presence of /etc/cloud would make your application behaviour dependent on third-party services/tools. Beside logic complexity (you'd have to handle possible curl errors, like invalid response codes) that can lead to bugs you surely don't want to meet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...