How can I set a default env var for each step whil...
# dev-metaflow
b
How can I set a default env var for each step while still allowing the user to use the
@environment
decorator? If I use the
@environment
decorator for them, it doesn’t allow them to call
@environment
!
1
s
you can set
os.environ['SOME_VAR'] = 'SOME_VALUE'
at the top of the module
@environment
is only needed if you need to set env vars for the container running on remote systems before the Python code executes
b
Thanks @straight-shampoo-11124, I think I need the second behaviour. I need to pass an API key to each step that is getting executed on AWS Batch.
s
you don’t want to pass it as a parameter?
b
I want a default value for the API key that can be changed if you pass in a parameter instead e.g.
Copy code
@environment(...)  # optionally add other env vars
@my_deco           # automatically applies API Key default here
@step
def step(...)
s
something like this maybe:
Copy code
from metaflow import FlowSpec, step, Parameter, environment
from functools import wraps
import os

def mykey(f):
    @wraps(f)
    def func(self):
        env_key = os.environ.get('MYKEY')
        if env_key:
            self.my_key = env_key
        else:
            self.my_key = self.key
        return f(self)
    return func

class OverrideableKey(FlowSpec):

    key = Parameter('key')

    @environment(vars={'MYKEY': 'SOMETHING'})
    @mykey
    @step
    def start(self):
        print('the key is', self.my_key)
        self.next(self.end)

    @step
    def end(self):
        pass

if __name__ == '__main__':
    OverrideableKey()
it uses the parameter value if
@environment
is not specified, otherwise the env var is used
note that you can specify parameters through environment variables too, e.g.
METAFLOW_RUN_KEY=test
in the above example
also deploy-time parameters may come in handy
b
Does this run the risk of leaking your API key? It seems like if you dump the Flow object, you will see
flow.key = "YOUR_API_KEY"
which seems unsafe
f
you can use something like AWS Secrets Manager for API keys