Infrastructure as code security is the practice of securing the code that defines cloud infrastructure, plus the state files and pipelines that apply the code. In practice, the work covers misconfiguration scanning in every pull request, policy as code, secrets kept out of state, state file protection, drift detection, a least-privilege pipeline identity and module provenance.
At a glance
- What gets secured: Terraform or other IaC code, the plan, the state file, the CI/CD pipeline that applies changes, third-party modules
- Core controls: IaC security scanning in pull requests, policy as code, secrets out of state, protected remote state, scheduled drift detection, short-lived pipeline credentials, pinned modules
- Example open-source tools: Checkov, Trivy (successor to tfsec), Open Policy Agent with Conftest
- Right-sizing: Tier assets so production and internet-facing resources get the strictest gates
- Evidence byproduct: The IaC repository becomes the configuration baseline and the change record for SOC 2 CC8.1, CC7.1 and ISO 27001 A.8.9
What does infrastructure as code security cover?
Infrastructure as code security covers the code, the state and the pipeline. A Terraform repository describes what the infrastructure should look like, the state file records what Terraform believes exists, and the pipeline holds the credentials that turn a merged pull request into real resources. An attacker who reaches the code, the state or the pipeline can change production.
The controls I put in place for an IaC security program are:
- Misconfiguration scanning of code and plans in every pull request.
- Policy as code for organization-specific rules a generic scanner does not know.
- Secrets management so credentials never land in code, plans or state.
- State file protection with encryption, versioning, locking and narrow access.
- Drift detection to catch changes made outside the pipeline.
- Least-privilege pipeline identity with short-lived credentials.
- Module provenance through pinned versions and reviewed sources.
How does IaC security scanning work in a pull request?
IaC security scanning runs a static analysis tool against Terraform code, or against the Terraform plan, each time a pull request is opened, and fails the build when a check fails. Examples of checks include a storage bucket open to the public, a security group allowing SSH from 0.0.0.0/0, an unencrypted database or logging turned off.
Examples of open-source IaC scanners:
- Checkov scans cloud infrastructure configurations for misconfigurations before deployment. Checkov covers Terraform (including plan files), CloudFormation, Kubernetes, Helm, ARM templates, the Serverless Framework and AWS CDK.
- Trivy includes the IaC misconfiguration checks from tfsec. Aqua Security is consolidating tfsec into Trivy and encourages tfsec users to move over.
Scanning the plan as well as the code catches values that only resolve at plan time, such as variables passed in from another workspace.
Key insight
An IaC scanner baseline needs justified exceptions.
The first scan of an existing repository usually returns a long failure list. At one SaaS company, the first CIS benchmark scan of production servers showed hundreds of failures across 289 rules, and about half were not applicable or already addressed by other controls. The same review works for IaC findings: give each finding a disposition of remediate, accept with a written reason, or not applicable. Checkov supports inline skip comments with a reason, so the justification lives next to the resource in Git.
The CI/CD security automation guide covers SAST, SCA and DAST jobs in the same pipeline.
What is policy as code for Terraform?
Policy as code for Terraform means writing organization-specific rules as code and testing every Terraform plan against those rules before apply. Generic scanners check common misconfigurations, and policy as code checks the decisions a company has made for itself.
Examples of policy-as-code rules:
- Every resource carries an owner tag and a data classification tag.
- Databases may only be created in approved regions.
- Production resources may not be destroyed without a second approval.
Conftest is a utility for writing tests against structured configuration data, and Conftest policies use the Rego language from Open Policy Agent. A common setup converts the plan to JSON with terraform show -json and runs Conftest against the JSON in the pipeline. Keep the policies in a repository with the same review rules as the infrastructure code.
How do secrets end up in Terraform state, and how do you keep them out?
Secrets end up in Terraform state when a secret value passes through Terraform configuration. HashiCorp's guidance on sensitive data states that Terraform stores secret values added to configuration in the state and plan files. Marking a variable as sensitive hides the value from CLI output, but the value is still stored in state and plan files.
Ways to keep secrets out of Terraform state:
- Reference secrets at runtime. Store the secret in a secrets manager and have the application read the secret directly, so Terraform only manages the secret's container and permissions.
- Use ephemeral values. Terraform omits ephemeral values from state and plan files entirely.
- Use write-only arguments where the provider supports them. Write-only arguments, usually named with a
_wosuffix, do not persist outside the current Terraform run. - Scan for hardcoded secrets in the repository and in pull requests, beside the IaC scanner.
Watch out
The Terraform state file is a secrets store whether the team planned one or not.
Treat state as sensitive data. Keep state out of Git, and give state the same access controls as the production secrets inside the file.
How should the Terraform state file be protected?
The Terraform state file should be stored in a remote backend that encrypts state at rest, keeps versions, locks state during runs and allows access only to the pipeline identity plus a small break-glass group. A state file on a laptop or in a repository hands every reader a copy of any secret that slipped into state.
Terraform state protection controls I check:
- Remote backend with encryption at rest and in transit.
- Object versioning, so a corrupted or deleted state can be restored.
- State locking, so two runs cannot write at the same time.
- Read and write access limited to the pipeline role, with human access logged and reviewed.
- A separate state per environment, so a development pipeline cannot read production state.
How does drift detection work for infrastructure as code?
Drift detection for infrastructure as code compares the live environment with the code on a schedule and raises an alert when the two differ. Drift comes from console changes, scripts and incident fixes that never make the trip back into the repository.
A simple drift check runs terraform plan -detailed-exitcode on a schedule. According to the terraform plan documentation, exit code 0 means no changes, 1 means an error and 2 means changes are present. A scheduled job that opens a ticket on exit code 2 turns drift into a tracked item with an owner.
Code records the configuration at the moment of apply. A scheduled drift check confirms the configuration still matches weeks later. At one cloud-native fintech, the team agreed to a quarterly check that current state matched the code. The quarterly check became the ongoing evidence the auditor needed for the SOC 2 Type 2 period.
What identity should the IaC pipeline use?
The IaC pipeline should use short-lived credentials issued through OpenID Connect (OIDC) federation, with separate roles for plan and apply. The IaC pipeline often holds the broadest cloud permissions in the company, so long-lived access keys stored as CI secrets are a high-value target.
GitHub's OIDC documentation describes the benefit plainly: no need to duplicate cloud credentials as long-lived GitHub secrets. The cloud provider trusts the CI platform, and each workflow run requests a short-lived token.
My approach to IaC pipeline identity:
- Plan role: read-only, available to pull request builds.
- Apply role: write access, trusted only for the protected main branch after an approved merge.
- Branch protection: required reviews and passing IaC scans before merge.
- No standing human admin access to production, with break-glass access logged.
How do you verify Terraform module provenance?
Terraform module provenance means knowing where each module and provider comes from and pinning the exact version the team reviewed. An unpinned public module can change infrastructure on the next run with no change in the company's repository.
The Terraform dependency lock file records provider versions and checksums, and Terraform rejects a provider package that matches none of the recorded checksums. The lock file tracks only providers. Terraform does not remember remote module versions, so only an exact version constraint pins a module.
Terraform supply chain controls:
- Commit
.terraform.lock.hclto the repository. - Pin every module to an exact version or commit.
- Prefer modules from an internal registry or a reviewed fork for production.
- Review module upgrades as code changes, with the scanner run against the new plan.
Do all assets need the same infrastructure as code security controls?
Infrastructure as code security controls work best when tiered by asset risk, with the strictest gates where a misconfiguration does the most damage.
A three-tier asset model from a SaaS company of 15 to 20 people:
| Asset tier | Examples | Configuration control |
| Tier 1 | Production systems, anything internet-facing | Weekly automated scans, full CIS benchmark baselines, alerts on configuration changes |
| Tier 2 | Hypervisors, storage, internal management servers | Quarterly manual reviews with documented checklists |
| Tier 3 | Network switches, phones | Default credentials changed, baseline documented, annual check |
At a small healthtech company, the head of IT spent most of a week running CIS benchmark scans on workstations that were out of scope for the audit. A two-tier standard fixed the scope: a basic secure deployment standard for everything in the production and management network, and CIS benchmark scanning only for sensitive and internet-facing systems such as firewalls and web servers.
My approach applies the same tiers to IaC policy gates. Modules that build Tier 1 resources hard-fail the pipeline on any high-severity finding. Modules for lower tiers report findings as warnings and feed a backlog.
How does an IaC repository become the configuration baseline and change record?
An IaC repository becomes the configuration baseline and the change record once the team documents what the code enforces. The code defines the approved configuration, Git history shows every change, and the pull request shows who reviewed and approved each change.
One cloud-native fintech used infrastructure as code for all server provisioning, including base configurations through automation playbooks. The team ran no CIS benchmark scanning and was unsure whether the IaC approach would satisfy configuration management for SOC 2. The work that closed the gap:
- Annotate the automation playbook with what each section enforces: base configuration, patching, networking and container setup.
- Document strengths already in the code. SSH key-only access to servers removed password complexity concerns entirely, but nobody had written the control down.
- For SOC 2 Type 1, present the annotated playbook as the configuration standard.
- For SOC 2 Type 2, add the quarterly drift check to show the configuration stayed in the defined state.
The SOC 2 configuration baselines guide for bare metal covers the same baseline work for servers that IaC does not manage.
What SOC 2 and ISO 27001 evidence does IaC security produce?
IaC security produces SOC 2 and ISO 27001 evidence as a byproduct of the engineering controls in an IaC security program. Under SOC 2 CC8.1, the entity authorizes, designs, develops or acquires, configures, documents, tests, approves, and implements changes to infrastructure, data, software, and procedures to meet its objectives (AICPA Trust Services Criteria). Pull requests with scans and approvals cover most of that sentence.
| Framework control | IaC security evidence |
| SOC 2 CC8.1 change management | Pull requests with reviewer approval, scan results and apply logs |
| SOC 2 CC7.1 detection and monitoring | Scheduled drift check results and the tickets they opened |
| ISO/IEC 27001:2022 A.8.9 configuration management | The IaC code as the documented baseline, plus justified scanner exceptions |
| ISO/IEC 27001:2022 A.8.32 change management | Git history and merge approvals for every infrastructure change |
| CIS Control 4, secure configuration | Policy-as-code rules and scan baselines by asset tier |
The ISO 27001 A.8.9 configuration management guide covers the full A.8.9 evidence set. For pulling IaC evidence into a GRC platform, see SOC 2 automation and compliance as code and the AWS compliance-as-code guide.
What are the IaC security best practices to start with?
The IaC security best practices to start with are the controls that close the largest gaps for the least effort. A sequence I use:
- Move state to an encrypted, versioned, locked remote backend and restrict access.
- Replace long-lived CI cloud keys with OIDC and split plan and apply roles.
- Add an IaC scanner to pull requests and triage the first results with written dispositions.
- Remove secrets from configuration and state.
- Schedule a drift check that opens a ticket on any difference.
- Pin modules and commit the lock file.
- Add policy-as-code rules for the decisions specific to the company.
- Tier assets and set gate strictness per tier.
Why is infrastructure as code security architecture work first?
Infrastructure as code security starts with four architecture questions:
- Who can change infrastructure?
- Through which path?
- With which credentials?
- How would anyone know about a change outside that path?
A team with protected state, short-lived pipeline credentials, scanned pull requests and a drift check already holds the configuration baseline and change record auditors ask for.
Truvo Cyber designs IaC pipelines and cloud controls as part of security architecture work, and builds the evidence collection through GRC engineering services.
Secure the pipeline that builds production
Truvo designs IaC pipelines as part of an effective security program, with audit evidence built in.
Frequently asked questions
What is infrastructure as code security?
Infrastructure as code security is the practice of securing the code that defines cloud infrastructure, the state files that track what exists, and the pipeline that applies changes. Core controls include IaC scanning in pull requests, policy as code, secrets kept out of state, drift detection and short-lived pipeline credentials.
What tools are used for IaC security scanning?
Common open-source IaC security scanning tools include Checkov and Trivy. Checkov scans Terraform, CloudFormation, Kubernetes, Helm and other formats. Trivy now carries the checks from tfsec. Open Policy Agent with Conftest tests Terraform plans against custom rules written in Rego. Many teams run a scanner and policy as code together in the pull request pipeline.
Does Terraform store secrets in the state file?
Terraform stores secret values in state and plan files when those values pass through Terraform configuration, even when the variable is marked sensitive. HashiCorp advises treating state as sensitive data. Ephemeral values and write-only arguments keep secrets out of state, and secrets managers let applications read secrets at runtime.
Can infrastructure as code count as SOC 2 evidence?
Infrastructure as code can count as SOC 2 evidence once the team documents what the code enforces. Annotated code serves as the configuration baseline, and pull requests with approvals and scan results show change management under CC8.1. For a Type 2 audit, auditors also look for periodic proof, such as drift checks, that live infrastructure still matches the code.
Ready to Start Your Compliance Journey?
Get a clear, actionable roadmap with our readiness assessment.
Contact Us
Sample SOC 2 Control List
Input your email to download the list.
About the Author
Former security architect for Bank of Canada and Payments Canada. 20+ years building compliance programs for critical infrastructure.