Compliance as Code: Building HIPAA-Ready CI/CD Pipelines With Terraform

Compliance as Code: Building HIPAA-Ready CI/CD Pipelines With Terraform

A healthcare software team can encrypt its production database, execute a Business Associate Agreement with its cloud provider, and still expose electronic protected health information through its software delivery pipeline.

A Terraform state file may retain a database password. A saved infrastructure plan may contain sensitive configuration values. An engineer may unknowingly send production data into a test workflow. A compromised third-party CI action may expose cloud credentials. An approved pull-request plan may also differ from the infrastructure plan generated after the code is merged.

The problem is not that healthcare organizations release software too quickly.

The problem is that security and compliance reviews often happen after infrastructure decisions have already been coded, approved, and deployed.

HIPAA compliance as code addresses this gap by translating selected security requirements, organizational policies, and risk decisions into version-controlled infrastructure modules, automated tests, policy gates, deployment approvals, and continuously generated evidence.

Terraform is valuable in this model because it makes infrastructure changes repeatable, reviewable, and testable. However, Terraform cannot make an organization HIPAA compliant. HIPAA compliance also depends on risk analysis, workforce controls, policies, vendor management, incident response, contingency planning, physical safeguards, access governance, and ongoing evaluations.

There is no universal “HIPAA-certified Terraform configuration.” HHS does not endorse or recognize private HIPAA Security Rule certifications, and receiving a certification does not remove a covered entity’s or business associate’s legal obligations. The practical objective is therefore to build a HIPAA-ready CI/CD pipeline that consistently applies approved safeguards, blocks unacceptable infrastructure changes, governs exceptions, and produces reliable evidence.

What Is HIPAA Compliance as Code?

HIPAA compliance as code is an engineering model that represents selected compliance controls and security decisions in machine-readable, testable, and version-controlled form.

For example, an organizational policy might state that a database containing ePHI must use encryption, private network connectivity, approved backup settings, audit logging, and restricted administrative access.

Compliance as code can translate that policy into:

  • A hardened Terraform database module
  • Required encryption and private-network settings
  • A policy rule that rejects prohibited database configurations
  • A CI gate that prevents deployment when the rule fails
  • A cloud-native control that detects or prevents manual changes
  • An evidence record showing that the control passed
  • A documented exception process for unusual cases

The policy and risk analysis remain the authoritative governance layer. The code makes the approved technical control more consistent and harder to bypass.

The HIPAA Security Rule is technology-neutral and scalable. It requires regulated entities to implement appropriate administrative, physical, and technical safeguards, but it does not mandate Terraform, GitHub Actions, Kubernetes, AWS, Azure, Google Cloud, or another particular platform. 

Organizations must select reasonable and appropriate safeguards based on their risks, capabilities, infrastructure, costs, and operating environment.

What Terraform Can and Cannot Do for HIPAA Compliance

Terraform can help automate Terraform cannot establish by itself
Encryption configurations An accurate and thorough HIPAA risk analysis
Private network architecture Permitted uses and disclosures of PHI
Cloud identity policies Workforce authorization decisions
Audit-logging infrastructure Security awareness and workforce training
Backup and recovery resources Business Associate Agreements
Standard resource tagging Incident investigation and breach determination
Hardened cloud modules Physical safeguards
Preventive infrastructure policies Organization-wide HIPAA compliance
Configuration-drift detection Legal interpretation of HIPAA requirements
Repeatable evidence generation Executive acceptance of residual risk

The HIPAA Security Rule requires an accurate and thorough assessment of risks and vulnerabilities to the confidentiality, integrity, and availability of all ePHI created, received, maintained, or transmitted by the regulated entity. A Terraform scanner can identify known configuration weaknesses, but its output is not the required risk analysis.

NIST SP 800-66 Revision 2 provides a structured resource for connecting HIPAA Security Rule requirements to cybersecurity controls and implementation activities. It should inform the control program, but each organization must still determine which measures are reasonable and appropriate for its own environment.

The 2026 HIPAA Security Context

As of July 24, 2026, HHS continues to present the December 2024 HIPAA Security Rule cybersecurity revision as a proposed rule, not a final enforceable rule.

The current HIPAA Security Rule therefore remains the legal baseline.

The proposed revision signals that HHS wants more explicit requirements around encryption, multi-factor authentication, asset inventories, network mapping, vulnerability management, compliance audits, incident response, and recovery planning. 

Healthcare organizations can use those proposals to inform forward-looking architecture, but they should not describe proposed provisions as current legal mandates.

Does HIPAA Currently require Encryption?

Under the current Security Rule, encryption and decryption at rest and transmission encryption are addressable implementation specifications.

Addressable does not mean optional.

A regulated entity must assess whether encryption is reasonable and appropriate through its risk analysis. When it is reasonable and appropriate, the entity must implement it. 

When it is not, the organization must document that determination and implement an equivalent alternative measure when one is reasonable and appropriate.

In modern healthcare cloud environments, encryption at rest and in transit will usually be a fundamental safeguard. Cloud contracts, customer requirements, state laws, internal policies, cyber insurance, and other frameworks may also impose requirements beyond the HIPAA baseline.

Compliance code should therefore enforce the organization’s approved encryption policy without falsely presenting every technical setting as a universal statutory command.

Reference Architecture for a HIPAA-Ready Terraform Pipeline

A mature pipeline should separate code review, infrastructure planning, policy evaluation, production authorization, deployment, and runtime verification.

HIPAA-ready Terraform CICD pipeline flow

A pull-request plan is useful for reviewing expected changes, but it is generally speculative. Infrastructure state, variables, configuration, or dependencies may change before deployment.

The production plan should be generated from the exact merged or release commit, evaluated, approved, and then passed directly to terraform apply. HashiCorp documents that a saved plan allows Terraform to apply the exact changes determined when the plan was created.

1. Define the ePHI and Pipeline Compliance Boundary

Start with data flow rather than Terraform code. Document where ePHI is:

  • Created
  • Received
  • Maintained
  • Processed
  • Transmitted
  • Logged
  • Cached
  • Backed up
  • Restored
  • Exported

Then identify which healthcare software-delivery components can access those locations or influence their security. The relevant environment may include:

  • Source-code repositories
  • CI/CD orchestration platforms
  • Hosted or self-hosted runners
  • Terraform execution environments
  • Remote state backends
  • Saved plan storage
  • Container and package registries
  • Secrets-management services
  • Cloud identity providers
  • Deployment accounts or subscriptions
  • Log aggregation platforms
  • Security scanners
  • Backup systems
  • Notification and ticketing integrations

A healthcare software vendor does not automatically become a business associate merely by supplying software. 

However, a vendor that hosts software containing ePHI or accesses ePHI while providing support may become a business associate.

Similarly, a cloud provider that creates, receives, maintains, or transmits ePHI on behalf of a covered entity or business associate is generally a business associate, even when the provider stores only encrypted ePHI and does not possess the decryption key. 

An appropriate BAA is required in those circumstances.

Keep PHI Out of CI/CD Whenever Possible

Production patient information should not be used as routine CI test data. Prefer:

  • Synthetic healthcare records
  • Purpose-built test patients
  • Properly de-identified data
  • Masked data with documented safeguards
  • Minimal test datasets created for an approved purpose

If real ePHI is necessary for an authorized test, the runner, storage, logs, caches, artifacts, access controls, retention rules, and involved vendors must be included in the risk analysis.

Where the HIPAA minimum-necessary standard applies, organizations must make reasonable efforts to limit the use and disclosure of PHI and requests to the minimum necessary for the intended purpose.

2. Build a HIPAA-to-Engineering Control Matrix

Do not begin with a generic list of “HIPAA Terraform rules.” Build a control matrix that connects every pipeline safeguard to:

  1. The applicable HIPAA standard
  2. The organization’s risk analysis
  3. The approved policy
  4. The technical implementation
  5. The preventive or detective test
  6. The evidence source
  7. The accountable owner
  8. The exception process
  9. The review frequency
HIPAA area Example pipeline implementation Example evidence
Security management process Risk-ranked policy library and remediation workflow Risk record, policy version and issue history
Information access management Least-privilege deployment identities IAM policy and access-review record
Security incident procedures Pipeline alerts integrated with incident response Alert, ticket, timeline and response record
Contingency planning Versioned backups and tested recovery infrastructure Backup status and restore-test report
Evaluation Periodic technical and nontechnical assessment Assessment report and remediation plan
Access control Unique users, MFA and short-lived workload identities Authentication and role-assumption logs
Audit controls Centralized records of plans, approvals and deployments Protected audit events
Integrity Reviewed plans, protected branches and signed artifacts Commit, policy and provenance results
Authentication Federated CI identity with constrained claims Token and trust-policy logs
Transmission security Enforced TLS and protected service paths Policy result and runtime verification

A control matrix prevents a common compliance failure: implementing a technical feature without being able to explain which risk it addresses, who owns it, or how the organization proves that it operated.

3. Protect Terraform State and Plan Files

Terraform state is one of the most important security assets in an infrastructure-as-code environment. State may contain:

  • Passwords and tokens
  • Private service endpoints
  • Resource identifiers
  • Network information
  • Connection strings
  • Sensitive outputs
  • Values returned by data sources
  • Infrastructure relationships

Marking a Terraform value as sensitive primarily controls how Terraform displays it. The underlying value may still be stored in state, and commands that produce raw or JSON output can reveal sensitive values.

Secure Remote State

Use a remote backend with:

  • Encryption at rest
  • TLS in transit
  • State locking
  • Object versioning
  • Restricted read and write permissions
  • Separate state for each environment
  • Access logging
  • Tested recovery procedures
  • No embedded credentials

An AWS S3 backend can use S3-native state locking with use_lockfile. 

HashiCorp also recommends enabling bucket versioning so previous state versions can be recovered after accidental deletion or human error.

terraform {
  backend "s3" {
    bucket       = "health-platform-prod-tfstate"
    key          = "clinical-api/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    kms_key_id   = "arn:aws:kms:us-east-1:123456789012:key/example-key-id"
    use_lockfile = true
  }
}

The bucket should be provisioned separately with:

  • S3 Block Public Access
  • Versioning
  • Restrictive identity and bucket policies
  • KMS key controls
  • Access logging
  • Recovery protections
  • Monitoring for unauthorized access

Do not hardcode backend credentials. HashiCorp warns that backend configuration values may be written into Terraform’s local metadata and saved plan files.

Treat Saved Plans as Sensitive Artifacts

A saved Terraform plan is an opaque binary artifact, but it can contain sensitive configuration and state-derived information. It can also be rendered using terraform show or exported as JSON.

Terraform explicitly warns that sensitive information obscured in terminal output can still be stored unredacted in a saved plan.

When a plan must move between pipeline stages:

  • Encrypt it
  • Restrict read access
  • Use short retention
  • Prevent public artifact links
  • Protect associated working-directory files
  • Prevent JSON output from reaching logs
  • Destroy the artifact after its approved use
  • Record its digest for evidence

Modern Terraform versions also support ephemeral values and provider-supported write-only arguments that can keep selected secrets out of state and plan files. 

These capabilities should be used where supported, but they do not eliminate the need to protect state.

4. Replace Permanent CI Credentials With Workload Identity

Production CI/CD pipelines should not depend on permanent cloud access keys stored as repository secrets. Use workload identity federation, such as OpenID Connect, to exchange a signed pipeline identity token for short-lived cloud credentials. 

GitHub Actions supports OIDC authentication with major cloud providers, allowing a workflow to request temporary credentials instead of maintaining a long-lived secret.

The cloud trust policy should restrict authentication through claims such as:

  • Repository
  • Organization
  • Branch
  • Environment
  • Workflow
  • Release reference
  • Reusable workflow identity
  • Commit or workflow SHA where supported

Separate identities should be used for:

  • Pull-request validation
  • Read-only production planning
  • Nonproduction deployment
  • Production deployment
  • Emergency access

The production apply identity should be available only to a protected deployment workflow after the required checks and approvals have completed.

Human administrators should use centrally governed identities, MFA, time-bound privileged elevation, and monitored emergency-access procedures.

5. Create Hardened Terraform Modules

Allowing every development team to independently configure encryption, logging, network access, backups, and IAM creates inconsistent safeguards.

Build opinionated modules that make the organization’s approved configuration the default.

A production database module may require:

  • Private subnet placement
  • Storage encryption
  • An approved KMS key
  • No public accessibility
  • Backup retention
  • Deletion protection
  • A final snapshot
  • Audit and engine logs
  • Monitoring
  • Mandatory ownership and classification tags
resource "aws_db_instance" "clinical" {
  identifier        = var.identifier
  engine            = "postgres"
  instance_class    = var.instance_class
  allocated_storage = var.allocated_storage

  storage_encrypted   = true
  kms_key_id           = var.kms_key_arn
  publicly_accessible  = false
  db_subnet_group_name = var.private_subnet_group

  backup_retention_period   = 35
  deletion_protection       = true
  skip_final_snapshot       = false
  final_snapshot_identifier = var.final_snapshot_identifier

  enabled_cloudwatch_logs_exports = [
    "postgresql",
    "upgrade"
  ]

  tags = {
    DataClassification = "ephi"
    Environment        = var.environment
    SystemOwner        = var.system_owner
    ManagedBy          = "terraform"
  }
}

The 35-day backup setting is an illustrative organizational decision, not a universal HIPAA retention requirement. Backup periods must follow the organization’s risk analysis, recovery objectives, policies, contracts, and applicable laws.

Commit .terraform.lock.hcl to version control. HashiCorp recommends reviewing provider-version changes through the same code-review process used for infrastructure configuration. 

Remote modules still require explicit version constraints because Terraform’s dependency lock file tracks providers, not remote module selections.

Turn HIPAA Controls Into Enforceable Cloud Policies
Identify CI/CD, Terraform state, identity, policy, and evidence gaps before they create production compliance risk.

6. Enforce Policy as Code Before Deployment

Static IaC scanners identify common weaknesses. Policy as code enforces the organization’s specific infrastructure rules. A policy library may prevent:

  • Publicly accessible ePHI databases
  • Unencrypted storage
  • Unapproved cloud regions
  • Internet-wide administrative ingress
  • Disabled audit logging
  • Overly broad IAM permissions
  • Missing backup controls
  • Missing mandatory tags
  • Unsupported cloud services
  • Resources outside approved network boundaries
  • Destructive changes without additional approval

The following Open Policy Agent example illustrates the control intent:

package terraform.hipaa

deny[msg] {
  resource := input.resource_changes[_]
  resource.type == "aws_db_instance"
  resource.change.after.storage_encrypted == false

  msg := sprintf(
    "%s must enable storage encryption",
    [resource.address]
  )
}

deny[msg] {
  resource := input.resource_changes[_]
  resource.type == "aws_db_instance"
  resource.change.after.publicly_accessible == true

  msg := sprintf(
    "%s must not be publicly accessible",
    [resource.address]
  )
}

This simplified policy is not a complete production ruleset. Production policies must account for:

  • Missing attributes
  • Computed and unknown values
  • after_unknown values
  • Create, update, replace, and delete actions
  • Provider-schema differences
  • Inherited controls
  • Existing resources with incomplete plan data
  • Approved exceptions
  • Compensating safeguards

Every policy should be tested against positive, negative, missing-value, and unknown-value fixtures before it becomes a blocking control.

Classify Policy Results

Use clear enforcement levels:

  • Mandatory: Deployment is blocked.
  • Conditional: Security or compliance approval is required.
  • Advisory: The finding is recorded but does not block deployment.
  • Not applicable: The rule does not apply, with documented reasoning.

A legitimate exception should identify:

  • The affected control
  • Business justification
  • Risk owner
  • Compensating safeguards
  • Approver
  • Expiration date
  • Remediation plan

Undocumented permanent bypasses weaken both security and auditability.

7. Protect the CI/CD Software Supply Chain

A secure Terraform configuration can still be compromised by a malicious workflow dependency, build tool, provider package, or third-party CI action. Pipeline protections should include:

  • Protected branches
  • Required peer review
  • Required status checks
  • Restricted workflow-file changes
  • Secret scanning
  • Dependency scanning
  • Software composition analysis
  • Container-image scanning
  • Artifact signing
  • Build provenance
  • Approved provider and module sources
  • Isolated or ephemeral runners
  • Minimal workflow permissions

GitHub states that pinning an action to a full-length commit SHA is the only supported way to consume that action as an immutable release. 

Organizations can also enforce SHA pinning through repository or enterprise policy.

CISA and NIST recommend protecting source repositories, managing dependencies, preserving software integrity, and embedding secure-development practices throughout the software lifecycle rather than adding them only before release.

8. Separate Pull-Request Planning From Production Apply

A secure deployment process should use two distinct planning stages.

Pull-request stage

  1. Run terraform fmt.
  2. Run terraform validate.
  3. Scan for secrets and infrastructure weaknesses.
  4. Generate a speculative plan.
  5. Evaluate the expected changes.
  6. Complete code review.
  7. Merge the approved change.

Production stage

  1. Check out the exact merged or release commit.
  2. Initialize the approved providers and modules.
  3. Generate a saved production plan.
  4. Evaluate the saved plan with policy as code.
  5. Review high-risk and destructive changes.
  6. Approve the final production plan.
  7. Apply the exact saved plan.
  8. Verify the deployed configuration.
  9. Capture the evidence package.

A speculative pull-request plan should not be assumed to remain valid after merge.

Applying without a saved plan causes Terraform to create a new execution plan. 

Passing the saved plan file to terraform apply ensures that Terraform executes the operations in the reviewed plan rather than silently creating a different plan.

Terraform may reject a saved plan when it becomes stale because the underlying state changed. The pipeline should then generate, evaluate, and approve a new plan instead of bypassing the check.

9. Generate Compliance Evidence Automatically

Every production change should create a protected evidence package containing:

  • Repository and commit SHA
  • Pull-request identifier
  • Terraform version
  • Provider and module versions
  • Saved-plan digest
  • IaC scan results
  • Policy-as-code results
  • Documented exceptions
  • Reviewer identities
  • Final approver
  • Deployment identity
  • Apply timestamp
  • Apply result
  • Changed resources
  • Post-deployment validation
  • Associated change ticket
  • Drift status

Evidence should be encrypted, access-controlled, searchable, and protected against unauthorized modification or deletion. 

HIPAA requires certain policies, procedures, actions, activities, and assessments to be documented and retained for six years from creation or from the date they were last in effect, whichever is later.

This requirement does not automatically mean that every raw CI log, cache, binary plan, or build artifact must be retained for six years.

Technical retention periods should be established according to:

  • HIPAA documentation requirements
  • Security policy
  • Incident-investigation needs
  • Contractual obligations
  • Litigation holds
  • Operational requirements
  • Applicable federal and state laws
  • The sensitivity of the artifact

In many cases, the evidence record can be retained longer than the sensitive plan artifact itself.

10. Continue Compliance After Terraform Apply

A passing pipeline proves only that a proposed change satisfied the controls evaluated at that time. It does not prove that:

  • Nobody later changed the resource manually
  • Access remained appropriate
  • Logging continued to operate
  • Backups remained restorable
  • A new vulnerability was not discovered
  • The service remained within the approved cloud boundary
  • A provider or configuration change did not create drift

Post-deployment controls should include:

  • Scheduled Terraform drift detection
  • Cloud configuration monitoring
  • Vulnerability and patch management
  • Centralized audit logging
  • Key-use monitoring
  • Privileged-access reviews
  • Backup and restore testing
  • Incident alerting
  • Periodic control evaluations
  • BAA and eligible-service reviews

Cloud compliance operates under a shared-responsibility model. An executed BAA and the use of HIPAA-eligible services do not make a healthcare application compliant by default. 

AWS, for example, states that customers remain responsible for workload configuration, access management, application security, encryption, and other customer-controlled safeguards.

Common HIPAA CI/CD Mistakes

Treating a BAA as a Technical Safeguard

A BAA establishes contractual responsibilities. It does not configure identity controls, encryption, logging, backups, network segmentation, or secure deployment workflows.

Assuming sensitive Removes Values From State

The sensitive property mainly affects display. Sensitive values may still be present in state or plan artifacts.

Running Scanners Without Enforcement

A report that nobody reviews is not an effective preventive control. Define which findings block deployment and who can approve exceptions.

Giving CI Permanent Administrator Credentials

Long-lived credentials increase exposure and weaken separation of duties. Use constrained, short-lived identities.

Using Production PHI in Routine Testing

This can expand the HIPAA boundary to runners, logs, caches, artifacts, testing services, and vendors that were not previously assessed.

Applying a Different Plan Than the One Approved

A speculative pull-request plan may not represent the final production change. Generate and approve a saved plan from the exact deployment commit.

Ignoring Manual Cloud Changes

Terraform does not prevent every out-of-band modification. Use cloud-native preventive controls, runtime monitoring, and drift detection.

Retaining Sensitive Plans Indefinitely

Evidence may need long-term retention, but raw plan files can expose unnecessary information. Separate durable audit evidence from short-lived sensitive artifacts.

HIPAA-Ready Terraform Pipeline Checklist

Before approving a production pipeline, confirm that:

  • The ePHI data flow and CI/CD boundary are documented.
  • Applicable cloud and delivery vendors have appropriate BAAs.
  • ePHI is limited to approved, contractually covered services.
  • Terraform state is remote, encrypted, versioned, locked, logged, and access-controlled.
  • Saved plan files are treated as sensitive artifacts.
  • Sensitive values are excluded from state and plans where supported.
  • CI uses short-lived federated cloud credentials.
  • Planning and production-apply permissions are separated.
  • Production plans originate from the exact deployment commit.
  • The exact approved saved plan is applied.
  • Hardened modules enable approved encryption, networking, logging, and recovery controls.
  • Policy-as-code checks block prohibited configurations.
  • Unknown policy values are handled safely.
  • Exceptions require approval and expiration dates.
  • Branches, workflows, dependencies, actions, and artifacts are protected.
  • Synthetic or properly de-identified data is used for routine testing.
  • Every production change produces linked and protected evidence.
  • Runtime monitoring detects drift and unauthorized changes.
  • Backup recovery and incident procedures are tested.
  • The pipeline is included in periodic technical and nontechnical evaluations.

Building a Defensible Healthcare Delivery Pipeline

HIPAA compliance automation should not be reduced to a collection of Terraform checks. A defensible program connects:

  • The ePHI inventory
  • The security risk analysis
  • Organizational policies
  • Cloud contracts and BAAs
  • Hardened Terraform modules
  • Workload identity
  • Deployment policies
  • Human approvals
  • Runtime controls
  • Incident procedures
  • Audit evidence

Terraform provides the infrastructure control plane. CI/CD provides the enforcement point. Policy as code provides repeatability. Continuous monitoring identifies changes after deployment. Governance connects all four. The result is not automatic HIPAA compliance. 

It is a more controlled, traceable, and defensible engineering environment in which security requirements are consistently applied, and infrastructure risk becomes visible before it reaches production.

Build HIPAA-Ready Cloud and DevSecOps Infrastructure With CapMinds

CapMinds helps healthcare organizations and healthcare SaaS companies design, implement, and operate secure cloud delivery environments for workloads involving sensitive clinical and operational data.

Our healthcare cloud and infrastructure services support:

  • HIPAA-aligned cloud architecture
  • Cloud risk and configuration remediation
  • Terraform module and landing-zone development
  • Secure CI/CD and DevSecOps implementation
  • Workload identity and privileged-access design
  • Policy-as-code development
  • HIPAA control mapping
  • Terraform state and secrets-management architecture
  • Cloud logging, monitoring, SIEM, and drift detection
  • Backup, disaster recovery, and resilience testing
  • Compliance evidence automation
  • Managed IT Services –  cloud, infrastructure, security, and DevOps operations

CapMinds focuses on building a controlled delivery system in which infrastructure changes are reviewable, prohibited configurations are blocked, exceptions are governed, and evidence is generated as part of everyday engineering.

Schedule a 30-Minute Strategy Call

Pandi Paramasivan

Pandi Paramasivan

Founder & CEO of CapMinds.

Leave a Reply

Your email address will not be published. Required fields are marked *