Search code examples
pythongoogle-cloud-platformcloudgoogle-cloud-run

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?


Solution

  • 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