From ebe6f0972c683401a8401d2cb0ebc011b6a92b82 Mon Sep 17 00:00:00 2001 From: Bert Blommers Date: Sat, 29 Oct 2022 15:41:29 +0000 Subject: [PATCH] CloudWatch: Ensure we can tag new Alarms that are currently tag-free (#5614) --- moto/cloudwatch/models.py | 5 ++++- tests/test_cloudwatch/test_cloudwatch_tags.py | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/moto/cloudwatch/models.py b/moto/cloudwatch/models.py index 189b55212..7f78edf95 100644 --- a/moto/cloudwatch/models.py +++ b/moto/cloudwatch/models.py @@ -665,7 +665,10 @@ class CloudWatchBackend(BaseBackend): return self.tagger.get_tag_dict_for_resource(arn) def tag_resource(self, arn, tags): - if arn not in self.tagger.tags.keys(): + # From boto3: + # Currently, the only CloudWatch resources that can be tagged are alarms and Contributor Insights rules. + all_arns = [alarm.alarm_arn for alarm in self.get_all_alarms()] + if arn not in all_arns: raise ResourceNotFoundException self.tagger.tag_resource(arn, tags) diff --git a/tests/test_cloudwatch/test_cloudwatch_tags.py b/tests/test_cloudwatch/test_cloudwatch_tags.py index dddab423c..97ccd2ab1 100644 --- a/tests/test_cloudwatch/test_cloudwatch_tags.py +++ b/tests/test_cloudwatch/test_cloudwatch_tags.py @@ -102,6 +102,28 @@ def test_tag_resource(): ) +@mock_cloudwatch +def test_tag_resource_on_resource_without_tags(): + cw = boto3.client("cloudwatch", region_name="eu-central-1") + cw.put_metric_alarm( + AlarmName="testalarm", + EvaluationPeriods=1, + ComparisonOperator="GreaterThanThreshold", + Period=60, + MetricName="test", + Namespace="test", + ) + alarms = cw.describe_alarms() + alarm_arn = alarms["MetricAlarms"][0]["AlarmArn"] + + # List 0 tags - none have been added + cw.list_tags_for_resource(ResourceARN=alarm_arn)["Tags"].should.equal([]) + + # Tag the Alarm for the first time + cw.tag_resource(ResourceARN=alarm_arn, Tags=[{"Key": "tk", "Value": "tv"}]) + assert len(cw.list_tags_for_resource(ResourceARN=alarm_arn)["Tags"]) == 1 + + @mock_cloudwatch def test_tag_resource_error_not_exists(): # given