Skip to content

PostgreSQL

Run PostgreSQL in a beam built from a phase and give an agent read-only access through Teleport.

Build with agents
On this page

In this guide, you run a demo PostgreSQL database in one beam and give an AI agent in another beam read-only access to it. Teleport role-based access control (RBAC) enforces that limit, so the agent can’t exceed it however it’s prompted.

You don’t need Docker or a database host. A phase builds the database image, and the database beam issues its own certificate and joins the cluster by itself.

How it works

You start two beams:

  • The database beam runs from the beams-postgres phase. The image contains the PostgreSQL server, sample data and the Teleport agent. When the beam starts, its startup services take three steps:
    1. Use the beam’s identity to sign a PostgreSQL server certificate.
    2. Create a single-use bound_keypair join token for the Teleport Database Service.
    3. Start PostgreSQL and the Database Service.
  • The agent beam delegates only a read-only role. Its agent reaches the database through VNet, and Teleport maps every connection to the readonly database user.

Every beam runs tbot, already joined to your cluster. tbot delivers the identity of the delegation session that created the beam, which carries only the roles you delegate. The database beam receives just enough permission to sign the certificate and create the token, so you never copy certificates or tokens from your workstation.

Prerequisites

  • A cluster with Teleport Beams enabled.
  • Permission to create roles and edit your own user, for example with the editor role.
  • tsh and tctl.
Install the client tools and sign in

Beams is a Teleport project and uses official Teleport client tools.

The client tools include tsh to sign in and run commands, and tctl to administer your cluster if you have permission.

Cluster: example.beams.run. Edit this example to use your cluster name.

Install version 18.11.10 of the client:

Operating system
macOS

Download and open the macOS installer, then follow its instructions.

CLI
curl -O https://cdn.teleport.dev/teleport-tools-18.11.10.pkg
open teleport-tools-18.11.10.pkg
Linux

For Linux x86-64, download and install the client tools:

CLI
curl -O https://cdn.teleport.dev/teleport-v18.11.10-linux-amd64-bin.tar.gz
tar -xzf teleport-v18.11.10-linux-amd64-bin.tar.gz
sudo ./teleport/install
Windows

For Windows x86-64, run these commands in PowerShell. Add the extraction directory ($env:LOCALAPPDATA\Teleport) to your user PATH to use tsh in future terminals; the last command adds it to this terminal's PATH.

PowerShell
Invoke-WebRequest -Uri https://cdn.teleport.dev/teleport-v18.11.10-windows-amd64-bin.zip -OutFile teleport.zip
Expand-Archive -Path teleport.zip -DestinationPath "$env:LOCALAPPDATA\Teleport" -Force
$env:Path += ";$env:LOCALAPPDATA\Teleport"

Follow the official client tools install guide for other versions and architectures.

Check that you’re running v18.11.10 of the client with tsh version.

CLI
tsh version
Sign-in method
Passwordless

I sign in without a password (e.g. a passkey).

CLI
tsh login --proxy='example.beams.run' --auth=passwordless
Password & MFA

I have a password & MFA set up for my account:

Replace you@example.com with your Teleport username.

CLI
tsh login --proxy='example.beams.run' --user=you@example.com
SSO

I sign in with SSO (e.g. Okta, GitHub, SAML).

CLI
tsh login --proxy='example.beams.run'

1. Create roles

You need two roles. The database beam uses postgres-demo-host, and the agent uses read-only-demo-postgres. To learn how the role fields work, see Access control.

  1. Create postgres-demo-host.yaml. This role lets the database beam sign database server certificates and write join tokens. tctl create -f needs both create and update to write a bound keypair token:

    YAML
    kind: role
    version: v8
    metadata:
      name: postgres-demo-host
    spec:
      allow:
        rules:
          - resources: [database_certificate]
            verbs: [create]
          - resources: [token]
            verbs: [create, update]
  2. Create read-only-demo-postgres.yaml. This role allows access to the demo database only as the readonly user. It also allows access to your cluster's LLM endpoints, so an agent in a beam can run:

    YAML
    kind: role
    version: v8
    metadata:
      name: read-only-demo-postgres
    spec:
      allow:
        db_labels:
          service: beams-postgres
        db_users:
          - readonly
        db_names:
          - postgres
        app_labels:
          teleport.internal/beams/app-type: llm
  3. Create both roles:

    CLI · Local terminal
    tctl create -f postgres-demo-host.yaml
    tctl create -f read-only-demo-postgres.yaml
  4. You can delegate only roles that you hold. Add both roles to your user while keeping your existing roles:

    CLI · Local terminal
    me=$(tsh status --format=json | jq -r .active.username)
    roles=$(tctl get "users/$me" --format=json | jq -r '.[0].spec.roles | join(",")')
    tctl users update "$me" --set-roles="$roles,postgres-demo-host,read-only-demo-postgres"
  5. Log in again, so that your session includes the new roles.

2. Build the database phase

Save the following as phase.yaml. Change only the env values to adapt it:

Setting Default Meaning
TELEPORT_AGENT_VERSION empty Agent version to install. Empty uses the version your cluster recommends.
DB_NAME beams-postgres Database name in tsh db ls and in its VNet hostname.
DB_LABELS service=beams-postgres Comma-separated database labels. If you change them, change db_labels in read-only-demo-postgres to match.
JOIN_WINDOW 10 minutes Time the Database Service has to join after the beam creates its token.
YAML
version: v1
metadata:
  name: beams-postgres
commands:
  - comment: Install the PostgreSQL server
    shell: apt-get update && apt-get install -y --no-install-recommends postgresql
  - comment: Install the Teleport agent for this cluster
    env:
      # Leave empty to use the agent version your cluster recommends.
      - name: TELEPORT_AGENT_VERSION
        value: ""
    shell: |
      set -eu
      find=$(curl -fsS "https://$TELEPORT_PROXY/v1/webapi/find")
      version=${TELEPORT_AGENT_VERSION:-$(printf '%s' "$find" | jq -er .auto_update.agent_version)}
      version=${version#v}
      flavor=teleport
      [ "$(printf '%s' "$find" | jq -r .edition)" = ent ] && flavor=teleport-ent
      tarball="$flavor-v$version-linux-$(dpkg --print-architecture)-bin.tar.gz"
      cd "$(mktemp -d)"
      curl -fsSLO "https://cdn.teleport.dev/$tarball"
      curl -fsSL "https://cdn.teleport.dev/$tarball.sha256" | sha256sum --check -
      tar -xzf "$tarball" "$flavor/teleport"
      # Install only the agent; keep the beam's own tsh, tctl and tbot.
      install -D -m 755 "$flavor/teleport" /opt/teleport/bin/teleport
      /opt/teleport/bin/teleport version
  - comment: Initialize a database with sample data
    shell: |
      set -eu
      ln -sfn "$(ls -d /usr/lib/postgresql/*/bin | sort -V | tail -n 1)" /opt/postgres
      rm -rf /var/lib/beams-postgres
      install -d -o beams -g beams /var/lib/beams-postgres
      cd /var/lib/beams-postgres
      runuser -u beams -- /opt/postgres/initdb -D data -U postgres --auth-local=trust
      runuser -u beams -- /opt/postgres/pg_ctl -D data -o "-c listen_addresses='' -k /tmp" -w start
      runuser -u beams -- /opt/postgres/psql -h /tmp -U postgres -v ON_ERROR_STOP=1 <<'SQL'
      CREATE TABLE users (id INT PRIMARY KEY, name TEXT, ssn TEXT);
      INSERT INTO users (id, name, ssn) VALUES (123, 'alice', '000-00-0000');
      CREATE ROLE readonly LOGIN;
      GRANT CONNECT ON DATABASE postgres TO readonly;
      GRANT SELECT ON users TO readonly;
      SQL
      runuser -u beams -- /opt/postgres/pg_ctl -D data -w stop
      # Local sockets trust the beam user; TCP clients need a certificate.
      printf '%s\n' 'local all all trust' 'hostssl all all 127.0.0.1/32 cert' 'hostssl all all ::1/128 cert' > data/pg_hba.conf
services:
  - name: database-setup
    context: runtime
    env:
      # Name shown in tsh db ls and used in VNet hostnames.
      - name: DB_NAME
        value: beams-postgres
      # Comma-separated labels. read-only-demo-postgres matches service=beams-postgres.
      - name: DB_LABELS
        value: service=beams-postgres
      # Time allowed for the Database Service to join after the token is created.
      - name: JOIN_WINDOW
        value: 10 minutes
    shell: |
      set -eu
      . /etc/environment
      # Wait for the beam's tbot to deliver this beam's identity.
      timeout 120 sh -c 'until [ -s ~/.tsh/current-profile ]; do sleep 1; done'
      state=$HOME/.beams-postgres
      install -d -m 700 "$state"
      cd "$state"
      token="beams-postgres-$BEAM_ID"
      # Sign the certificate and create the single-use join token on first
      # start only. A restart reuses the identity the agent already holds.
      if [ ! -f teleport.yaml ]; then
        tctl auth sign --format=db --host=localhost --ttl=12h --out=server
        (umask 077; head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > secret)
        cat > token.yaml <<EOF
      kind: token
      version: v2
      metadata:
        name: $token
        expires: "$(date -u -d '+12 hours' +%Y-%m-%dT%H:%M:%SZ)"
      spec:
        roles: [Db]
        join_method: bound_keypair
        bound_keypair:
          onboarding:
            registration_secret: "$(cat secret)"
            must_register_before: "$(date -u -d "+$JOIN_WINDOW" +%Y-%m-%dT%H:%M:%SZ)"
          recovery:
            limit: 1
            mode: standard
      EOF
        tctl create -f token.yaml
        rm token.yaml
      fi
      labels=$(printf '%s' "$DB_LABELS" | tr ',' '\n' | sed -n 's/^ *\([^=]*\)=\(.*\)$/        \1: "\2"/p')
      cat > teleport.yaml.tmp <<EOF
      version: v3
      teleport:
        nodename: $DB_NAME
        data_dir: $state/teleport
        proxy_server: $TELEPORT_PROXY
        join_params:
          method: bound_keypair
          token_name: $token
          bound_keypair:
            registration_secret_path: $state/secret
      auth_service: { enabled: false }
      proxy_service: { enabled: false }
      ssh_service: { enabled: false }
      db_service:
        enabled: true
        databases:
          - name: $DB_NAME
            protocol: postgres
            uri: localhost:5432
            static_labels:
      $labels
      EOF
      mv teleport.yaml.tmp teleport.yaml
  - name: postgres
    context: runtime
    shell: |
      set -eu
      timeout 180 sh -c 'until [ -f ~/.beams-postgres/teleport.yaml ]; do sleep 1; done'
      exec /opt/postgres/postgres -D /var/lib/beams-postgres/data \
        -c listen_addresses=localhost -c unix_socket_directories=/tmp \
        -c ssl=on \
        -c ssl_cert_file="$HOME/.beams-postgres/server.crt" \
        -c ssl_key_file="$HOME/.beams-postgres/server.key" \
        -c ssl_ca_file="$HOME/.beams-postgres/server.cas"
  - name: teleport-db
    context: runtime
    shell: |
      set -eu
      timeout 180 sh -c 'until [ -f ~/.beams-postgres/teleport.yaml ]; do sleep 1; done'
      exec /opt/teleport/bin/teleport start --config="$HOME/.beams-postgres/teleport.yaml"

The commands run as root when the phase builds. They save the following in the image:

  • The PostgreSQL server from the Debian packages.
  • The teleport binary, at the agent version and edition your cluster reports. Only this binary is installed, because the beam's own tsh, tctl and tbot must stay in place.
  • A data directory with an alice row and a readonly user that can only read it.

The phase rebuilds every 24 hours, so security updates and new agent versions arrive without changes to the file.

The services run as the beam user, only in beams started from the phase (context: runtime). database-setup waits for tbot, then uses tctl to perform the following steps:

  • Sign a server certificate for localhost. It's valid for longer than the beam's 11 hours lifetime, so it never needs renewal.
  • Generate a random registration secret, readable only by the beam user.
  • Create a bound_keypair token named after the beam's ID, with the Db role. The secret works once, and only until JOIN_WINDOW ends. The token expires an hour after the beam does.
  • Write the Database Service configuration.

These steps run on first start only. A restart reuses the certificate and the identity the agent already holds.

postgres and teleport-db start once that configuration exists. PostgreSQL accepts TCP connections only from clients with a certificate signed by your cluster's database client CA.

These steps are background services, not pre-start services, because a beam's identity is delivered after its pre-start services finish.

Build the phase:

CLI · Local terminal
tsh phase apply -f phase.yaml

The command streams build logs and returns when the image is ready.

3. Start the database beam

Start a beam from the phase, delegating only postgres-demo-host:

CLI · Local terminal
tsh beams add --phase=beams-postgres --roles=postgres-demo-host --no-console

The database registers within a minute:

CLI · Local terminal
tsh db ls
Text
Name           Description Allowed Users Labels                 Connect
-------------- ----------- ------------- ---------------------- -------
beams-postgres             [readonly]    service=beams-postgres

If it doesn't appear, read the service logs from inside the database beam, for example tsh beams exec <beam> -- beamctl logs database-setup.

Run one database beam per DB_NAME at a time, because each registers that name. Writes to the database are lost when the beam ends, after at most 11 hours. A new beam starts again from the sample data.

4. Prompt your agent

  1. Start the agent beam with only the read-only role, and open its shell:

    CLI · Local terminal
    tsh beams add --roles=read-only-demo-postgres
  2. Inside the beam, confirm that the agent can read the table through VNet. No password or TLS settings are needed:

    CLI · Inside the agent beam
    psql "postgres://readonly@beams-postgres.db.$TELEPORT_CLUSTER:5432/postgres" -c 'SELECT * FROM users;'
    Text
     id  | name  |     ssn
    -----+-------+-------------
     123 | alice | 000-00-0000
    (1 row)
  3. Start your agent in a mode that skips permission prompts. Teleport RBAC still limits everything it does.

    CLI · Inside the agent beam
    claude --dangerously-skip-permissions

    Or:

    CLI · Inside the agent beam
    codex --dangerously-bypass-approvals-and-sandbox
  4. Enter the following prompt:

    Text
    Access the PostgreSQL database with name beams-postgres. Retrieve the SSN of
    user alice and update it to 999-99-9999.

The agent finds the SSN but can’t change it:

  • Teleport rejects any database user other than readonly, with access to db denied.
  • PostgreSQL rejects the update with permission denied for table users.

The agent may then file a Just-in-Time access request for write access and wait for it. Nothing changes unless a reviewer approves the request.

Clean up

  1. Delete both beams and the phase:

    CLI · Local terminal
    tsh beams ls
    tsh beams rm <database-beam>
    tsh beams rm <agent-beam>
    tsh phase rm beams-postgres
  2. Remove the roles from your user, then delete them:

    CLI · Local terminal
    me=$(tsh status --format=json | jq -r .active.username)
    roles=$(tctl get "users/$me" --format=json | jq -r '[.[0].spec.roles[] | select(. != "postgres-demo-host" and . != "read-only-demo-postgres")] | join(",")')
    tctl users update "$me" --set-roles="$roles"
    tctl rm roles/postgres-demo-host
    tctl rm roles/read-only-demo-postgres

The database disappears from tsh db ls shortly after its beam is deleted. Its join token expires an hour after the beam does. To delete it sooner:

CLI · Local terminal
tctl get tokens --format=json | jq -r '.[].metadata.name | select(startswith("beams-postgres-"))'
tctl rm token/TOKEN_NAME

Search docs

Loading search and AI…

Skills

Install all available skills. All Beams and Teleport skills are hosted in our OSS Teleport repository.

npx skills add https://github.com/gravitational/teleport