Pulumi PostgreSQL

3.16.3 · active · verified Thu Apr 16

The `pulumi-postgresql` package provides a Pulumi provider for creating and managing PostgreSQL cloud resources. It allows users to define PostgreSQL databases, roles, schemas, and other configurations as infrastructure-as-code using Python and other supported languages. The provider is derived from the Terraform PostgreSQL provider and receives frequent updates, often alongside its upstream dependencies.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a new PostgreSQL database and a new role (user) using the `pulumi-postgresql` provider. It assumes PostgreSQL connection details are configured via environment variables (`PGHOST`, `PGUSER`, `PGPASSWORD`, `PGDATABASE`, `PGPORT`, `PGSSLMODE`) or Pulumi configuration. For local development, `PGSSLMODE` is often set to `disable` to avoid SSL connection errors. Always manage sensitive data like passwords using Pulumi secrets.

import pulumi
import pulumi_postgresql as postgresql
import os

# Configure PostgreSQL provider using environment variables for sensitive data
# Alternatively, use `pulumi config set postgresql:host <value>` etc.
# For passwords, use `pulumi config set --secret postgresql:password <value>`

pg_host = os.environ.get('PGHOST', 'localhost')
pg_user = os.environ.get('PGUSER', 'postgres')
pg_password = os.environ.get('PGPASSWORD', 'password')
pg_database = os.environ.get('PGDATABASE', 'postgres') # Database for initial connection
pg_port = os.environ.get('PGPORT', '5432')
pg_sslmode = os.environ.get('PGSSLMODE', 'disable') # Often 'disable' for local dev, 'require' for production

# The provider needs to be explicitly configured if not using default environment variables or pulumi config.
# For this example, we're relying on environment variables or `pulumi config`.
# If you need to explicitly create a provider instance:
# pg_provider = postgresql.Provider("pg-provider",
#     host=pg_host,
#     username=pg_user,
#     password=pg_password,
#     database=pg_database,
#     port=pg_port,
#     sslmode=pg_sslmode
# )

# Create a new PostgreSQL database
new_db = postgresql.Database("my-new-database",
    name="mydatabase",
    opts=pulumi.ResourceOptions(delete_before_replace=True) # Optional: ensures clean replacement if name changes
)

# Create a new PostgreSQL role (user)
new_role = postgresql.Role("my-app-role",
    name="app_user",
    login=True,
    password="strong_password_here", # In production, this should be a secret!
    opts=pulumi.ResourceOptions(delete_before_replace=True) # Optional
)

# Export the database name and role name
pulumi.export('database_name', new_db.name)
pulumi.export('role_name', new_role.name)

view raw JSON →