Terraform 1.4.3: how to to Use `locals` for Conditional Resource Count Based on S3 Bucket Metrics
I'm working on a personal project and I've encountered a strange issue with Quick question that's been bugging me - I'm working with an scenario while trying to conditionally create resources based on the metrics of an S3 bucket using Terraform 1.4.3... Specifically, I want to create an alarm in CloudWatch only if the S3 bucket has a certain number of objects. I'm attempting to use `locals` to define a threshold and then use that in the resource count, but I keep running into a `plan` behavior. Hereβs what I have: ```hcl locals { object_count = aws_s3_bucket.my_bucket.object_count threshold = 100 # only create alarm if there are more than 100 objects } resource "aws_cloudwatch_metric_alarm" "s3_alarm" { count = local.object_count > local.threshold ? 1 : 0 alarm_name = "HighObjectCount" metric_name = "NumberOfObjects" namespace = "AWS/S3" statistic = "Average" period = 60 evaluation_periods = 1 threshold = local.threshold comparison_operator = "GreaterThanThreshold" dimensions = { BucketName = aws_s3_bucket.my_bucket.bucket } } ``` When I run `terraform plan`, I receive this behavior: ``` behavior: Invalid count argument on main.tf line 10, in resource "aws_cloudwatch_metric_alarm" "s3_alarm": 10: count = local.object_count > local.threshold ? 1 : 0 The argument must be a whole number, not a string. ``` I've tried to verify the data type of `local.object_count`, and it looks like it is being interpreted as a string instead of a number. I've also attempted to cast it using `tonumber(local.object_count)` but that did not resolve the scenario. Is there a different approach I can take to ensure this count works correctly? Any advice on how to reference the S3 bucket metrics properly would be greatly appreciated! For context: I'm using Hcl on Windows. How would you solve this?