Error trying to (re)attach a database: "app already contains a secret named DATABASE_URL"

After having detach and removed a previous db and then created a new one (I wanted to restore from a snapshot of an other db from a previous version of the app), I always receive an error when trying to attach the new one.

These are the steps I followed:

1) Detach the db

$ flyctl pg connect -a <my-pg-app>
# DROP DATABASE <my-attached-app-db> WITH (FORCE);
# DROP USER <my-attached-app-role> WITH (FORCE);
$ flyctl postgres detach --app  <my-app>  <my-pg-app>

2) Delete detached db via web dashboard interface

3) Create new db

# first tried to restore from a snap shot via $ fly postgres create --snapshot-id <my-snapshot-id> with no luck, then tried to create a brand new db:
$ fly postgres create

4) Attach new created db

$ fly postgres attach 

5) Got error

Error consumer app "<my-app>" already contains a secret named DATABASE_URL

6) Try to manually (re)set the DATABASE_URL

$ fly secrets set DATABASE_URL=postgres://postgres:<my-app-db-password>@<my-app-db>.internal:5432 --app <my-app>

5) Got same error

Error consumer app "<my-app>" already contains a secret named DATABASE_URL

6) Try to unset DATABASE_URL

$ fly secrets unset DATABASE_URL  --verbose
Release v15 created
==> Monitoring deployment
[...]
2022-09-30T08:01:43Z   [info]  /app/releases/0.1.0/runtime.exs:51
2022-09-30T08:01:43Z   [info]ERROR! Config provider Config.Reader failed with:
2022-09-30T08:01:43Z   [info]** (RuntimeError) environment variable DATABASE_URL is missing.
2022-09-30T08:01:43Z   [info]For example: ecto://USER:PASS@HOST/DATABASE
[...]
--> v15 failed - Failed due to unhealthy allocations - not rolling back to stable job version 15 as current job has same specification and deploying as v16
--> Troubleshooting guide at https://fly.io/docs/getting-started/troubleshooting/
Error abort

I don’t understand if I’m missing something, or if something went wrong behind the scenes outside my control. Any suggestion to avoid to resolve deleting and recreating also the app?

Ah, looking at the error, it appears to be coming from your app because setting secrets incurs a deploy. Could you fly scale count 0 to scale to zero? Then you should be able to unset and set your env var.

1 Like

setting secrets incurs a deploy

oh, right, good point

Could you fly scale count 0 to scale to zero? Then you should be able to unset and set your env var.

this solved the stranding

Thank you @jphenow !

As a reference for future readers, these are all the further steps I’ve done:

$ fly scale count 0

$ fly secrets unset DATABASE_URL

$ fly postgres attach <my-pg-app>

$ fly scale count 1

$ fly deploy
3 Likes

FYI: flyctl secrets unset has a --stage option. flyctl secrets unset · Fly Docs

1 Like