Skip to content

Latest commit

 

History

History
350 lines (275 loc) · 10.8 KB

File metadata and controls

350 lines (275 loc) · 10.8 KB
title Pulumi
icon Blocks
tag TypeScript
description Manage PgBeam projects, databases, replicas, custom domains, cache rules, spend limits, agent credentials, policy profiles, webhook endpoints, and self host enrollments as infrastructure using Pulumi and the @pgbeam/pulumi package.

Manage your PgBeam infrastructure as code with Pulumi. The @pgbeam/pulumi package provides native Pulumi resources for projects, databases, replicas, custom domains, cache rules, spend limits, agent credentials, policy profiles, webhook endpoints, and self host enrollments.

Setup

Install the package

<Tabs items={["npm", "pnpm", "yarn"]}> bash npm install @pgbeam/pulumi @pulumi/pulumi bash pnpm add @pgbeam/pulumi @pulumi/pulumi bash yarn add @pgbeam/pulumi @pulumi/pulumi

Configure credentials

Set your PgBeam API key via Pulumi config or environment variable:

<Tabs items={["Pulumi config", "Environment variable", "Programmatic"]}>

pulumi config set pgbeam:apiKey --secret pgb_your_api_key
```bash title=".env" PGBEAM_API_KEY=pgb_your_api_key ``` ```ts title="index.ts" import * as pgbeam from "@pgbeam/pulumi";

pgbeam.configure({ apiKey: "pgb_your_api_key" });

</Tab>
</Tabs>

</Step>
<Step>

### Create a project

```ts title="index.ts"
import * as pgbeam from "@pgbeam/pulumi";
import * as pulumi from "@pulumi/pulumi";

const config = new pulumi.Config();

const project = new pgbeam.Project("my-app", {
  orgId: config.require("orgId"),
  name: "my-app",
  database: {
    host: "my-rds.us-east-1.rds.amazonaws.com",
    port: 5432,
    name: "mydb",
    username: "pgbeam",
    password: config.requireSecret("dbPassword"),
  },
});

export const proxyHost = project.proxyHost;

Deploy

pulumi up

Pulumi creates the PgBeam project and its primary database atomically. The proxyHost output gives you the PgBeam proxy endpoint to use in your application connection string.

Resources

**Policy profiles are not yet managed as code.** Resources that reference a policy (`policy_profile_id` on an agent credential, `default_policy_profile_id` on a project) expect the ID of a profile created out of band with `pgbeam policies create` or the dashboard. There is no policy-profile resource in the providers yet, so the policy itself, the most security-sensitive primitive, lives outside your reviewed IaC flow and is invisible to drift detection. Track this before gating full adoption on policy-as-code.

Project

Manages a PgBeam project with a primary database.

const res = new pgbeam.Project("example", {
  orgId: "org_abc123",
  name: "my-app",
  description: "Production database proxy",
  tags: ["production", "us-east-1"],
  allowedCidrs: [
    { cidr: "10.0.0.0/8", label: "VPC" },
    { cidr: "2001:db8::/32", label: "IPv6 range" },
  ],
  defaultPolicyProfileId: "pol_01h455vb4pex5vsknk084sn02q",
  residency: "eu",
  agentsDisabled: false,
  status: "active",
});

Outputs: proxyHost, queriesPerSecond, burstSize, maxConnections, databaseCount, activeConnections, createdAt, updatedAt, primaryDatabaseId

Database

Manages an upstream database connection within a PgBeam project.

const res = new pgbeam.Database("example", {
  projectId: "prj_01h455vb4pex5vsknk084sn02q",
  host: "db.example.com",
  port: 5432,
  name: "mydb",
  username: "pgbeam",
  sslMode: "require",
  role: "primary",
  poolRegion: "us-east-1",
  queryTimeoutMs: 0,
  autoReadRouting: false,
  cacheConfig: {
    enabled: true,
    ttlSeconds: 60,
    maxEntries: 10000,
    swrSeconds: 30,
  },
  poolConfig: {
    poolSize: 20,
    minPoolSize: 5,
    poolMode: "transaction",
    maxActive: 200,
  },
  password: secret.value,
});

Outputs: connectionString, createdAt, updatedAt

Replica

Manages a read replica for a PgBeam database.

Replicas are immutable; any property change triggers replacement.

const res = new pgbeam.Replica("example", {
  databaseId: "db_01h455vb4pex5vsknk084sn02q",
  host: "replica.db.example.com",
  port: 5432,
  sslMode: "require",
});

Outputs: createdAt, updatedAt

CustomDomain

Manages a custom domain for a PgBeam project.

CustomDomains are immutable; any property change triggers replacement.

const res = new pgbeam.CustomDomain("example", {
  projectId: "prj_01h455vb4pex5vsknk084sn02q",
  domain: "db.example.com",
});

Outputs: verified, verifiedAt, tlsCertExpiry, dnsVerificationToken, dnsInstructions, createdAt, updatedAt

CacheRule

Manages a per-query cache rule. Deletion disables caching (soft-delete).

const res = new pgbeam.CacheRule("example", {
  projectId: "prj_01h455vb4pex5vsknk084sn02q",
  databaseId: "db_01h455vb4pex5vsknk084sn02q",
  queryHash: "a1b2c3d4e5f60718",
  cacheEnabled: true,
  cacheTtlSeconds: 300,
  cacheSwrSeconds: 60,
});

Outputs: queryHash, normalizedSql, queryType, callCount, avgLatencyMs, p95LatencyMs, avgResponseBytes, stabilityRate, recommendation, firstSeenAt, lastSeenAt

SpendLimit

Manages the monthly spend limit for an organization.

const res = new pgbeam.SpendLimit("example", {
  orgId: "org_abc123",
  spendLimit: 500,
});

Outputs: orgId, plan, billingProvider, subscriptionStatus, currentPeriodEnd, enabled, customPricing, spendCapped, spendCappedAt, limits, createdAt, updatedAt

AgentCredential

Manages a scoped agent credential (a PgBeam-issued Postgres login plus a hosted MCP token) for an AI agent. The connection string and MCP token are one-time secrets returned only at creation and exposed as sensitive computed outputs; they cannot be retrieved again. To rotate the secrets, taint/replace the resource (or use the rotate endpoint out of band).

const res = new pgbeam.AgentCredential("example", {
  projectId: "prj_01h455vb4pex5vsknk084sn02q",
  policyProfileId: "pol_01h455vb4pex5vsknk084sn02q",
  name: "Claude Code (analytics)",
  status: "active",
  principalType: "agent",
  expiresAt: "...",
});

Outputs: pgUsername, authMethod, lastUsedAt, createdAt, updatedAt, connectionString, mcpUrl, mcpToken

PolicyProfile

Manages a policy profile: a named bundle of agent-gateway enforcement rules (access mode, table allow/deny lists, statement-kind rules, PII masking rules, per-relation row filters, query/egress budgets, write mode, approvals, and migration safety) attached to agent credentials and enforced in the PG wire protocol. Nested-list fields (masking_rules, row_filters) and the nested statement_rules object are expressed as structured config.

const res = new pgbeam.PolicyProfile("example", {
  projectId: "prj_01h455vb4pex5vsknk084sn02q",
  name: "Read-only analytics",
  accessMode: "read_only",
  statementRules: {
    allow: ["..."],
    deny: ["..."],
  },
  tableAllowlist: ["..."],
  tableDenylist: ["..."],
  maskingRules: ["..."],
  budgetQueriesPerHour: 0,
  budgetQueriesPerDay: 0,
  maxRows: 0,
  statementTimeoutMs: 0,
  rowFilters: ["..."],
  writeMode: "normal",
  approvalMode: "off",
  approvalAutoMaxRows: 0,
  approvalTimeoutSeconds: 300,
  migrationSafety: "off",
  egressBytesPerDay: 0,
  maxAffectedRows: 0,
});

Outputs: createdAt, updatedAt

WebhookEndpoint

Manages a webhook endpoint that receives project audit and anomaly event deliveries. The signing secret is write-only and never returned by the API.

const res = new pgbeam.WebhookEndpoint("example", {
  projectId: "...",
  url: "https://example.com/hooks/pgbeam",
  format: "json",
  eventTypes: ["..."],
  enabled: true,
  description: "...",
  secret: secret.value,
});

Outputs: createdAt, updatedAt

SelfHostEnrollment

Manages a self-host (BYOC) enrollment: a token a self-hosted proxy uses to authenticate to the control plane's config/audit stream. The token is a one-time secret returned only at creation and exposed as a sensitive computed output; it cannot be retrieved again. To rotate the token, replace the resource. Deletion revokes the enrollment.

SelfHostEnrollments are immutable; any property change triggers replacement.

const res = new pgbeam.SelfHostEnrollment("example", {
  orgId: "org_abc123",
  regionLabel: "customer-vpc-us-east",
  description: "prod cluster",
  expiresAt: "...",
});

Outputs: createdBy, createdAt, lastSeenAt, revokedAt, token

Configuration

Setting Source Description
pgbeam:apiKey Pulumi config API key (recommended: use --secret)
pgbeam:baseUrl Pulumi config API base URL (default: https://api.pgbeam.com)
PGBEAM_API_KEY Environment Fallback API key
PGBEAM_API_URL Environment Fallback base URL

Config resolution order: configure() call > Pulumi stack config > environment variables.

Replacement vs update

Some property changes trigger resource replacement (delete + create) rather than in-place updates:

Resource Replacement triggers
Project orgId, cloud, selfHosted
Database projectId
Replica Any property change (immutable)
CustomDomain Any property change (immutable)
CacheRule projectId, databaseId, queryHash
SpendLimit orgId
AgentCredential projectId, policyProfileId, name, principalType, expiresAt
PolicyProfile projectId
WebhookEndpoint projectId
SelfHostEnrollment Any property change (immutable)

Further reading