CloudFormation Security
AWS IaC Security 2026
Stack Policies, Drift Detection, Service Roles, Secrets Management & Compliance
Stack PolicyDrift DetectionService RoleStackSets
CloudFormation Security Architecture
CloudFormation Stacks können komplette AWS-Umgebungen erstellen oder zerstören. Ohne Security könnten Stacks ungewollt gelöscht oder modifiziert werden. Stack Policies, Service Roles und Drift Detection sind essentiell.
Stack Protection
- • Stack Policies
- • Termination Protection
- • Change Sets
- • Rollback Configuration
Access Control
- • Service Roles
- • IAM Permissions
- • SCP Restrictions
- • Cross-Account
Governance
- • Drift Detection
- • StackSets
- • Hook Policies
- • Config Rules
Stack Policy (Prevent Deletion)
# production-stack-policy.json - Prevent Resource Modification
{
"Statement": [
{
"Effect": "Deny",
"Action": [
"Update:Delete",
"Update:Replace"
],
"Principal": "*",
"Resource": "LogicalResourceId/ProductionDatabase",
"Condition": {
"StringEquals": {
"ResourceType": [
"AWS::RDS::DBInstance",
"AWS::RDS::DBCluster"
]
}
}
},
{
"Effect": "Deny",
"Action": [
"Update:Delete",
"Update:Replace"
],
"Principal": "*",
"Resource": "LogicalResourceId/ProductionVPC",
"Condition": {
"StringEquals": {
"ResourceType": [
"AWS::EC2::VPC",
"AWS::EC2::Subnet",
"AWS::EC2::RouteTable"
]
}
}
},
{
"Effect": "Deny",
"Action": [
"Update:Delete",
"Update:Replace"
],
"Principal": "*",
"Resource": "LogicalResourceId/VaultKMSKey",
"Condition": {
"StringEquals": {
"ResourceType": [
"AWS::KMS::Key"
]
}
}
},
{
"Effect": "Deny",
"Action": [
"Update:*"
],
"Principal": "*",
"Resource": "LogicalResourceId/S3DataBucket",
"Condition": {
"StringEquals": {
"ResourceType": [
"AWS::S3::Bucket"
]
},
"StringNotEquals": {
"ResourcePropertyDifference.Types": ["Add"] # Only allow additions
}
}
},
{
"Effect": "Allow",
"Action": "Update:*",
"Principal": "*",
"Resource": "*"
}
]
}
# Apply Stack Policy
aws cloudformation set-stack-policy \
--stack-name production-infrastructure \
--stack-policy-body file://production-stack-policy.json
# Or during stack creation
aws cloudformation create-stack \
--stack-name production-infrastructure \
--template-body file://template.yaml \
--stack-policy-body file://production-stack-policy.json \
--enable-termination-protectionCloudFormation Service Role
# cloudformation-service-role.yaml - Least Privilege Role
AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation Service Role with Minimal Permissions
Resources:
CloudFormationServiceRole:
Type: AWS::IAM::Role
Properties:
RoleName: CloudFormation-Deployment-Role
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: cloudformation.amazonaws.com
Action: sts:AssumeRole
Condition:
StringEquals:
aws:SourceAccount: !Ref AWS::AccountId
# Inline Policies (least privilege)
Policies:
- PolicyName: EC2Permissions
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: VPCReadOnly
Effect: Allow
Action:
- ec2:DescribeVpcs
- ec2:DescribeSubnets
- ec2:DescribeSecurityGroups
Resource: "*"
- Sid: SpecificVPCModify
Effect: Allow
Action:
- ec2:CreateSecurityGroup
- ec2:DeleteSecurityGroup
- ec2:AuthorizeSecurityGroupIngress
- ec2:RevokeSecurityGroupIngress
Resource:
- !Sub "arn:aws:ec2:$${AWS::Region}:$${AWS::AccountId}:vpc/vpc-*"
- !Sub "arn:aws:ec2:$${AWS::Region}:$${AWS::AccountId}:security-group/*"
Condition:
StringEquals:
ec2:Vpc: !ImportValue ProductionVPC
- PolicyName: S3Permissions
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: SpecificBucketOnly
Effect: Allow
Action:
- s3:CreateBucket
- s3:DeleteBucket
- s3:PutBucketPolicy
- s3:PutBucketEncryption
- s3:PutBucketVersioning
Resource:
- !Sub "arn:aws:s3:::company-data-$${AWS::AccountId}-*"
- !Sub "arn:aws:s3:::company-data-$${AWS::AccountId}-*/*"
- PolicyName: RDSPermissions
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: RDSModifyOnly
Effect: Allow
Action:
- rds:CreateDBInstance
- rds:ModifyDBInstance
- rds:DeleteDBInstance
Resource:
- !Sub "arn:aws:rds:$${AWS::Region}:$${AWS::AccountId}:db:production-*"
Condition:
StringEquals:
rds:Vpc: !ImportValue ProductionVPC
- PolicyName: DenyDangerous
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: DenyIAMChanges
Effect: Deny
Action:
- iam:CreateUser
- iam:DeleteUser
- iam:CreateAccessKey
- iam:DeleteAccountPasswordPolicy
Resource: "*"
- Sid: DenyOrgChanges
Effect: Deny
Action:
- organizations:LeaveOrganization
- organizations:DeleteOrganization
Resource: "*"
# Permission Boundaries
PermissionsBoundary: !Ref CloudFormationPermissionsBoundary
CloudFormationPermissionsBoundary:
Type: AWS::IAM::ManagedPolicy
Properties:
ManagedPolicyName: CloudFormation-Permissions-Boundary
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ec2:*
- s3:*
- rds:*
- elasticloadbalancing:*
Resource: "*"
Condition:
StringEquals:
aws:RequestedRegion:
- !Ref AWS::Region
- Effect: Deny
Action:
- iam:*
- organizations:*
- account:*
Resource: "*"
# Use the service role
aws cloudformation create-stack \
--stack-name production-infrastructure \
--template-body file://template.yaml \
--role-arn arn:aws:iam::123456789:role/CloudFormation-Deployment-RoleDrift Detection & Remediation
# Lambda - Automated Drift Detection & Remediation
import boto3
import json
from datetime import datetime, timedelta
def lambda_handler(event, context):
cf = boto3.client('cloudformation')
sns = boto3.client('sns')
# Get production stacks
stacks = cf.list_stacks(
StackStatusFilter=['CREATE_COMPLETE', 'UPDATE_COMPLETE']
)
drift_detected = []
for stack in stacks['StackSummaries']:
stack_name = stack['StackName']
# Skip non-production stacks
if 'production' not in stack_name.lower():
continue
# Detect drift
drift_response = cf.detect_stack_drift(StackName=stack_name)
drift_id = drift_response['StackDriftDetectionId']
# Wait for detection (poll)
waiter = cf.get_waiter('stack_drift_detection_complete')
waiter.wait(StackDriftDetectionId=drift_id)
# Get drift status
drift_status = cf.describe_stack_drift_detection_status(
StackDriftDetectionId=drift_id
)
if drift_status['StackDriftStatus'] == 'DRIFTED':
drifted_resources = cf.describe_stack_resource_drifts(
StackName=stack_name,
StackResourceDriftStatusFilters=['MODIFIED', 'DELETED', 'NOT_CHECKED']
)
drift_detected.append({
'StackName': stack_name,
'DriftId': drift_id,
'DriftedResources': len(drifted_resources['StackResourceDrifts']),
'Resources': [
{
'LogicalId': r['LogicalResourceId'],
'Type': r['ResourceType'],
'Status': r['StackResourceDriftStatus'],
'PropertyDifferences': r.get('PropertyDifferences', [])
}
for r in drifted_resources['StackResourceDrifts']
]
})
# Auto-remediate specific resources
for resource in drifted_resources['StackResourceDrifts']:
if resource['StackResourceDriftStatus'] == 'MODIFIED':
logical_id = resource['LogicalResourceId']
# Only auto-remediate safe resources
if resource['ResourceType'] in ['AWS::EC2::SecurityGroup', 'AWS::IAM::Role']:
# Create change set to remediate
change_set = cf.create_change_set(
StackName=stack_name,
ChangeSetName=f"drift-remediation-{datetime.now().strftime('%Y%m%d%H%M%S')}",
ChangeSetType='UPDATE',
UsePreviousTemplate=True,
Capabilities=['CAPABILITY_IAM']
)
# Auto-execute for approved resources
cf.execute_change_set(
ChangeSetName=change_set['Id'],
StackName=stack_name
)
# Send alert if drift detected
if drift_detected:
sns.publish(
TopicArn='arn:aws:sns:us-east-1:123456789:security-alerts',
Subject='CloudFormation Drift Detected',
Message=json.dumps(drift_detected, indent=2, default=str)
)
return {
'statusCode': 200,
'body': json.dumps({
'StacksChecked': len(stacks['StackSummaries']),
'DriftDetected': len(drift_detected),
'Details': drift_detected
})
}
# CloudWatch Event Rule for scheduled drift detection
# EventBridge Rule: Daily at 2 AM
{
"source": ["aws.events"],
"detail-type": ["Scheduled Event"],
"resources": ["arn:aws:events:us-east-1:123456789:rule/daily-drift-check"]
}StackSets for Multi-Account Governance
# stackset-administration.yaml - Multi-Account StackSet
AWSTemplateFormatVersion: '2010-09-09'
Description: Security Baseline StackSet for All Accounts
Parameters:
TargetOUID:
Type: String
Description: AWS Organizations OU ID
Resources:
SecurityBaselineStackSet:
Type: AWS::CloudFormation::StackSet
Properties:
StackSetName: security-baseline
Description: Security baseline for all accounts
PermissionModel: SERVICE_MANAGED # Use Organizations
AutoDeployment:
Enabled: true
RetainStacksOnAccountRemoval: false
TemplateURL: https://s3.amazonaws.com/company-templates/security-baseline.yaml
Parameters:
- ParameterKey: EnableGuardDuty
ParameterValue: "true"
- ParameterKey: EnableCloudTrail
ParameterValue: "true"
- ParameterKey: EnableConfig
ParameterValue: "true"
StackInstancesGroup:
- DeploymentTargets:
OrganizationalUnitIds:
- !Ref TargetOUID
Regions:
- us-east-1
- us-west-2
- eu-west-1
- eu-central-1
OperationPreferences:
FailureToleranceCount: 1
MaxConcurrentCount: 5
RegionConcurrencyType: PARALLEL
Capabilities:
- CAPABILITY_IAM
- CAPABILITY_AUTO_EXPAND
# StackSet Instance with Service Role
StackSetInstance:
Type: AWS::CloudFormation::StackSet
Properties:
StackSetName: network-baseline
TemplateURL: https://s3.amazonaws.com/company-templates/vpc-baseline.yaml
ExecutionRoleName: AWSCloudFormationStackSetExecutionRole
AdministrationRoleARN: !Sub "arn:aws:iam::$${ManagementAccountId}:role/AWSCloudFormationStackSetAdministrationRole"
StackInstancesGroup:
- DeploymentTargets:
Accounts:
- "123456789012"
- "123456789013"
Regions:
- us-east-1
OperationPreferences:
FailureTolerancePercentage: 20
MaxConcurrentPercentage: 50