Source

Implementation

Provisioner Type

Resource Type

Flavor

Tool

postgres-instance

Provisions a dedicated PostgreSQL instance.

type: postgres-instance
expected_outputs:
  - host
  - port
  - username
  - password

provisioners.yaml (view on GitHub) :

- uri: template://default-provisioners/postgres-instance
 
  type: postgres-instance
  description: Provisions a dedicated PostgreSQL instance.
  # Init template has the random service name and password if needed later
  init: |
    randomServiceName: pg-{{ randAlphaNum 6 }}
    randomDatabase: db-{{ randAlpha 8 }}
    randomUsername: user-{{ randAlpha 8 }}
    randomPassword: {{ randAlphaNum 16 | quote }}
    sk: default-provisioners-postgres-instance
    publishPort: {{ dig "annotations" "compose.score.dev/publish-port" "0" .Metadata | quote }}    
  # The state for each database resource is a unique db name and credentials
  state: |
    serviceName: {{ dig "serviceName" .Init.randomServiceName .State | quote }}
    database: "postgres"
    username: "postgres"
    password: {{ dig "password" .Init.randomPassword .State | quote }}    
  # The outputs are the core database outputs. We output both name and database for broader compatibility.
  outputs: |
    host: {{ .State.serviceName }}
    port: 5432
    username: postgres
    password: {{ .State.password }}    
  # Ensure the data volume exists
  volumes: |
    {{ .State.serviceName }}-data:
      driver: local    
  # Create 2 services, the first is the database itself, the second is the init container which runs the scripts
  services: |
    {{ .State.serviceName }}:
      image: mirror.gcr.io/postgres:17-alpine
      restart: always
      environment:
        POSTGRES_USER: postgres
        POSTGRES_PASSWORD: {{ .State.password | quote }}
      {{ if ne .Init.publishPort "0" }}
      ports:
      - target: 5432
        published: {{ .Init.publishPort }}
      {{ end }}
      volumes:
      - type: volume
        source: {{ .State.serviceName }}-data
        target: /var/lib/postgresql/data
      healthcheck:
        test: ["CMD", "pg_isready", "-U", "postgres"]
          
  info_logs: |
    - "{{.Uid}}: To connect to postgres, enter password {{ .State.password | squote }} at: \"docker run -it --network {{ .ComposeProjectName }}_default --rm postgres:17-alpine psql -h {{ .State.serviceName }} -U {{ .State.username }} --dbname {{ .State.database }}\""
    {{ if ne .Init.publishPort "0" }}
    - "{{.Uid}}: Or connect your postgres client to \"postgres://{{ .State.username }}:{{ .State.password }}@localhost:{{ .Init.publishPort }}/{{ .State.database }}\""
    {{ end }}    
  expected_outputs:
    - host
    - port
    - username
    - password