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 MalformedPolicyDocument errors when creating IAM roles in Terraform. Fix assume role policies, trust relationships, and JSON syntax.
Error creating IAM Role: MalformedPolicyDocument: Invalid principal in policyThe IAM assume role policy (trust relationship) contains invalid JSON, references a non-existent principal, or has syntax errors. Common mistakes include using the wrong ARN format, missing quotes, or referencing deleted accounts/services.
# BAD — common mistakes
resource "aws_iam_role" "lambda" {
name = "lambda-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda" # Wrong! Missing .amazonaws.com
}
}]
})
}
# GOOD — correct service principal
resource "aws_iam_role" "lambda" {
name = "lambda-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com" # Correct!
}
}]
})
}# Check your policy is valid JSON
terraform console
> jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "ec2.amazonaws.com" }
Action = "sts:AssumeRole"
}]
})# Lambda: lambda.amazonaws.com
# EC2: ec2.amazonaws.com
# ECS Tasks: ecs-tasks.amazonaws.com
# API Gateway: apigateway.amazonaws.com
# CloudWatch: events.amazonaws.com
# S3: s3.amazonaws.com
# SNS: sns.amazonaws.com
# CodeBuild: codebuild.amazonaws.com
# CodePipeline: codepipeline.amazonaws.comresource "aws_iam_role" "cross_account" {
name = "cross-account-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = {
AWS = "arn:aws:iam::123456789012:root" # Account ID must exist!
}
Action = "sts:AssumeRole"
}]
})
}terraform 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.