pg

Stores the state in a Postgres database version 10 or newer.

This backend supports state locking.

Example Configuration

terraform {
  backend "pg" {
    conn_str = "postgres://user:pass@db.example.com/terraform_backend"
  }
}

Before initializing the backend with terraform init, the database must already exist:

createdb terraform_backend

This createdb command is found in Postgres client applications which are installed along with the database server.

Using environment variables

We recommend using environment variables to configure the pg backend in order not to have sensitive credentials written to disk and committed to source control.

The pg backend supports the standard libpq environment variables.

The backend can be configured either by giving the whole configuration as an environment variable:

terraform {
  backend "pg" {}
}
$ export PG_CONN_STR=postgres://user:pass@db.example.com/terraform_backend
$ terraform init

or just the sensitive parameters:

terraform {
  backend "pg" {
    conn_str = "postgres://db.example.com/terraform_backend"
  }
}
$ export PGUSER=user
$ read -s PGPASSWORD
$ export PGPASSWORD
$ terraform init

Data Source Configuration

To make use of the pg remote state in another configuration, use the terraform_remote_state data source.

data "terraform_remote_state" "network" {
  backend = "pg"
  config = {
    conn_str = "postgres://localhost/terraform_backend"
  }
}

Configuration Variables

The following configuration options or environment variables are supported:

Technical Design

This backend creates one table states in the automatically-managed Postgres schema configured by the schema_name variable.

The table is keyed by the workspace name. If workspaces are not in use, the name default is used.

Locking is supported using Postgres advisory locks. force-unlock is not supported, because these database-native locks will automatically unlock when the session is aborted or the connection fails. To see outstanding locks in a Postgres server, use the pg_locks system view.

The states table contains: