Lesson 02 — Secure Infrastructure as Code (IaC)
Learning Path
☁️ Phase 02 – AWS Cloud Security
📘 Module 11 – DevSecOps & Infrastructure as Code (IaC) Security
🎯 Lesson Objective
Section titled “🎯 Lesson Objective”By the end of this lesson, you will be able to:
- Understand Infrastructure as Code (IaC).
- Explain the benefits of IaC.
- Deploy infrastructure using AWS CloudFormation.
- Build infrastructure using Terraform.
- Secure IaC templates.
- Detect Infrastructure Drift.
- Implement Change Management.
- Apply enterprise Infrastructure as Code best practices.
📚 Lesson Information
Estimated Time: 4 Hours
Difficulty: Intermediate–Advanced
Prerequisites: Lesson 01 – DevSecOps Fundamentals
Hands-on Labs: Yes
💼 Business Scenario
Section titled “💼 Business Scenario”CloudNova Technologies manages cloud infrastructure for over 250 enterprise applications deployed across multiple AWS Regions.
The infrastructure includes:
- 3,000 Amazon EC2 Instances
- Amazon VPCs
- Security Groups
- IAM Roles
- Amazon RDS Databases
- Amazon EKS Clusters
- Amazon S3 Buckets
- AWS Lambda Functions
Initially, engineers created infrastructure manually using the AWS Console.
As the company expanded, several problems appeared.
- Different environments had inconsistent configurations.
- Security Groups allowed unrestricted internet access.
- IAM permissions differed between environments.
- Developers accidentally modified production resources.
- Manual deployments became slow and error-prone.
- Disaster Recovery environments were inconsistent.
The CTO asks:
“Can we build our entire AWS infrastructure automatically while ensuring every deployment follows security standards?”
As the Cloud Security Engineer, your responsibility is to implement secure Infrastructure as Code practices.
Why Infrastructure as Code?
Section titled “Why Infrastructure as Code?”Modern cloud environments contain thousands of resources.
Managing them manually leads to:
- Human error
- Configuration drift
- Slow deployments
- Poor documentation
- Security inconsistencies
- Difficult recovery
Infrastructure as Code solves these challenges by defining infrastructure using version-controlled code.
What is Infrastructure as Code?
Section titled “What is Infrastructure as Code?”Infrastructure as Code (IaC) is the practice of provisioning and managing infrastructure through code rather than manual configuration.
Instead of clicking through the AWS Console, engineers define infrastructure using templates.
Example:
Developer
↓
Infrastructure Code
↓
Validation
↓
Deployment
↓
AWS ResourcesInfrastructure becomes repeatable, consistent and auditable.
Benefits of IaC
Section titled “Benefits of IaC”CloudNova adopted Infrastructure as Code because it provides:
- Automation
- Consistency
- Repeatability
- Version Control
- Disaster Recovery
- Faster Deployments
- Reduced Human Error
- Easier Auditing
- Infrastructure Documentation
Traditional vs IaC
Section titled “Traditional vs IaC”Traditional Deployment
Section titled “Traditional Deployment”AWS Console
↓
Manual Configuration
↓
Human Error
↓
ProductionProblems:
- Inconsistent environments
- Difficult rollback
- Manual documentation
- Security issues
Infrastructure as Code
Section titled “Infrastructure as Code”Git Repository
↓
CloudFormation / Terraform
↓
Code Review
↓
Security Validation
↓
AWS DeploymentBenefits:
- Repeatable
- Automated
- Secure
- Version Controlled
Enterprise IaC Workflow
Section titled “Enterprise IaC Workflow”CloudNova follows this deployment lifecycle.
Planning
↓
Write Template
↓
Commit to Git
↓
Pull Request
↓
Code Review
↓
IaC Security Scan
↓
Validation
↓
Approval
↓
Deployment
↓
MonitoringEvery infrastructure change follows the same controlled process.
Infrastructure as Code Tools
Section titled “Infrastructure as Code Tools”CloudNova uses multiple IaC technologies.
| Tool | Purpose |
|---|---|
| AWS CloudFormation | Native AWS Infrastructure |
| Terraform | Multi-Cloud Infrastructure |
| AWS CDK | Infrastructure using programming languages |
| Helm | Kubernetes deployments |
| Kubernetes YAML | Container orchestration |
AWS CloudFormation
Section titled “AWS CloudFormation”AWS CloudFormation is AWS’s native Infrastructure as Code service.
CloudFormation templates define:
- VPCs
- EC2
- IAM
- Security Groups
- RDS
- S3
- Lambda
- Route 53
Deployment process:
Template
↓
CloudFormation Stack
↓
AWS ResourcesCloudFormation Template Structure
Section titled “CloudFormation Template Structure”Every CloudFormation template typically contains:
Version
↓
Description
↓
Parameters
↓
Mappings
↓
Conditions
↓
Resources
↓
OutputsThis structure makes templates reusable and maintainable.
Example CloudFormation
Section titled “Example CloudFormation”AWSTemplateFormatVersion: "2010-09-09"
Description: Secure S3 Bucket
Resources:
SecureBucket:
Type: AWS::S3::Bucket
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256Notice that encryption is enabled by default.
Terraform
Section titled “Terraform”Terraform is an Infrastructure as Code platform developed by HashiCorp.
It allows organisations to provision resources across multiple cloud providers.
CloudNova uses Terraform because:
- Multi-cloud support
- Modular architecture
- Large provider ecosystem
- Version-controlled deployments
Terraform Workflow
Section titled “Terraform Workflow”Terraform Code
↓
terraform fmt
↓
terraform validate
↓
terraform plan
↓
Security Scan
↓
terraform apply
↓
AWS InfrastructureSecurity validation occurs before deployment.
Example Terraform
Section titled “Example Terraform”resource "aws_s3_bucket" "secure_bucket" {
bucket = "cloudnova-secure"
}In production environments, encryption, versioning and access controls would also be defined.
Git Version Control
Section titled “Git Version Control”Every infrastructure template is stored in Git.
Benefits include:
- Version History
- Rollback
- Pull Requests
- Peer Review
- Change Tracking
- Audit Trail
No infrastructure changes are made directly in production.
Infrastructure Drift
Section titled “Infrastructure Drift”Infrastructure Drift occurs when deployed resources no longer match the Infrastructure as Code templates.
Example:
Terraform
↓
Security Group
↓
Administrator manually changes rule
↓
Configuration DriftDrift creates:
- Compliance failures
- Security risks
- Operational issues
Detecting Drift
Section titled “Detecting Drift”CloudNova regularly checks for drift.
Methods include:
- CloudFormation Drift Detection
- Terraform Plan
- AWS Config
- AWS Config Rules
- Security Hub
Early detection prevents unexpected configuration changes.
Secure IaC Principles
Section titled “Secure IaC Principles”Every Infrastructure as Code template should:
✔ Enable encryption.
✔ Follow least privilege.
✔ Avoid hardcoded secrets.
✔ Enable logging.
✔ Use secure defaults.
✔ Require approvals.
✔ Be version controlled.
✔ Be security scanned before deployment.
Change Management
Section titled “Change Management”Infrastructure changes follow an enterprise approval process.
Developer
↓
Pull Request
↓
Peer Review
↓
Security Review
↓
Approval
↓
Deployment
↓
MonitoringEmergency changes require executive approval.
Enterprise IaC Architecture
Section titled “Enterprise IaC Architecture” Developer │ Git Repository │ Pull Request │ Code Review │ IaC Security Scanner │ ┌───────────────┼────────────────┐ │ │ │CloudFormation Terraform Policy Validation │ │ │ └───────────────┼────────────────┘ │ Deployment Pipeline │ AWS Infrastructure │ AWS Config • CloudTrail • Security HubEnterprise Best Practices
Section titled “Enterprise Best Practices”CloudNova standards include:
- Store every template in Git.
- Never deploy infrastructure manually.
- Require Pull Requests.
- Require peer reviews.
- Validate every template before deployment.
- Scan Infrastructure as Code for vulnerabilities.
- Encrypt all storage resources.
- Enable logging by default.
- Detect infrastructure drift regularly.
- Review infrastructure changes through Change Management.
🛠 Lab 01 — Deploy a CloudFormation Stack
Section titled “🛠 Lab 01 — Deploy a CloudFormation Stack”Objective:
Deploy a secure S3 bucket.
Tasks:
- Create a CloudFormation template.
- Enable bucket encryption.
- Enable versioning.
- Deploy the stack.
- Verify successful deployment.
🛠 Lab 02 — Deploy Infrastructure with Terraform
Section titled “🛠 Lab 02 — Deploy Infrastructure with Terraform”Create:
- VPC
- Security Group
- EC2 Instance
Run:
terraform initterraform validateterraform planterraform applyVerify that resources are created successfully.
🛠 Lab 03 — Detect Infrastructure Drift
Section titled “🛠 Lab 03 — Detect Infrastructure Drift”Modify an AWS Security Group manually using the AWS Console.
Then:
- Run CloudFormation Drift Detection or
- Execute:
terraform planDocument the detected differences.
🛠 Lab 04 — Review an IaC Template
Section titled “🛠 Lab 04 — Review an IaC Template”Review an existing template and identify:
- Public Security Groups
- Unencrypted Storage
- Excessive IAM Permissions
- Missing Logging
- Missing Tags
Recommend improvements.
🛠 Lab 05 — Secure an Existing Template
Section titled “🛠 Lab 05 — Secure an Existing Template”Update the template to include:
- Encryption
- Versioning
- IAM Least Privilege
- Logging
- Tags
- Secure Defaults
Validate before deployment.
💻 AWS CLI Lab
Section titled “💻 AWS CLI Lab”Validate CloudFormation Template
Section titled “Validate CloudFormation Template”aws cloudformation validate-template \--template-body file://template.yamlList CloudFormation Stacks
Section titled “List CloudFormation Stacks”aws cloudformation list-stacksDescribe Stack Resources
Section titled “Describe Stack Resources”aws cloudformation describe-stack-resources \--stack-name SecureStackDetect Drift
Section titled “Detect Drift”aws cloudformation detect-stack-drift \--stack-name SecureStackDescribe Drift Detection Status
Section titled “Describe Drift Detection Status”aws cloudformation describe-stack-drift-detection-status \--stack-drift-detection-id DRIFT_IDList Terraform State
Section titled “List Terraform State”terraform state list✅ Verification
Section titled “✅ Verification”Verify that you can:
✔ Explain Infrastructure as Code.
✔ Differentiate CloudFormation and Terraform.
✔ Deploy infrastructure using templates.
✔ Detect configuration drift.
✔ Secure Infrastructure as Code.
✔ Apply enterprise Change Management.
✔ Explain secure deployment workflows.
🔍 Troubleshooting
Section titled “🔍 Troubleshooting”Problem
Section titled “Problem”CloudFormation deployment fails.
Verify:
- Template syntax.
- IAM permissions.
- Resource dependencies.
- Parameter values.
Problem
Section titled “Problem”Terraform plan shows unexpected changes.
Review:
- State file.
- Manual infrastructure changes.
- Provider version.
- Variable values.
Problem
Section titled “Problem”Infrastructure Drift detected.
Verify:
- Manual configuration changes.
- AWS Config findings.
- CloudFormation Drift results.
- Terraform state consistency.
🚫 Common Mistakes
Section titled “🚫 Common Mistakes”❌ Creating infrastructure manually.
❌ Hardcoding secrets in templates.
❌ Deploying without validation.
❌ Ignoring drift detection.
❌ Not using version control.
❌ Granting AdministratorAccess by default.
❌ Deploying directly to production without review.
🧪 DIY Challenge
Section titled “🧪 DIY Challenge”CloudNova is launching a new production environment.
Design a secure Infrastructure as Code solution that includes:
- Secure VPC.
- Private and Public Subnets.
- IAM Roles.
- Encrypted S3 Buckets.
- Amazon EC2.
- Amazon RDS.
- CloudTrail.
- CloudWatch.
- Security Groups.
- Infrastructure Validation Pipeline.
Prepare:
- CloudFormation Template
- Terraform Project
- Architecture Diagram
- Deployment Workflow
- Change Management Plan
📊 Knowledge Check
Section titled “📊 Knowledge Check”- What is Infrastructure as Code?
- Why is IaC preferred over manual deployments?
- What is AWS CloudFormation?
- What is Terraform?
- What is Infrastructure Drift?
- Why should templates be stored in Git?
- Why should Infrastructure as Code be security scanned?
- Why are Pull Requests important?
- What is Change Management?
- How does Infrastructure as Code improve cloud security?
💡 Key Takeaways
Section titled “💡 Key Takeaways”After completing this lesson, you should understand:
- Infrastructure as Code enables organisations to provision and manage cloud infrastructure through version-controlled, repeatable templates instead of manual configuration.
- AWS CloudFormation and Terraform are widely used IaC tools that support automated deployments, consistency and disaster recovery.
- Secure IaC practices include encryption by default, least privilege IAM, logging, version control, template validation and automated security scanning.
- Infrastructure Drift can introduce compliance and security risks, making continuous drift detection and remediation essential.
- Enterprise deployment processes combine Git-based workflows, peer reviews, security validation and change management to ensure infrastructure changes are secure, auditable and reliable.
🚀 Next Lesson
Section titled “🚀 Next Lesson”➡️ Lesson 03 — CI/CD Pipeline Security