1. Answers
  2. Managing PostgreSQL Schemas with Pulumi

How do I create and manage schemas in a PostgreSQL database using Pulumi?

In this guide, we will demonstrate how to create and manage schemas in a PostgreSQL database using Pulumi. We will define a PostgreSQL database and a schema within that database. This example will use the Pulumi PostgreSQL provider to manage these resources.

Key Points

  • Define a PostgreSQL database.
  • Create a schema within the PostgreSQL database.
  • Manage the schema properties such as owner and policies.

Here is the complete Pulumi program written in TypeScript:

import * as pulumi from "@pulumi/pulumi";
import * as postgresql from "@pulumi/postgresql";

// Define a PostgreSQL database
const database = new postgresql.Database("mydatabase", {
    name: "mydatabase",
    owner: "db_owner",
    lcCtype: "en_US.UTF-8",
    encoding: "UTF8",
    template: "template0",
    lcCollate: "en_US.UTF-8",
    isTemplate: false,
    tablespaceName: "pg_default",
    connectionLimit: -1,
    allowConnections: true,
});

// Create a schema in the PostgreSQL database
const schema = new postgresql.Schema("myschema", {
    name: "myschema",
    owner: "schema_owner",
    database: database.name,
    ifNotExists: true,
    dropCascade: false,
});

// Export the database and schema names
export const databaseName = database.name;
export const schemaName = schema.name;

Summary

In this example, we created a PostgreSQL database named mydatabase and a schema named myschema within that database using Pulumi. We defined the properties for both the database and the schema, including the owner and other settings. This approach allows you to manage PostgreSQL schemas declaratively using Pulumi’s infrastructure as code capabilities.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up