SY0-701Chapter 116 of 212Objective 3.6

Infrastructure as Code Security

This chapter covers Infrastructure as Code (IaC) security, a critical topic for the SY0-701 Security+ exam under Objective 3.6 (Security Architecture). IaC automates the provisioning and management of infrastructure through machine-readable definition files, enabling consistent, repeatable deployments. Securing IaC involves protecting the code itself, the deployment pipeline, and the resulting infrastructure from misconfigurations, injection attacks, and secret leaks. Understanding IaC security is essential for modern cloud and DevOps environments, and the exam tests your ability to identify risks and apply controls like immutable infrastructure, secure coding practices, and pipeline security.

25 min read
Advanced
Updated May 31, 2026

Immutable Infrastructure as Vending Machine

A vending machine is a perfect analogy for immutable infrastructure. Once stocked and configured at the factory, the machine is sealed and shipped. You cannot open it to fix a jam or swap out a candy bar; if something breaks, you replace the entire machine. This mirrors immutable servers: once a configuration is baked into a machine image (AMI or container), you never patch or modify it in production. Instead, you destroy the instance and launch a new one from a hardened image. The security benefit is that configuration drift is impossible—attackers cannot persist by modifying files or installing backdoors because the instance is ephemeral. If a vulnerability is discovered, you rebuild the image with the fix and redeploy. This eliminates the 'snowflake server' problem where each server is uniquely configured and manually patched, leading to inconsistencies. Just as a vending machine's internal state is reset with each new stock, an immutable server's state is reset with each deployment. Attackers who gain access find no persistent foothold; their changes vanish on reboot or replacement. The mechanism is identical: treat infrastructure as disposable, not repairable.

How It Actually Works

What is Infrastructure as Code (IaC)?

Infrastructure as Code (IaC) is the practice of managing and provisioning computing infrastructure (networks, virtual machines, load balancers, databases) through machine-readable definition files, rather than through manual hardware configuration or interactive configuration tools. These definition files can be version-controlled, reviewed, and tested like application code. Common IaC tools include Terraform (HashiCorp), AWS CloudFormation, Azure Resource Manager (ARM) templates, Ansible, Puppet, and Chef. The key security principle is that infrastructure should be treated as code: it should be stored in a repository, undergo peer review, be scanned for vulnerabilities, and be deployed through a secure CI/CD pipeline.

The Threat: Misconfiguration and Drift

The primary security risk with IaC is misconfiguration—accidentally exposing resources to the public internet, using default credentials, or failing to encrypt data. Configuration drift occurs when manual changes are made to a running instance, causing it to diverge from the defined state. Attackers exploit these misconfigurations to gain unauthorized access. For example, an S3 bucket configured as 'public' in a Terraform file can leak sensitive data. The exam focuses on preventing these issues through immutable infrastructure, secure coding practices, and automated scanning.

How IaC Works Mechanically

1.

Define: You write a configuration file (e.g., Terraform HCL, CloudFormation YAML) that declares the desired state of your infrastructure. This includes resource types, properties, and dependencies.

2.

Version Control: The file is committed to a Git repository, enabling change tracking and collaboration.

3.

Review and Scan: Pull requests trigger automated scans for security issues (e.g., tfsec, Checkov, Snyk IaC). These tools check for hardcoded secrets, overly permissive IAM policies, and unencrypted storage.

4.

Plan: The IaC tool generates an execution plan showing what changes will be made. This plan is reviewed by humans or automated policy engines (e.g., OPA, Sentinel).

5.

Apply: The tool connects to the cloud provider's API and provisions the resources. This step should be automated through a CI/CD pipeline with least-privilege credentials.

6.

Monitor: Continuous monitoring (e.g., AWS Config, Azure Policy) detects drift and triggers remediation.

Key Components and Standards

Immutable Infrastructure: Instead of patching running servers, you replace them entirely. This prevents drift and ensures consistency. Exam tip: Immutable infrastructure is a core IaC security concept.

Idempotency: Applying the same configuration multiple times results in the same state. This prevents unintended changes.

Secrets Management: Never hardcode secrets. Use tools like HashiCorp Vault, AWS Secrets Manager, or environment variables injected at runtime.

Policy as Code: Use Open Policy Agent (OPA) or HashiCorp Sentinel to enforce security policies (e.g., "all S3 buckets must have encryption enabled").

CI/CD Pipeline Security: Secure the pipeline itself—use signed commits, scan for vulnerabilities, restrict access to production environments.

How Attackers Exploit IaC

Injection Attacks: Attackers can inject malicious code into IaC templates if user input is not sanitized. For example, a Terraform template that accepts a variable for an AMI ID could be tricked into launching a compromised AMI.

Exposed Secrets: If a secret (e.g., AWS access key) is hardcoded in a Terraform file and pushed to a public repo, attackers can use it to access your cloud account.

Privilege Escalation: Overly permissive IAM roles defined in IaC can allow attackers to escalate privileges.

Supply Chain Attacks: Compromised modules or providers (e.g., a malicious Terraform module from the public registry) can introduce backdoors.

Defenders' Countermeasures

Static Analysis for IaC: Use tools like Checkov, tfsec, or Terrascan to scan for misconfigurations before deployment. These tools check against security benchmarks like CIS Benchmarks.

Secrets Scanning: Use git-secrets or pre-commit hooks to prevent secrets from being committed.

Principle of Least Privilege: Define IAM roles with minimal permissions. Use IAM policies that grant only required actions.

Immutable Deployments: Use golden images (AMIs, container images) that are hardened and scanned. Never SSH into production servers.

Change Management: Require peer review and automated policy checks before merging IaC changes.

Real Command/Tool Examples

Terraform: terraform plan shows changes; terraform apply provisions resources. Use terraform validate to check syntax.

Checkov: checkov -d . scans all IaC files in a directory. Example output: "Check: CKV_AWS_18: Ensure the S3 bucket has access logs enabled."

tfsec: tfsec . outputs misconfigurations with severity levels.

AWS CloudFormation: Use aws cloudformation deploy --template-file template.yaml --capabilities CAPABILITY_IAM to deploy.

Policy as Code: OPA example policy: deny[msg] { input.bucket.acl == "public-read" ; msg = "S3 bucket must not be public" }.

Walk-Through

1

1. Define Infrastructure in Code

Write a configuration file (e.g., Terraform HCL) that declares resources like EC2 instances, S3 buckets, IAM roles, and security groups. This file should be stored in a version-controlled repository. Security best practices include using variables for sensitive data, avoiding hardcoded secrets, and following the principle of least privilege. For example, an EC2 instance should have a security group that only allows necessary ports. Tools like VS Code with Terraform extension can provide syntax highlighting and validation.

2

2. Commit and Scan for Issues

Commit the IaC file to a Git repository. Before merging, automated scans run using tools like Checkov or tfsec. These scans check for misconfigurations such as open security groups, unencrypted storage, or public S3 buckets. The scan output will highlight violations with severity levels (HIGH, MEDIUM, LOW). For example, Checkov might flag 'CKV_AWS_79: Ensure Instance Metadata Service Version 1 is not enabled' and suggest enforcing IMDSv2. Developers must fix these issues before proceeding.

3

3. Review and Approve via Pull Request

A pull request (PR) is created for the IaC change. Peer reviewers examine the diff for security flaws, such as overly permissive IAM policies or exposed ports. Automated policy engines (e.g., OPA) can enforce organizational rules—for instance, blocking any PR that creates a security group with 0.0.0.0/0 for SSH. The CI/CD pipeline may also run a `terraform plan` to show what resources will be created, modified, or destroyed. Only approved PRs are merged.

4

4. Deploy via CI/CD Pipeline

After merging, the CI/CD pipeline (e.g., Jenkins, GitLab CI, GitHub Actions) triggers the IaC tool to apply the configuration. The pipeline uses temporary credentials with least privilege—only enough to create the defined resources. For example, a GitHub Actions workflow might run `terraform apply -auto-approve` using an OpenID Connect (OIDC) role. The pipeline should log all actions for audit. If the deployment fails, the pipeline should roll back to the previous state.

5

5. Monitor for Drift and Remediate

After deployment, continuous monitoring tools (e.g., AWS Config, Azure Policy) detect configuration drift—any manual changes that deviate from the IaC definition. For example, if an administrator manually opens an S3 bucket to public, AWS Config will flag it as noncompliant. Automated remediation can be set up to revert the change or alert the security team. Regular compliance scans (e.g., CIS benchmarks) should also be run against the live infrastructure to ensure it matches the desired state.

What This Looks Like on the Job

Scenario 1: Public S3 Bucket via Terraform A security engineer at a fintech company notices an alert from AWS GuardDuty indicating that an S3 bucket is publicly accessible. Investigating, they find the bucket was created by a Terraform deployment. The engineer checks the Git history and sees that a developer had set acl = "public-read" in the Terraform file, which was merged without review. The engineer immediately revokes public access, then implements a Checkov scan in the CI pipeline that blocks any ACL that grants public access. They also add an OPA policy that denies any S3 bucket without block_public_acls = true. The mistake was relying solely on manual review; automated policy enforcement would have caught it.

Scenario 2: Exposed Secrets in IaC Repository A DevOps engineer accidentally commits a Terraform file containing an AWS access key and secret key to a public GitHub repository. Within minutes, a bot scrapes the repo and uses the credentials to launch hundreds of EC2 instances for cryptocurrency mining. The company's cloud bill spikes. The security team's response is to immediately rotate the compromised keys, remove the commit from history (using git filter-branch), and enable secrets scanning with pre-commit hooks (e.g., git-secrets). They also configure GitHub's secret scanning to alert on future leaks. The common mistake is assuming that removing the file later is sufficient; the key must be rotated because it was exposed.

Scenario 3: Immutable Infrastructure to Prevent Ransomware A healthcare provider uses immutable infrastructure with AWS Auto Scaling groups and golden AMIs. An attacker gains SSH access to one instance via a vulnerability. Before they can pivot, the instance is automatically replaced due to a health check failure (the attacker's changes cause the application to crash). The new instance is identical to the original hardened image. The attacker's modifications are lost. The security team reviews logs and finds the attack vector, then patches the AMI. This approach prevents persistent access. A common mistake is treating instances as mutable and trying to clean them manually, which can leave remnants.

How SY0-701 Actually Tests This

Exactly What SY0-701 Tests on IaC Security

The exam focuses on understanding how IaC improves security through consistency, automation, and immutability. You need to know:

The difference between mutable and immutable infrastructure.

How to secure IaC code (secrets management, scanning, version control).

The role of CI/CD pipelines in IaC security.

Common misconfigurations (public S3 buckets, open security groups, unencrypted data).

Tools: Terraform, CloudFormation, Ansible, Chef, Puppet (but not their syntax).

Top 4 Wrong Answers and Why Candidates Choose Them

1.

"IaC eliminates all security risks because it automates deployment." – Automation reduces human error but does not eliminate misconfigurations; flawed code still creates vulnerabilities.

2.

"IaC should be deployed directly to production without review." – Candidates confuse speed with security; IaC must undergo review and testing.

3.

"Secrets should be stored in the IaC file for simplicity." – This is a dangerous practice; secrets must be handled by a secrets manager.

4.

"Immutable infrastructure means you never update the image." – No, you rebuild the image with updates; the running instances are replaced.

Specific Terms and Values

Idempotent: Applying the same configuration multiple times yields the same result.

Drift: When actual infrastructure state differs from the defined state.

Golden Image: A pre-configured, hardened OS image used for immutable deployments.

Policy as Code: Using code (e.g., OPA, Sentinel) to enforce security rules.

CIS Benchmarks: Industry standards for secure configuration that IaC scanning tools check against.

Common Trick Questions

"Which of the following is a benefit of IaC?" – Answer: Consistent deployments. Wrong: Faster manual configuration (manual is slower).

"What is the best way to handle secrets in IaC?" – Answer: Use a secrets management service. Wrong: Encrypt them in the file (still exposed in repo).

"What is immutable infrastructure?" – Answer: Servers are replaced, not patched. Wrong: Servers are never changed (they are replaced with new images).

Decision Rule for Eliminating Wrong Answers

On scenario questions, if the answer involves manually connecting to a server to fix it, it's likely wrong for IaC. Look for answers that involve rebuilding from a template, automated scanning, or pipeline changes. If the question mentions "configuration drift," the correct answer will involve detecting or preventing drift (e.g., using AWS Config or IaC tools).

Key Takeaways

IaC automates provisioning via code (e.g., Terraform, CloudFormation) and enables consistent, repeatable deployments.

Immutable infrastructure replaces servers instead of patching them, preventing drift and persistent attacks.

Secrets must never be hardcoded in IaC files; use a secrets manager like HashiCorp Vault or AWS Secrets Manager.

Use static analysis tools (Checkov, tfsec) to scan IaC files for misconfigurations before deployment.

Policy as Code (OPA, Sentinel) enforces security rules (e.g., 'S3 buckets must be private') at deployment time.

CI/CD pipelines for IaC should use least-privilege credentials and include automated scanning and approval gates.

Configuration drift is detected by tools like AWS Config or Azure Policy and should trigger alerts or automated remediation.

Golden images are hardened base images used for immutable deployments; they must be regularly updated and scanned.

Common misconfigurations include public S3 buckets, open security groups, and unencrypted data storage.

IaC is a key component of DevSecOps, integrating security into the development lifecycle.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Mutable Infrastructure

Servers are updated in-place via patches and upgrades.

Configuration drift is common over time.

Requires remote access (SSH/RDP) for maintenance.

Difficult to reproduce exact state for debugging.

Security patches are applied manually or via config management.

Immutable Infrastructure

Servers are never updated; replaced entirely with new versions.

No configuration drift; each instance is identical to the golden image.

No remote access to production instances; only logs are collected.

Easy to reproduce; deploy a new instance from the same image.

Security patches are applied by rebuilding the golden image and redeploying.

Watch Out for These

Mistake

IaC means you don't need to patch servers anymore.

Correct

You still need to patch the base images (golden images) used to create instances. Immutable infrastructure replaces instances with new ones built from updated images.

Mistake

IaC is only for cloud infrastructure.

Correct

IaC can be used for on-premises infrastructure via tools like Ansible, Puppet, or Terraform with providers for VMware or OpenStack.

Mistake

If IaC files are stored in a private repo, they are secure.

Correct

Private repos can still be accessed by insiders or compromised accounts. Secrets should never be stored in IaC files, even in private repos.

Mistake

Automated scanning of IaC files eliminates all misconfigurations.

Correct

Scanning reduces misconfigurations but cannot catch all issues, especially logic errors or complex policy violations. Human review and runtime monitoring are still needed.

Mistake

IaC and configuration management (e.g., Ansible) are the same.

Correct

IaC provisions infrastructure (VMs, networks), while configuration management installs and configures software on existing servers. They are complementary.

Frequently Asked Questions

What is the difference between IaC and configuration management?

IaC (Infrastructure as Code) provisions the underlying infrastructure (VMs, networks, storage) using declarative templates like Terraform or CloudFormation. Configuration management (e.g., Ansible, Chef, Puppet) installs and configures software on existing servers. They are often used together: IaC creates the server, then configuration management sets it up. For the exam, understand that IaC focuses on infrastructure provisioning, while config management focuses on software state.

How do you securely handle secrets in IaC?

Never hardcode secrets in IaC files. Use a secrets management tool like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault. In your IaC code, reference the secret by its identifier (e.g., `data.aws_secretsmanager_secret.example`). The secrets are injected at runtime, not stored in version control. Also, use environment variables or encrypted variables in CI/CD pipelines. Exam tip: If an answer suggests encrypting secrets in the file, it's still risky because the encrypted value could be decrypted if the key is compromised.

What is the purpose of a golden image in IaC?

A golden image is a pre-configured, hardened OS image (e.g., Amazon Machine Image, VM template) that includes security patches, required software, and security configurations. It is used to launch immutable instances. When a vulnerability is discovered, you update the golden image and redeploy, destroying old instances. This ensures all instances are identical and secure. For the exam, remember that golden images eliminate configuration drift and reduce the attack surface.

What tools are used to scan IaC for security issues?

Common tools include Checkov, tfsec, Terrascan, and Snyk IaC. These tools analyze Terraform, CloudFormation, Kubernetes YAML, and other IaC files against security best practices and CIS benchmarks. They can be integrated into CI/CD pipelines to block deployments with critical misconfigurations. On the exam, you may be asked to identify which tool is used for IaC scanning—look for names like 'Checkov' or 'tfsec'.

What is configuration drift and how do you prevent it?

Configuration drift occurs when the actual state of infrastructure deviates from the desired state defined in IaC files. This can happen due to manual changes, emergency fixes, or automated processes. To prevent drift, use immutable infrastructure (replace instead of modify), enforce policy as code (block changes that violate rules), and monitor with tools like AWS Config or Azure Policy that can detect and automatically remediate drift. On the exam, drift is a key reason to use IaC.

Can IaC be used for on-premises infrastructure?

Yes. Tools like Terraform have providers for VMware vSphere, OpenStack, and other on-premises platforms. Ansible and Puppet can also manage on-premises servers. IaC is not limited to cloud; it applies to any environment where infrastructure can be defined as code. However, the exam often focuses on cloud scenarios because that is where IaC is most commonly used.

What is the role of CI/CD in IaC security?

A secure CI/CD pipeline for IaC should include: (1) version control with branch protection, (2) automated scanning for misconfigurations and secrets, (3) peer review of pull requests, (4) policy as code enforcement, (5) least-privilege deployment credentials (e.g., OIDC), and (6) audit logging of all changes. The pipeline ensures that only approved, scanned, and policy-compliant code reaches production. Exam questions may ask about pipeline security controls.

Terms Worth Knowing

Ready to put this to the test?

You've just covered Infrastructure as Code Security — now see how well it sticks with free SY0-701 practice questions. Full explanations included, no account needed.

Done with this chapter?