GenAI & Agents · Agent-assisted

Vault Access via Directory Groups, Requested by an Agent, Approved by a Human

Vault identity, groups and policies are Terraform-managed, and an agent turns an access ticket into a validated branch and pull request that edits group membership.

  • HashiCorp Vault
  • Terraform
  • Python
  • GitHub Actions
  • GitHub Copilot

// Why this matters

Managing HashiCorp Vault access with Terraform groups and pull requests turns a slow, error-prone ticket queue into a reviewable diff. Vault is where secrets live, so the process that grants access to it deserves more rigor than a chat message to whoever has admin.

The engineering insight is to avoid putting people in Vault at all. People belong to directory groups; Vault trusts the directory through OIDC; access is a function of group membership. Then "give a developer access to the lower environment" is one line in one list.

An agent is useful here for the boring middle: parsing the request, checking it against a fixed schema and producing a correct edit. It is dangerous if it can also approve and apply, so it cannot. See Vault as the Control Plane: A Five-Tier Key Model with Locking for how the secret data itself is organised.

// The problem

Access requests arrived as free-text tickets. Someone with admin rights would translate "developer access to production secrets for X" into a change, and the translation varied: wrong group, wrong environment, a missed removal when someone changed teams. Nobody could easily answer who had access to what.

Vault-side manual edits are also invisible to review. A policy attached to a user in the UI leaves no diff, no approver and no easy revocation.

Finally, there is the typo problem. If the config is a list of email addresses, a typo or an external address is one keystroke away. The system needs to reject bad input before a human spends time reviewing it.

// The solution

Three layers. Policy files per environment define what each role can do, as plain HCL files loaded by Terraform. Vault identity groups attach those policies by role. Each identity group has an external group alias that maps to a directory group, so membership is controlled where people are managed.

Access is then a membership change in the directory-group config (the same config described in One Config, Two Clouds: Group and Role Management as Code). A role is a fixed set of groups, one per environment. A request for a role in both environments means two group edits.

The agent is a small Python CLI with a Copilot instruction file wrapping it. It takes a ticket ID, an email, a role from a fixed list and an environment (upper, lower or both). It validates each input, checks whether the user is already a member, creates a ticket-named branch from the latest main, edits the config and opens a pull request with a templated body. It never runs Terraform apply.

Review happens on the PR. A plan-only workflow runs for both environments and posts the result. A human reads the plan, approves and merges; the merge triggers apply, which is skipped when the plan has no changes. Revocation uses the identical path. I rejected giving the agent an apply token because it would collapse the separation that makes the agent safe (the broader pattern is in Agentic SRE: MCP Servers and Workflow Agents for Change and Observability).

How it flows flow1. Ticket → 2. Validate → 3. Existence check → 4. Branch → 5. Edit → 6. Pull request → 7. Review and plan → 8. Merge and apply → 9. Revoke01Ticket02 · GATEValidate03Existence check04Branch05Edit06Pull request07Review and plan08Merge and apply09Revoke
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Ticketrequest names role, environment and user
  2. Validate gateemail domain, role from a fixed list, environment upper, lower or both
  3. Existence checkuser looked up before the edit
  4. Branchcreated from latest main with a ticket-based name
  5. Edituser added to role groups for the chosen environments
  6. Pull requestcommit and PR opened; the agent applies nothing
  7. Review and planPR triggers plan-only workflow for both environments
  8. Merge and applyno-op plans skip apply
  9. Revokethe same path removes membership
RequesterAgentRepositoryReviewerPipelineTicket: role, env, emailValidated: domain, role, env, existingBranch, edit membership, open PRPlan-only for both environmentsRead plan, approve, mergeApply if plan has changes
Ticket to merged access. The agent stops at the PR; apply is triggered by the merge.
Peopledirectory usersDirectory groupsrole x environmentmanaged as codeVault identityexternal group aliasidentity grouppolicy attachmentPoliciesfiles per environmentreviewed in git
Where access is decided. Vault never knows individuals; the directory group is the single control point.

// Before you start

  • A Vault cluster with the OIDC auth method enabled against your directory
  • Terraform 1.5+ with the vault provider and a CI identity that can manage identity and policy endpoints
  • Directory groups per role and environment, managed in code
  • Python 3.10+, git and the GitHub CLI for the agent
  • GitHub Actions with a protected environment for apply

// Step-by-step implementation

  1. 01 Store policies as files, one set per environment

    Keep each policy as an .hcl file in a directory per environment and load them with fileset. A new policy is a new file; a changed rule is a diff. Names come from the file name, so there is nothing to keep in sync.

    Roles are tiers of the same shape: viewer reads, developer reads and writes application paths, admin manages mounts and policies. Keep them as separate files so a reviewer can compare tiers.

  2. 02 Create identity groups and alias them to directory groups

    An external identity group holds the policies; an alias links it to the directory group by name or object ID, as presented in the OIDC token groups claim. When a user logs in, Vault reads the claim, finds the alias and grants the group's policies for the session.

    No per-user entities are needed. If you also create users explicitly (for audit naming), give each an OIDC alias, but the group path is what grants access.

  3. 03 Run plan on pull request, apply on merge

    Two jobs from one workflow. On pull request, plan both environments and post the output. On push to main, plan again and apply only if the plan has changes; a no-op plan skips apply entirely. Per-environment matrix keeps blast radius separate.

    Make apply require a protected environment with reviewers. The PR approval reviews the change; the environment protects the credentials used to apply it.

  4. 04 Encode roles and environments as a fixed mapping in the agent

    The agent's authority is its schema. Roles are keys in a dictionary, each pointing to a group per environment; there is no code path that creates a role or a group. If a request names a role not in the table, the agent stops.

    Use Literal types and an allow-listed email domain so validation is a few lines and the failure messages are precise.

  5. 05 Edit the membership config safely and idempotently

    Prefer a structured format over regex edits on HCL. If your config is a tfvars or YAML file, parse and rewrite it; if it must be HCL, anchor the edit to the exact group block and check the result parses before committing.

    Make the operation idempotent: if the user is already in every target group, report that and exit without a branch. That makes retries and duplicate tickets harmless.

  6. 06 Branch, commit and open the pull request, and nothing else

    Create the branch from the latest main with a name built from the ticket ID, commit with a conventional message, push and open the PR with a template that lists role, environments, requester and the checklist the reviewer should walk through.

    The agent has no Terraform credentials and no merge permission. Make that structural: run it with a token that can only push branches and open PRs.

// How to verify it works

  • Run the agent with an email from a different domain: it must exit non-zero before touching git.
  • Run it for a user already in the target groups: it must report "already a member" and create no branch.
  • Open the PR it creates and read the plan comment: only membership additions should appear, for exactly the requested environments.
  • After merge, log in to Vault as the user through OIDC and run vault token lookup: the token policies must include the role policy.
  • Revoke by running the removal path and merging: a fresh login must no longer carry the policy.

// Design decisions and trade-offs

  • The agent never applies; a human reviews the plan.
  • Role-to-group mapping is a fixed list, so the agent cannot invent roles.
  • Policies live as files in version control; PR-plan and merge-apply are split.
  • Chat and scan toggles are controlled per workflow.

// Pitfalls and lessons learned

  • Policies attach at login. A user who is already logged in keeps their token until it expires, so revocation is not instant; shorten the OIDC token TTL if that matters.
  • The group alias name must match what the token actually carries (usually an object ID, not a display name). A mismatch yields silent no-policy logins.
  • Regex edits on HCL are brittle. A structured config format or a parse check after the edit saves a lot of confusion.
  • Applying on every merge even when the plan is empty creates noise and risk. Branch on the plan exit code.
  • Never give the agent apply credentials "just for the lower environment". The separation only works if it is absolute.
  • Role tiers drift if policies are copied. Keep one file per role and compare in review.

// Frequently asked questions

How do I give users Vault access through directory groups?

Enable OIDC auth, create an external identity group per role with its policies, and add an alias whose name matches the directory group ID in the token. Membership in the directory group then grants the policies.

Should an automation agent be able to apply Terraform?

No. Let it propose a change and let a human review the plan; that is the control which makes it safe to automate the tedious part.

How do I revoke Vault access?

Remove the user from the directory group through the same pull request path. Existing tokens expire on their TTL; revoke explicitly for urgent cases.

What does terraform plan -detailed-exitcode do in CI?

It returns 2 when there are changes, which lets the pipeline skip apply on a no-op plan.

Why store Vault policies as files?

Files give diffs, history and review. A policy change becomes a pull request instead of an invisible edit.

// The outcome

Access changes become reviewed, revocable pull requests; 6 roles across 2 environments.

// Where to take it next

// Keep reading