# Terraform state

> Keep Terraform and OpenTofu state in a repository, through their http backend on registry.branchd.run, with locking, every version kept, and restore and force-unlock in the console.
A repository can hold Terraform and OpenTofu states. Each state has a name,
and lives at one URL on the packages host. That URL serves the state and its
lock:

```
https://registry.branchd.run/terraform/<repository>/<state>
```

- **`<repository>`** is the repository's full path, such as `acme/infra`.
- **`<state>`** is a name you choose: letters, digits and `.` `_` `-`,
  starting with a letter or digit, at most 200 characters. Use one state per
  stack and environment, such as `mysql-prod`.
- **Every write is kept as a version**, numbered from 1. The newest one is
  the current state.
- **A state holds secrets, so it is never public.** Reading one needs write
  access on the repository. It is encrypted at rest, and it is never handed
  out by a link.

## Set up the backend

```hcl
terraform {
  backend "http" {
    address        = "https://registry.branchd.run/terraform/acme/infra/mysql-prod"
    lock_address   = "https://registry.branchd.run/terraform/acme/infra/mysql-prod"
    unlock_address = "https://registry.branchd.run/terraform/acme/infra/mysql-prod"
    username       = "token"
  }
}
```

- **All three addresses are the same URL.** Keep the default methods: the
  URL answers `GET`, `POST`, `DELETE`, `LOCK` and `UNLOCK`.

- **The password is a token**, from `TF_HTTP_PASSWORD`, so it stays out of
  the file:

  ```sh
  export TF_HTTP_PASSWORD="$(branchd auth token)"   # or a personal API key
  tofu init
  ```

- **Set a username.** Its value is not read, but Terraform sends no password
  without one.

- **The first write creates the state.** There is nothing to create first.

To move an existing state in, change the backend block and run:

```sh
tofu init -migrate-state
```

Terraform copies the current state across as version 1. The old backend
keeps its copy until you delete it.

## Locking

Terraform locks the state for every `plan` and `apply`. A second run is
refused while it holds the lock, and Terraform prints who holds it and for
what:

```
Error acquiring the state lock
Lock Info:
  ID:        6f1c…
  Operation: OperationTypeApply
  Who:       ci@runner-4
```

A run that was killed can leave its lock behind. Release it with
`tofu force-unlock <ID>`, or with **Force unlock** on the state's page in
the console. Both need the maintain level. Only release a lock when you are
sure its run has stopped: two applies writing the same state at once can
lose resources from it.

## In a pipeline

The steps in [`branchd/steps/opentofu`](https://branchd.run/branchd/steps/opentofu)
run OpenTofu against a state of the repository, with the backend and the
job's token set up for you. The stack declares an empty backend:

```hcl
terraform {
  backend "http" {}
}
```

```yaml title=".branchd/pipelines/terraform.yaml"
# .branchd/pipelines/terraform.yaml
# Plans every pull request against the repository's Terraform state `prod`,
# and applies on pushes to main (a protected branch). The stack declares an
# empty `backend "http" {}`: the steps point it at
# https://registry.branchd.run/terraform/<repository>/prod and give it the
# job's token, which also reaches the states its terraform_remote_state
# blocks read where a CI grant lets it.
name: Terraform
on:
  push:
    branches: [main]
  pull_request:
permissions:
  terraform-state: write    # read only, on a pull request's run
  pull-requests: write      # for plan's comment on the pull request
jobs:
  plan:
    if: event == 'pull_request'
    steps:
      - uses: branchd/steps/opentofu/plan@v1
        with: {state: prod, working_directory: infra}
  apply:
    if: branch == 'main' && event == 'push'
    steps:
      - uses: branchd/steps/opentofu/apply@v1
        with: {state: prod, working_directory: infra}
```

- **`plan@v1`** runs `tofu init` and `tofu plan`, and outputs `has_changes`,
  `add`, `change` and `destroy`. On a pull request it comments the plan's
  summary there, and updates the comment on later runs. Without
  `pull-requests: write` it skips the comment and says so.
- **`apply@v1`** applies the plan of an earlier `plan` step in the same job,
  or plans and applies. It outputs the root outputs, sensitive ones left out.
- **`output@v1`** reads a state's non-sensitive outputs into step outputs,
  without OpenTofu or a checkout.
- **The token stays fresh.** A job token lives for minutes, so the steps
  pass OpenTofu a fresh one on every request, and a long apply still writes
  its state and releases its lock.

The job's `permissions:` decide what its token may do:

- **`read`** gets the state. **`write`** also writes it and takes its lock.
- **Writes need a protected ref**, as package writes do. On a pull request
  or an unprotected branch the token only reads, so `plan` there runs with
  `-lock=false`.

Without the steps, set the backend's password from the job's token
yourself:

```sh
export TF_HTTP_USERNAME=job TF_HTTP_PASSWORD="$BRANCHD_TOKEN"
tofu init -input=false && tofu apply -input=false -auto-approve
```

See [Job token](https://docs.branchd.run/branchd/pipelines/job-token#permissions) for every
permission.

## Another repository's state

A stack can read another stack's outputs with `terraform_remote_state`:

```hcl
data "terraform_remote_state" "network" {
  backend = "http"
  config = {
    address  = "https://registry.branchd.run/terraform/acme/network/prod"
    username = "token"
  }
}

resource "aws_instance" "app" {
  subnet_id = data.terraform_remote_state.network.outputs.subnet_id
}
```

- **The password comes from `TF_HTTP_PASSWORD`**, as for the backend: one
  token covers the stack's own state and every state it reads. Leave the
  password out of the block.
- **Always set `address`.** Without it, the block reads the stack's own
  state.
- **You need write access on the other repository** to read its state
  yourself, as for any state.

### Let another repository's jobs in

A job reads another repository's state only where that repository grants
it, with a CI grant on the Terraform state area. Make one on the
repository that holds the state, from its **Terraform** tab
(**Reached by**, then **Grant access**), from its settings (**Access**,
then **CI access**), or with the CLI:

```sh
branchd tfstate grant acme/network --to repo:acme/app --level outputs
```

| Level     | The other repository's jobs may                                                                                                                                               |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `outputs` | Read the state's root outputs, sensitive ones included, and nothing else. Its resources, and the secrets they hold, are left out. This is all `terraform_remote_state` needs. |
| `read`    | Read the whole state, every secret in it included.                                                                                                                            |
| `write`   | Also write the state and take its lock, on a protected run only.                                                                                                              |

- **The reading job also declares** `permissions: terraform-state: read` in
  its own pipeline file.
- **A grant can name** a repository, a group, a team or the company, and
  apply to any run, protected runs only, or as the run's owner, as
  [CI grants](https://docs.branchd.run/branchd/packages/access#another-repositorys-jobs) do
  for packages. A grant made on a group covers every repository under it.
- **No grant deletes a state.**
- **A refused read shows only "invalid auth"** in OpenTofu's output, because
  it does not print the answer's body. The full reason is in the run's
  audit, and `branchd repo grant explain acme/network --from acme/app`
  says which grant would apply.

## From the CLI

`branchd tfstate` (CLI 0.73 or later) works with a repository's states. Inside
a clone, `-R` can be left out.

| Command                                     | Does                                                                                     |
| ------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `branchd tfstate list`                      | Lists the states, with their newest version and lock                                     |
| `branchd tfstate show <state>`              | Shows a version's resources and outputs, never their values                              |
| `branchd tfstate versions <state>`          | Lists the versions, newest first                                                         |
| `eval "$(branchd tfstate env <state>)"`     | Sets the `TF_HTTP_*` variables, a fresh token included, for an empty `backend "http" {}` |
| `branchd tfstate backend <state>`           | Prints the backend block, or with `--remote <name>` a `terraform_remote_state` block     |
| `branchd tfstate pull <state>`              | Downloads a version's state file (it contains secrets)                                   |
| `branchd tfstate unlock <state>`            | Releases a held lock                                                                     |
| `branchd tfstate restore <state> <version>` | Makes an earlier version current again                                                   |
| `branchd tfstate grant <repo> --to <who>`   | Lets another repository's jobs reach the states, at `--level outputs`, `read` or `write` |

## Versions, restore and delete

The **Terraform** tab of a repository lists its states: each state's
current version, serial, resource count, who wrote it and when, and its
lock if one is held. A state's page shows:

- **its versions**, newest first, with the Terraform version and the caller
  that wrote each one: a person, an agent or a pipeline run;
- **a version's resources**, by module and type, and its outputs, with
  sensitive ones marked. Attribute and output values are never shown;
- **what changed since the version before**: resources added and removed,
  and instance counts that changed.

At the maintain level you can also:

- **download** a version's state file. It contains every secret the state
  holds;
- **restore** an earlier version. Its contents are written as a new version,
  so the history keeps every write. The next plan compares your
  infrastructure with the restored state, so it may plan to create again
  what was made after that version. Restore is refused while the state is
  locked;
- **delete** an earlier version. The newest cannot be deleted;
- **delete** the state with every version. Terraform then finds no state at
  that URL, and plans every resource as new.

Deleting cannot be undone.

## Access

| To                                           | Needs                                                            |
| -------------------------------------------- | ---------------------------------------------------------------- |
| Read a state (`terraform plan`, the console) | Write access on the repository, and `forge:terraform-state:read` |
| Write and lock it (`terraform apply`)        | Write access, and `forge:terraform-state:edit`                   |
| Download, restore, force-unlock or delete    | The maintain level, and `forge:terraform-state:admin`            |

A personal API key at the write level holds the first two scopes, and one at
the maintain level holds all three. See [Scopes](https://docs.branchd.run/branchd/access/scopes).

Source: https://docs.branchd.run/branchd/terraform-state
