Eric Albanese
03/20/2024, 6:23 PMMarvin
03/20/2024, 6:23 PMpython
from prefect import task, Flow
import os
@task
def get_user_profile():
# Check an environment variable to determine the run context
env = os.getenv('PREFECT_ENV', 'production')
if env == 'development':
return "dev_user_profile"
else:
return "prod_user_profile"
with Flow("dbt_flow") as flow:
user_profile = get_user_profile()
# ... more flow tasks using the obtained user_profile
# Set the environment variable before running the flow locally
os.environ['PREFECT_ENV'] = 'development'
# for production in cloud do not set the environment variable or set to 'production'
In this example, an environment variable PREFECT_ENV
is used to determine the environment. When you run the flow on your local machine, you set PREFECT_ENV=development
, and for cloud runs, you either don't set the variable or set it to production
. Depending on the value of PREFECT_ENV
, get_user_profile
will return the appropriate user profile.
You would need to set environment variables differently depending on whether you're running locally or in the cloud. For local runs, you could set them in your shell or through a .env
file. For cloud runs, you'd set them in your cloud environment or through Prefect's UI for environment configuration.
Remember to ensure that your strategy for toggling between environments aligns with your CI/CD process and infrastructure setup.
For further reading on using environment variables and configuring Prefect, you can refer to these links:
- Prefect Core's Environment Variable Config
- Prefect Security
For a more specific solution or if there's a feature in Prefect 2.x that facilitates the distinction between local and cloud execution contexts, I'd recommend reaching out to the Prefect community or looking into the Prefect 2.x documentation.