Infrastructure as Code Security Review: Terraform and CloudFormation Best Practices

Infrastructure as Code (IaC) has revolutionized how we deploy and manage cloud resources, but it's also introduced new attack vectors. A single misconfigured Terraform resource or CloudFormation template can expose your entire infrastructure to security breaches. This comprehensive guide covers the essential security considerations every engineering team should implement when reviewing IaC configurations.
Key Takeaways
- •Shift security left: Implement IaC security scanning in your CI/CD pipeline to catch misconfigurations before they reach production.
- •Follow cloud security frameworks: Use CIS benchmarks, AWS Security Best Practices, and cloud-native security controls as your baseline.
- •Implement defense in depth: Combine automated scanning, manual review processes, and runtime monitoring for comprehensive security coverage.
Common IaC Security Anti-Patterns
Before diving into specific tools and techniques, it's crucial to understand the most common security mistakes that slip through IaC code reviews. These patterns appear consistently across both Terraform and CloudFormation configurations.
Critical Security Misconfigurations
🚫 High-Risk Patterns
- • Public S3 buckets with sensitive data
- • Security groups with 0.0.0.0/0 access
- • Unencrypted database instances
- • Hardcoded secrets in configuration
- • Overly permissive IAM policies
- • Missing access logging
- • Default encryption keys
- • Unrestricted admin access
✅ Security Best Practices
- • Least privilege access controls
- • Encryption at rest and in transit
- • Network segmentation
- • Secrets management integration
- • Comprehensive audit logging
- • Resource tagging strategy
- • Backup and disaster recovery
- • Multi-factor authentication
⚠️ Critical Review Focus
80% of cloud security incidents stem from misconfigurations, not vulnerabilities. Focus your review process on identifying and preventing these common patterns before deployment.
Terraform Security Review Checklist
Terraform's declarative syntax makes it powerful but also prone to security oversights. Here's a comprehensive checklist for reviewing Terraform configurations.
Provider and Backend Security
🔧 Terraform Backend Configuration
Terraform Security Examples
🚫 Insecure Terraform Patterns
# VULNERABLE - Public S3 bucket
resource "aws_s3_bucket" "data" {
bucket = "company-sensitive-data"
# Missing: bucket_public_access_block
}
# VULNERABLE - Overly permissive security group
resource "aws_security_group" "web" {
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # Open to world
}
}
# VULNERABLE - Hardcoded secret
resource "aws_db_instance" "main" {
password = "super-secret-password" # Should use secrets manager
}
✅ Secure Terraform Configuration
# SECURE - Properly configured S3 bucket
resource "aws_s3_bucket" "data" {
bucket = "company-sensitive-data"
}
resource "aws_s3_bucket_public_access_block" "data" {
bucket = aws_s3_bucket.data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
# SECURE - Restrictive security group with specific CIDR
resource "aws_security_group" "web" {
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["10.0.0.0/8"] # Internal network only
}
}
# SECURE - Using secrets manager
resource "aws_db_instance" "main" {
manage_master_user_password = true
# Password managed by AWS Secrets Manager
}
CloudFormation Security Review
AWS CloudFormation templates require different security considerations due to their JSON/YAML structure and tight integration with AWS services.
CloudFormation Security Patterns
🔍 Parameter Security
Use NoEcho for sensitive parameters and integrate with AWS Systems Manager Parameter Store for secrets management. Never store sensitive data in template parameters.
📋 Template Validation
Implement CloudFormation Guard rules for policy-as-code validation. Use cfn-lint for template syntax and best practice validation before deployment.
CloudFormation Security Examples
🚫 Insecure CloudFormation Template
Parameters:
DatabasePassword:
Type: String
Description: Database password
# MISSING: NoEcho: true
Resources:
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: my-public-bucket
# VULNERABLE: Missing PublicAccessBlockConfiguration
DatabaseInstance:
Type: AWS::RDS::DBInstance
Properties:
MasterUserPassword: !Ref DatabasePassword
# VULNERABLE: No encryption at rest
VPCSecurityGroups:
- !Ref DatabaseSecurityGroup
DatabaseSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 3306
ToPort: 3306
CidrIp: 0.0.0.0/0 # VULNERABLE: Open to world
✅ Secure CloudFormation Template
Parameters:
DatabasePassword:
Type: String
Description: Database password
NoEcho: true # SECURE: Hide in console
Resources:
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: my-private-bucket
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
DatabaseInstance:
Type: AWS::RDS::DBInstance
Properties:
ManageMasterUserPassword: true # SECURE: AWS manages password
StorageEncrypted: true # SECURE: Encryption at rest
VPCSecurityGroups:
- !Ref DatabaseSecurityGroup
DatabaseSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 3306
ToPort: 3306
SourceSecurityGroupId: !Ref WebSecurityGroup # SECURE: Reference other SG
IAM Security in IaC
Identity and Access Management (IAM) configurations are critical security components that require careful review. Overly permissive IAM policies are among the most common IaC security issues.
IAM Security Checklist
IAM Component | Security Requirements | Review Focus |
---|---|---|
Policies | Least privilege, specific resources | No wildcards (*) |
Roles | Trusted entities, session duration | Assume role conditions |
Users | MFA enforcement, no inline policies | Direct policy attachments |
Groups | Logical grouping, policy inheritance | Membership management |
IAM Policy Security Examples
🚫 Overly Permissive Policy
{
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}
✅ Least Privilege Policy
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/*"
}
Automated IaC Security Scanning
Manual reviews catch many issues, but automated scanning is essential for comprehensive security coverage and consistent policy enforcement across all infrastructure deployments.
Essential Security Scanning Tools
Checkov
Static analysis for Terraform and CloudFormation
• 1000+ built-in policies
• Custom policy creation
• CI/CD integration
• Multiple IaC formats
Terrascan
Policy engine for IaC security
• Multi-cloud support
• OPA integration
• Compliance frameworks
• Runtime scanning
tfsec
Terraform-specific security scanner
• Fast static analysis
• Detailed explanations
• Custom checks
• IDE integration
Implementing Automated Scanning in CI/CD
# GitHub Actions example
name: IaC Security Scan
on: [push, pull_request]
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Checkov
uses: bridgecrewio/checkov-action@master
with:
directory: ./terraform
framework: terraform
output_format: sarif
output_file_path: reports/results.sarif
- name: Run tfsec
run: |
docker run --rm -v $(pwd):/src aquasec/tfsec /src/terraform
- name: Upload results
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: reports/results.sarif
Network Security in IaC
Network configuration is often the most complex aspect of infrastructure security. Proper network segmentation and access controls are critical for defense in depth.
Network Security Patterns
VPC Configuration
Enable flow logs, use multiple AZs, implement proper CIDR planning
Security Groups
Specific port ranges, source/destination restrictions, regular audits
NACLs
Stateless filtering, subnet-level controls, allow/deny rules
Monitoring
VPC Flow Logs, CloudTrail, GuardDuty for network anomaly detection
Secrets Management in IaC
One of the most critical aspects of IaC security is proper secrets management. Hardcoded secrets in configuration files are a common source of security breaches.
Secure Secrets Management Approaches
🔐 AWS Solutions
- • AWS Secrets Manager
- • Systems Manager Parameter Store
- • IAM roles and policies
- • KMS encryption keys
- • Certificate Manager
🗝️ Third-Party Solutions
- • HashiCorp Vault
- • Azure Key Vault
- • Google Secret Manager
- • External Secrets Operator
- • Sealed Secrets
IaC Security Review Process
Establishing a consistent review process ensures that security considerations are systematically addressed in every infrastructure deployment.
Multi-Stage Review Process
📋 Complete Review Workflow
Building Security Culture in IaC
📚 Education & Training
- • Cloud security fundamentals
- • IaC security best practices
- • Tool-specific training
- • Regular security updates
- • Incident response drills
⚡ Continuous Improvement
- • Security metrics tracking
- • Regular process reviews
- • Tool effectiveness analysis
- • Feedback loops
- • Knowledge sharing sessions
🛡️ Secure infrastructure starts with secure code.
Automate Your Infrastructure Security Reviews
Propel's AI automatically scans your Terraform and CloudFormation files for security misconfigurations during code review.