# Use a secret in a deployment

Give a deployed app a secret as an environment variable, decrypted at each rollout and never stored in the app or the image.

## Prerequisites

- Permission for `deploy:ManageEnv` on the app, and `secrets:GetSecretValue` on each secret you
  bind that the app did not have bound before.
- The secret's key enabled.

## Bind the secret on the app

Bind the secret to a variable on the app's **Environment** page, or in the app's environment API;
see [Set environment variables](/docs/deploy/guide/set-environment-variables) and
[Import a .env file](/docs/deploy/guide/import-a-env-file). Binding grants the `deploy` consumer
on the secret (with no expiry), so no separate grant is needed; see
[Grant a consumer access to a secret](grant-a-consumer.md).

A variable holds the secret it was bound to. When a secret is bound by name, as in a `.env`
import, the name resolves in the app's secrets environment: its own secret there, else the
Default. To choose that environment, set it on the app (`deploy:UpdateApp`):

```http
PUT /secrets/api/apps/3c4d5e6f-7a8b-4c9d-8e0f-1a2b3c4d5e6f/environment
{ "environmentId": "7c6d5e4f-3a2b-4c1d-9e8f-7a6b5c4d3e2f" }
```

`null` resolves names to Default secrets only.

## Result

At each rollout, the control plane refreshes the bound secrets that are synced from a source, then
decrypts the active version of each bound secret and hands it to the app's machine, where the
container receives it as an environment variable. Each read is written to the secret's access log
as the `deploy` consumer. A rotation reaches a running app at its next rollout.

If a synced secret cannot be refreshed, the rollout uses its last synced value.

## Refusals

A rollout fails, naming the secret, when its `deploy` grant was revoked after binding:
"Secret "STRIPE*API_KEY" is not granted to deploy. Grant it under Secrets → Consumers." It also fails
when the secret's key is not enabled: "Encryption key \_key-id* is not enabled".

Binding a secret you may not read is refused with `403`. A deleted secret leaves its variable
without a value, and the app runs without it from the next rollout.

## Related

- [See where a secret goes](see-who-has-read-a-secret.md)
- `secrets.environments.set-app-environment`
