Managing PostgreSQL roles and grants with Terraform in your own infrastructure
Many teams create PostgreSQL roles and grants by hand, in a psql session or a one-off script, so nobody can review who has access to what or rebuild the same setup in a second environment. The cyrilgdn Terraform PostgreSQL provider fixes that by describing databases, roles, schemas and grants as Terraform resources in version control. It is published on the Terraform registry and replaces the earlier hashicorp/terraform-provider-postgresql, which HashiCorp stopped hosting after it withdrew support for community providers. The provider works by connecting to a PostgreSQL server and issuing the statements needed to converge the server to the declared state.
The provider manages the objects it can name: databases, roles and their attributes, schemas, and the privileges granted on them. It does not manage what sits outside SQL, such as server configuration in postgresql.conf, the client authentication rules in pg_hba.conf, TLS certificates, backups, or the identity provider that decides which people should hold which roles. Those stay in their own tooling, and the access review that decides whether a grant is still justified stays with the people who own the data. Before you start, confirm in the provider documentation which privilege types and object kinds your version supports, because grant coverage varies between releases. The repository is the place to check, starting from the Terraform PostgreSQL provider repository.
The most important operational fact is that the provider needs a connection as a privileged role, typically one that can create roles and databases and grant privileges. Whatever account Terraform uses can change access across the whole cluster, so treat that credential as the most sensitive item in the pipeline. Decide early where it lives, who can read it, and whether it is rotated. Confirm with your security team that a dedicated, least-privileged administrative role, rather than the superuser, is acceptable for the objects in scope, and that the connection uses TLS and an authentication method your standards allow.
What you need before the first terraform apply
Four things must be in place before the provider can change anything: a reachable PostgreSQL server, a privileged role for the provider, a Terraform installation, and a state store you have decided on. Each one has a check that prevents a surprise on the first plan.
A reachable PostgreSQL server
The machine running Terraform must open a network connection to the PostgreSQL server on its port, and the server's pg_hba.conf must allow that client address with an authentication method the provider supports. Confirm TLS requirements up front, since a plan that works from a laptop may fail from a CI runner in a different network segment. Test the connection with the same credentials and host settings the provider will use.
A privileged administration role
The provider connects as a role that can create and alter other roles, databases and schemas, and grant privileges on them. Use a dedicated administration role rather than a DBA's personal superuser login, and limit where its credentials can be used. Confirm which privileges the chosen provider version needs by reading its documentation, because a role that is too narrow will fail mid-apply.
Provider and PostgreSQL version check
Pin the provider version in your configuration and confirm in the provider repository that it supports the PostgreSQL major versions you run. Check the PostgreSQL versioning policy for which majors are still supported, since a provider that works today may be pinned to a version nearing end of life. Record both versions so a later upgrade of either one can be reviewed as a change.
Provider repositoryA Terraform installation and runner
Install a Terraform version that your team standardizes on and run it from a controlled host or CI job, not from individual workstations. Pin the version in the repository so every plan and apply uses the same binary. Decide who may run apply against production databases, since the runner holds the administration credentials.
A state storage decision
Terraform state records every role and grant the configuration manages, and it can hold the passwords you pass in. Choose a backend with encryption at rest, access control and locking before the first apply, and decide who can read it. Moving state later is possible but adds risk, so settle this on day one.
How to configure the cyrilgdn provider step by step
This sequence takes a PostgreSQL cluster from an unmanaged state to one where roles, databases and grants are declared in Terraform, with a tested connection, a dedicated admin role and a clean plan against existing objects. Each step ends with a check so you know the previous step is safe to build on.
Pin the provider in required_providers
Declare the cyrilgdn PostgreSQL provider in the required_providers block of your root module, using the Terraform registry source and an explicit version constraint. Commit the generated dependency lock file so every operator and CI runner resolves the same provider build. Use the registry name rather than the earlier hashicorp provider name, because the cyrilgdn provider replaced it after HashiCorp stopped hosting community providers. Check: terraform init completes and the lock file records the provider with a checksum for each platform your team uses.
Create a dedicated Terraform admin role
Have a DBA create a login role used only by Terraform, with the privileges needed to create roles, databases and schemas and to manage grants, and no superuser attribute unless your environment requires it. Store its password in your secrets manager, not in the repository. Confirm the exact privileges your target objects need against the provider documentation in the project repository, because the minimum set depends on which resources you manage. Check: the role can log in from the Terraform runner host and cannot log in from application networks.
Configure the provider connection with TLS
Add a provider block that points at the primary server, reads the admin credentials from variables or your secrets backend, and requires TLS with certificate verification. Set the sslmode and CA certificate settings to match your server certificates. Keep the password out of plain state where possible by reviewing how your chosen backend stores sensitive values. Check: terraform plan connects without errors, and a deliberately wrong password fails with an authentication error, which confirms the credential is actually being used.
Create a test database and role
Declare one non-production database, one schema and one login role with a grant on that schema, using a naming prefix that makes test objects easy to recognize. Apply the change against a development or staging cluster only. Confirm with psql that the role can connect and use the schema but cannot access objects outside its grants. Check: the apply finishes, psql shows the expected privileges, and a second terraform plan reports no changes.
Inventory existing roles and objects
Before importing, list the roles, databases, schemas and grants that already exist, including service accounts and roles used by monitoring and replication tooling. Decide which of them Terraform will own and which stay outside code, and record that decision in the repository. Note that some built-in and system roles should not be managed by Terraform. Check: the inventory is reviewed by the DBA and the application owners, and each object has a named owner and a managed or unmanaged status.
Import existing objects into state
Write resource blocks for each object you chose to manage, then use terraform import with the provider's documented identifier format for each resource type. Import in small batches so that a mistake is easy to find and reverse. Keep the import commands in a reviewed change so the team can see which state entries were created and why. Check: each imported resource appears in state with the expected name and attributes, and nothing has been created or altered on the server.
Confirm a clean plan before applying changes
Run terraform plan after the imports and read it line by line. Any proposed change to an existing role, grant or owner means the code and the live cluster disagree, so correct the code to match reality or plan a deliberate change with the owner's approval. Do not apply until the plan shows no changes or only changes you can explain. Check: the plan reports no changes for imported objects, and the reviewer records that the output matches the inventory from the previous step.
Promote the workflow and schedule drift checks
Move the same code and provider version to production through your normal change process, with the admin credential supplied by the runner's secrets store. Schedule a scheduled plan job that fails when it detects drift, so changes made by hand on the server surface quickly. Pair the job with your periodic access review so the reviewers see both the code and any drift findings. Check: the scheduled plan runs on production state, reports no unexpected changes, and the failure notification reaches the team that owns database access.
How Terraform state handles PostgreSQL passwords
Terraform state must be treated as secret storage once roles are managed through the PostgreSQL provider, because a role's password set through the provider can be written into the state file in readable form. Anyone who can read the state can read the password, so the state backend needs the same controls you would apply to a password vault: encryption at rest and in transit, access limited to the pipeline and a small group of platform engineers, audit logging of reads and writes, and state locking so two applies cannot overwrite each other. Confirm in your own backend which of these it provides natively and which you must configure, and confirm who can read the state bucket, table or workspace, including backups and snapshots of it.
Avoid putting passwords in variable files or in code. Instead, pass them at run time from a secrets manager, using a dedicated provider or a secret-fetching step in the pipeline that exports the value as a sensitive input. Keep the secret out of plan output and logs, and mark the input as sensitive so Terraform masks it in the console. Decide early whether the database owns the password or a secrets manager does, because that choice determines whether a rotation is a Terraform change, a rotation job outside Terraform, or a value that Terraform should ignore after creation. Where roles are also issued dynamic credentials, keep those out of this state entirely.
Before relying on the provider for rotation, confirm how the version you pin behaves when a password input changes. Check whether an updated value produces an in-place ALTER ROLE on the next apply, whether it is re-sent on every plan, and whether the provider reads the current password back at all, since it generally cannot compare a stored hash with a plain value. Test this in a non-production database with a throwaway role, and record the provider version in your change process. The provider's repository documents its resource arguments and open issues, which is the place to confirm this behavior for your version.
How the Terraform runner, state and PostgreSQL fit together
The flow starts in the Git repository, where HCL code declaring databases, roles, schemas and grants is reviewed. A CI job or admin runner executes terraform plan and then terraform apply, connecting to PostgreSQL with an admin role that the provider uses to create and alter objects. The runner reads passwords from a secrets source rather than from code, and writes state to a backend that must be encrypted and locked. Check the trust boundary: the state store and the database should be reachable only from the runner, and anyone who can read state should be treated as able to read the passwords it holds.
Repository, runner, state and database, with the trust boundary around state and PostgreSQL.
Which PostgreSQL objects map to which Terraform resources
This table pairs each PostgreSQL object with the kind of Terraform resource that manages it, the input it needs and who should own that value. Use it to decide what lives in code, what stays in a secrets store and what belongs in a periodic access review. Confirm resource and argument names against the provider documentation for the version you pin.
| PostgreSQL object | Terraform resource (confirm in provider docs) | Inputs it needs | Owner of each value |
|---|---|---|---|
| Database | Database resource with owner and encoding settings | Database name, owning role, encoding and template choices | Code for names and owner, platform team for the server connection |
| Login role | Role resource with login enabled | Role name, connection limit, password reference, expiry if used | Password in the secrets store, name and attributes in code |
| Group role (no login) | Role resource with login disabled | Group name, attributes such as inheritance, member list | Code, with membership changes reviewed by the data owner |
| Role membership | Grant of role to role or user | Group role, member roles, admin option if used | Code, confirmed in access review each cycle |
| Schema | Schema resource | Schema name, owning role, database it lives in | Code for structure, application team for ownership decisions |
| Default privileges | Default privileges resource per owner role, object type and grantee | Owner role, schema, object type, privileges, grantee | Code, because a wrong default silently grants access to future tables |
| Object grants (tables, sequences, functions) | Grant resource covering existing objects | Database, schema, object type, privileges, grantee | Code, with reviewers checking privileges against the access model |
| Passwords and state file | Not a schema object; supplied as a variable to the role resource | Generated or injected secret value | Secrets store owns the value; restrict who can read the state file that may hold it |
How to detect drift between code and the live database
Drift appears when the live database no longer matches the Terraform configuration, usually because someone or something changed a role or grant by hand. The cards below cover where drift comes from, how a scheduled plan surfaces it, how to decide between reverting and codifying, and how to make out-of-band changes rare.
Manual grants and incident changes
Most drift starts with a manual GRANT or ALTER ROLE run during an incident, a support ticket or a quick fix that nobody wrote back into code. These changes are easy to make and easy to forget. Ask your team to list every break-glass path to the database and record which changes must be reconciled into the repository within a set window after the incident closes.
Objects created by applications
Applications and migration tools often create tables, sequences or schemas that the Terraform configuration does not know about. Ownership and default privileges can also shift when a deployment runs as a different role. Decide which objects belong to code and which belong to the application, and make the boundary explicit so that plan output stays meaningful.
Scheduled plan in CI
Run terraform plan on a schedule in CI against the production state, with no apply step. A non-empty plan means the live database differs from the code. Route the output to the team that owns the database, and treat repeated noise on the same resource as a signal that the configuration or the ownership boundary needs work.
Reading plan output for passwords
A plan that touches a role password may look like drift even when nothing changed, because the provider cannot read the current password back. Confirm how your provider version handles password attributes before you treat these lines as real changes. Keep this in mind when you review plans, so that a noisy password diff does not hide a genuine privilege change.
Revert or codify the change
When a plan shows a difference, decide whether the live state is wrong or the code is incomplete. Revert the database change when it was a mistake or exceeded its purpose. Codify it when the access is still needed, by changing the configuration, reviewing it and applying it. Record the decision and the reviewer so the access review has a trail.
Restricting admin role access
Drift is rare when few people can connect as the role that owns and manages Terraform-managed objects. Limit that role to the Terraform runner and a small set of break-glass users, require their use to be logged, and send connection logs to your review process. Pair these controls with periodic access reviews so that any change that bypasses code is caught quickly.
Provider repositoryPairing Terraform code with periodic access reviews
Code shows what access was intended, but it does not show whether a person or service still needs that access. A periodic access review closes that gap by asking a named owner to confirm each role, membership and grant against current need. Terraform makes the review practical because the Git history records who approved each change and when, while the live catalog shows what the database actually holds. Reviewers should compare the two at each cycle, since drift between them is exactly what a review is meant to catch. Before the first cycle, decide who owns each role, how often reviews run and which systems count as in scope.
Run each cycle from two sources. First, export the live state from the catalog, using queries against pg_roles, pg_auth_members and the information_schema privilege views, and compare it with what the Terraform configuration declares. Second, read the Git history for the roles under review to see who requested each grant and what justification was recorded in the merge request. A reviewer then marks each membership as kept, changed or removed. Any difference between code and catalog is treated as a finding, not silently overwritten, because it may mean someone granted access outside the pipeline. Confirm that your team's review query behaves the same on the PostgreSQL version you run, since catalog views can change between releases.
Removals should go through code, not through ad hoc REVOKE statements in a session. Delete the membership or grant from the configuration in a merge request, have a second person approve it, and let the pipeline apply it, so the removal is recorded like any other change. Keep the review record itself, meaning the export, the reviewer's decisions, the merge request links and the apply output, in storage that the team can retain and retrieve. This is evidence that a review took place and what it decided. Whether that evidence meets a specific audit requirement is a question for your assessor and certification body, and you should confirm their expectations for review frequency and sign-off before designing the cycle.
Common failures when applying PostgreSQL grants with Terraform
This table lists the failures teams most often hit when a Terraform PostgreSQL provider applies roles and grants, with the likely cause and fix for each. Read it before the first apply in a new environment, and confirm the exact behavior against the provider repository for the version you run.
| Failure | Likely cause | Fix |
|---|---|---|
| Connection refused or authentication failed | pg_hba.conf does not allow the machine running Terraform to connect as the admin role, or TLS settings do not match the server | Add a host-based rule for the runner's address and the admin role, match the TLS mode in the provider settings, then reload the configuration and test with psql first |
| Permission denied on an object | The admin role lacks rights on the database, schema or table it is asked to grant on, often because another role owns the object | Run the provider as a role that owns or can grant on the target objects, or add the admin role to the owning role, and keep ownership changes in the same plan |
| Perpetual diffs on grants | Default privileges or implicit owner grants are created outside Terraform, so the provider sees privileges it did not declare | Declare the default privileges in code, or import the existing grants, and confirm how the provider treats owner and public privileges in the provider repository |
| Perpetual diffs on ownership | Objects were created by a different role than the one declared as owner, so each plan proposes an ownership change | Set the owner explicitly on each object, or change the creating role in your deployment process so ownership matches the code |
| Password reported as changed on every plan | The password is not stored in state in the form the provider compares, or the password is hashed differently on each read, so the provider cannot match it | Use a hashed or SCRAM-encoded password input where the provider supports it, and check the provider's password handling notes before relying on plan output |
| State lock conflict | Two runs or a stale lock from a failed apply hold the state backend lock | Confirm no other run is active, then release the lock through the backend's own tooling; serialize applies through one pipeline |
| Passwords stored in plain text in state | The state file holds values the provider reads from the server or from input variables | Encrypt the state backend, restrict read access to it, and keep passwords out of version control |
Questions teams ask before managing PostgreSQL grants in Terraform
What drives the cost of managing PostgreSQL grants in Terraform?
The main drivers are how many databases, schemas, roles and grants exist today, how messy the current grant history is, and how the state and secrets will be designed. A cluster with a few databases and a handful of roles is a much smaller job than one where grants were granted by hand over many years and nobody knows who owns what. Review process also matters: if every change needs sign-off from a data owner, that time recurs with each request. Ask any partner for a written scope that lists the object counts, the state backend, the CI pipeline and the review workflow, because those items set the quote. Ask also which parts are one-time (import, design, first review) and which recur (ongoing changes, provider upgrades, access reviews).
How long does the initial import of existing roles and grants take?
The import time depends mainly on the number of objects that must be brought under code: databases, schemas, roles, memberships and default privileges. Each object needs to be read, matched to an owner, written as configuration and checked against the live cluster with a plan that shows no changes. Clusters with many years of ad hoc grants take longer because the team must decide which grants are still needed before codifying them. No duration is stated here. Ask for a timeline that breaks the import into object groups and names the environments (development, staging, production) that will be imported in sequence.
What must our team provide before the work starts?
Four things are needed before the Terraform code can run safely:
- A PostgreSQL administrative role with enough privilege to create and alter roles, databases and schemas, and to grant privileges on them. Confirm with your DBA which role will be used and how its password is stored.
- A remote state backend that supports locking and encryption, so two pipeline runs cannot write state at the same time.
- CI access to the repository, the state backend and the database network path, with the secrets needed to authenticate.
- A named owner for each role or group, who approves changes and confirms during access reviews that the access is still required.
Can an internal team manage PostgreSQL grants in Terraform on its own?
Yes, a team with PostgreSQL administration skills and some experience with Terraform can do this without an outside partner, and many do. The hard parts are less about syntax than about decisions: how state holds password material, how drift is detected and who acts on it, and how existing grants are reconciled with the code without causing an outage. Teams that split this work often keep ownership of the code and the access approvals in-house and bring in outside help for the initial design, import and review process. Whichever path you choose, agree the scope in writing first.
How should Terraform state handle PostgreSQL passwords?
Terraform state can contain sensitive values, so passwords set through the provider should be treated as secrets. Store state in an encrypted backend with access restricted to the pipeline and a small group of administrators, and avoid putting plain-text passwords in variable files committed to source control. Where possible, let the login system or a secrets manager generate and rotate passwords, and keep the Terraform configuration referencing those secrets rather than holding their values. Confirm with your security team how state is encrypted, who can read it and how backups of the state are handled.
How do we detect drift between Terraform code and the live database?
Run a scheduled plan against each environment and treat any reported change as a finding to resolve. A plan shows grants or roles that were changed outside the code, such as a privilege added by hand during an incident. Decide in advance whether drift is corrected automatically or reviewed first, because automatic correction can remove access someone still needs. Keep the plan output in the pipeline logs so auditors can see when drift was found and how it was handled.
How does Terraform management connect to access reviews?
Terraform gives reviewers a single, versioned list of what each role can do, which makes periodic access reviews faster and easier to evidence. Each role should have a named owner who confirms during the review that the access is still needed, and removals should go through the same code change process as additions. The code shows what was granted and when it changed, but it does not decide whether access is appropriate, so the review criteria and sign-off still belong to your governance process. Ask any partner how they will prepare review evidence, and be clear that independent auditors, not the implementation partner, assess whether controls meet a standard.
How DeployOpen scopes and delivers this integration
DeployOpen is a Chainscore Labs company. We plan, implement, harden and document self-hosted open-source platforms inside your own cloud accounts, data centers or air-gapped networks, and PostgreSQL role and grant automation with Terraform is one of the pieces we build around those platforms. The Terraform code, the state backend, the provider configuration and the review workflow all run in infrastructure you control, so the people who own the database also own the code that defines its access.
Most engagements are fixed-scope: the written scope, deliverables and timelines are agreed before any work starts. For this integration, that scope usually names the databases and schemas in use, the role hierarchy to be codified, which existing roles will be imported rather than recreated, where the Terraform state lives and who may apply changes. It also names what is out of scope, such as application-level permissions inside the apps themselves. Ask for the scope in writing before you compare quotes, because two quotes that cover different roles and schemas are not comparable.
Ongoing work is available as a retainer. Typical retainer items for this topic include provider version upgrades, periodic drift checks, re-running the access review export, and retesting after schema changes. Confirm with us exactly which items sit inside the retainer and which are billed as separate changes, and confirm how the access review evidence will be handed over to your auditors. DeployOpen prepares systems, controls and evidence for compliance assessments, but independent auditors and certification bodies issue the audit reports.

