# Rotate a secret

Store a new value as the next version, or make an earlier version active again.

Replace _5b8c1d2e-3f4a-4b6c-8d7e-9f0a1b2c3d4e_ with the secret's id.

## Prerequisites

- To rotate, `secrets:RotateSecret` on the secret. To list versions, `secrets:ListSecretVersions`.
  To roll back, `secrets:RollbackSecret`. In the console, also `secrets:ListSecrets` to open
  **Secrets**; without it the page says "You do not have permission to list secrets."
- A secret you store yourself. A synced secret is refused (change it in the source and sync; see
  [Sync a secret from a source](sync-a-secret-from-a-source.md)), and so is a secret managed by
  Error Tracking.
- The secret's key enabled, to rotate.

## Rotate to a new value

**Console**
1. Open **Secrets** and choose the secret.
2. In its panel, choose **Rotate** (also in the row's **⋯** menu).
3. For **New value**, paste the value.
4. Choose **Rotate**.

The panel shows the new version as active.

**CLI**
```sh
dcloud secrets secrets rotate 5b8c1d2e-3f4a-4b6c-8d7e-9f0a1b2c3d4e --value 'sk_test_EXAMPLE2'
```

**API**
```http
POST /secrets/api/secrets/5b8c1d2e-3f4a-4b6c-8d7e-9f0a1b2c3d4e/rotate
{ "value": "sk_test_EXAMPLE2" }
```

**Terraform**
Change `value` on the `dcloud_secret` and run `terraform apply`. The change is a rotation.

The answer is `200` with `{ version }`, the new active number. The previous version is retired, not
deleted. With a rotation policy, the due date starts again from now. Running apps and jobs keep the
old value until their next deployment or run.

## Roll back to an earlier version

**Console**
1. In the secret's panel, under **Versions**, find the retired version.
2. Choose **Roll back** beside it.

**CLI**
```sh
dcloud secrets secrets list-versions 5b8c1d2e-3f4a-4b6c-8d7e-9f0a1b2c3d4e
dcloud secrets secrets rollback 5b8c1d2e-3f4a-4b6c-8d7e-9f0a1b2c3d4e --version 2
```

**API**
```http
POST /secrets/api/secrets/5b8c1d2e-3f4a-4b6c-8d7e-9f0a1b2c3d4e/rollback
{ "version": 2 }
```

`GET /secrets/api/secrets/{id}/versions` lists the versions newest first, never a value.

**Terraform:** not available. A rollback is not a configuration change.

The version becomes active under its own number and the one that was active is retired.

## Refusals

- `409` "This secret is synced from a source: change it there and use Sync now. A manual rotation
  or rollback would be overwritten by the next sync."
- `409` for a secret managed by Error Tracking, naming where to rotate it.
- `409` "Key is not enabled" (rotate).
- `404` "No such version" (rollback).

## Related

- [Secrets and versions](secrets-and-versions.md)
- `secrets.secrets.rotate` · `secrets.secrets.rollback` · `dcloud_secret`
