Fix Terraform Error: CloudWatch Log Group Already Exists
Fix terraform CloudWatch Log Group ResourceAlreadyExistsException. Import orphaned log groups, prevent Lambda auto-creation
DevOps
Fix ResourceAlreadyExistsException when creating CloudWatch Log Groups in Terraform. Import existing groups, handle retention policies, and prevent name...
A CloudWatch Log Group with that name already exists. Import it with terraform import aws_cloudwatch_log_group.main /my/log/group, or use a unique name. Many AWS services auto-create log groups — check before creating them in Terraform.
Error: creating CloudWatch Log Group (/ecs/my-app):
ResourceAlreadyExistsException: The specified log group already existsterraform import aws_cloudwatch_log_group.app /ecs/my-appFor Lambda and ECS, you can let AWS auto-create the log group and just manage retention:
# Instead of creating the log group, import it after first deployment
# Or use data source to reference it
data "aws_cloudwatch_log_group" "lambda" {
name = "/aws/lambda/${aws_lambda_function.main.function_name}"
}# Create log group BEFORE the Lambda/ECS resource
resource "aws_cloudwatch_log_group" "lambda" {
name = "/aws/lambda/${var.function_name}"
retention_in_days = 30
# Create before Lambda so Terraform owns it
lifecycle {
create_before_destroy = true
}
}
resource "aws_lambda_function" "main" {
depends_on = [aws_cloudwatch_log_group.lambda]
function_name = var.function_name
# ...
}resource "aws_cloudwatch_log_group" "app" {
name = "/${var.project}/${var.environment}/app"
retention_in_days = 14
tags = { Environment = var.environment }
}| AWS Service | Log Group Pattern |
|---|---|
| Lambda | /aws/lambda/<function-name> |
| ECS | /ecs/<service-name> (if configured) |
| API Gateway | /aws/apigateway/<api-id> |
| RDS | /aws/rds/instance/<id>/<log-type> |
| VPC Flow Logs | Custom name |
| CodeBuild | /aws/codebuild/<project-name> |
aws logs describe-log-groups --log-group-name-prefix /ecs/my-app)CloudWatch Log Groups often already exist because AWS services auto-create them. Import existing groups into Terraform state, or create them before the service that uses them. Set retention_in_days to avoid unlimited log storage costs.
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.