How to securely store secrets in Prefect 2.0?

Create a Secret

UI

You can create a Secret either via UI:

Code

Or via a simple flow:

from prefect import flow
from prefect.blocks.system import Secret


@flow
def add_secret_block():
    Secret(value="mysuperstrongP4ssw0rd42").save(name="db_password")


if __name__ == "__main__":
    add_secret_block()

Using Secret in your flow

To use the above created Secret in your flow, load the Secret block and call the get method:

from prefect import flow
from prefect.blocks.system import Secret


@flow
def retrieve_secret():
    db_pwd = Secret.load("db_password").get()
    print(db_pwd)


if __name__ == "__main__":
    retrieve_secret()

Real-life example

Here is an example of using a Slack webhook URL (stored as Secret from the UI) with the prefect-slack Collection:

from prefect import flow
from prefect.blocks.system import Secret
from prefect_slack import SlackWebhook
from prefect_slack.messages import send_incoming_webhook_message


@flow
def send_slack_message_with_secret_block():
    secret_value = Secret.load("SLACK_WEBHOOK_URL").get()
    send_incoming_webhook_message(
        slack_webhook=SlackWebhook(secret_value),
        text="Message sent thanks to a Secret block! :tada:",
    )


if __name__ == "__main__":
    send_slack_message_with_secret_block()

image