Fix Terraform Error: CloudWatch Log Group Already Exists
Fix terraform CloudWatch Log Group ResourceAlreadyExistsException. Import orphaned log groups, prevent Lambda auto-creation
DevOps
How to fix MalformedPolicy errors when applying S3 bucket policies in Terraform. Debug JSON syntax, ARN format, and principal issues.
Error putting S3 policy: MalformedPolicy: Invalid principal in policyThe S3 bucket policy has invalid JSON, incorrect ARN format, or references a principal that doesn't exist. This also happens when the policy is too large (20KB limit) or has conflicting statements.
# BAD — heredoc is error-prone
resource "aws_s3_bucket_policy" "public" {
bucket = aws_s3_bucket.web.id
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-bucket/*"
}]
}
EOF
}
# GOOD — jsonencode catches errors at plan time
resource "aws_s3_bucket_policy" "public" {
bucket = aws_s3_bucket.web.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Sid = "PublicRead"
Effect = "Allow"
Principal = "*"
Action = "s3:GetObject"
Resource = "${aws_s3_bucket.web.arn}/*"
}]
})
}resource "aws_s3_bucket_policy" "cdn" {
bucket = aws_s3_bucket.web.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Sid = "AllowCloudFront"
Effect = "Allow"
Principal = {
Service = "cloudfront.amazonaws.com"
}
Action = "s3:GetObject"
Resource = "${aws_s3_bucket.web.arn}/*"
Condition = {
StringEquals = {
"AWS:SourceArn" = aws_cloudfront_distribution.cdn.arn
}
}
}]
})
}# Test the policy before applying
aws s3api put-bucket-policy \
--bucket my-bucket \
--policy file://policy.json \
--dry-run # Not supported, but you can validate the JSON
# Check existing policy
aws s3api get-bucket-policy --bucket my-bucket | python3 -m json.toolterraform plan — always review before applyingterraform validate — catches syntax errors earlyLearn to avoid these errors with interactive, project-based courses:
Related: Fix the Terraform inconsistent dependency lock file error — quick fix for this common issue.
This error is common and fixable. Follow the solutions above, and check our Terraform course for hands-on training that covers real-world troubleshooting scenarios.
Fix terraform CloudWatch Log Group ResourceAlreadyExistsException. Import orphaned log groups, prevent Lambda auto-creation
Fix terraform import errors when a resource already exists in state. Covers state rm, state show, reimport workflow, import blocks
Fix terraform too many command line arguments errors. Correct -var syntax, quote values with spaces, and learn proper Terraform CLI argument format for plan
Fix terraform invalid escape sequence errors. Double backslashes for Windows paths, use heredocs for regex, and learn all valid HCL escape sequences.