Check whether deployed in cloud

I have a python program running in a Docker container. My authentication method depends on whether the container is deployed in GCP or not. Ideally I’d have a function like this:

def deployment_environment():
    # return 'local' if [some test] else 'cloud'
    pass

What’s the most idiomatic way of checking this? My instinct is to use env named [APP_NAME]_DEPLOYMENT_ENVIRONMENT which gets set either way — but making sure this is set correctly has too many moving parts. Is there a GCP package/tool which can check for me?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There are two solutions I’ve arrived at:

With env

Set an env var when deploying, like so:

gcloud functions deploy [function-name] --set-env-vars ENV_GCP=1

Then, in your code:

import socket


def deployment_environment():
    return 'cloud' if ('ENV_GCP' in os.environ) else 'local'
Pros Cons
intent is clear, both setting and using env more involved
idiomatic relies on user setting env correctly

Via Python, with Sockets

import socket


def deployment_environment():
    try:
        socket.getaddrinfo('metadata.google.internal', 80)
        return 'cloud'
    except socket.gaierror:
        return 'local'
Pros Cons
more succinct makes improper use of try/catch
doesn’t rely on an extra step of setting env dependency on socket package & GCP runtime contract


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x