From 5d7d096bed08cc64b87b6dece96bfc52414431c9 Mon Sep 17 00:00:00 2001 From: Bert Blommers Date: Sat, 25 Feb 2023 10:19:28 -0100 Subject: [PATCH] EC2: describe_instances() should be able to filter by exact tag-values (#5980) --- moto/ec2/utils.py | 2 ++ tests/test_ec2/test_instances.py | 21 +++++++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/moto/ec2/utils.py b/moto/ec2/utils.py index b633bf9c9..3e0e609bc 100644 --- a/moto/ec2/utils.py +++ b/moto/ec2/utils.py @@ -395,6 +395,8 @@ def tag_filter_matches(obj: Any, filter_name: str, filter_values: List[str]) -> for tag_value in tag_values: if any(regex.match(tag_value) for regex in regex_filters): return True + if tag_value in filter_values: + return True return False diff --git a/tests/test_ec2/test_instances.py b/tests/test_ec2/test_instances.py index 0c670c80b..491baa9e7 100644 --- a/tests/test_ec2/test_instances.py +++ b/tests/test_ec2/test_instances.py @@ -1,5 +1,6 @@ import base64 import ipaddress +import json import warnings from unittest import SkipTest, mock from uuid import uuid4 @@ -769,9 +770,15 @@ def test_get_instances_filtering_by_tag(): tag1_val = str(uuid4()) tag2_name = str(uuid4())[0:6] tag2_val = str(uuid4()) + tag3_name = str(uuid4())[0:6] - instance1.create_tags(Tags=[{"Key": tag1_name, "Value": tag1_val}]) - instance1.create_tags(Tags=[{"Key": tag2_name, "Value": tag2_val}]) + instance1.create_tags( + Tags=[ + {"Key": tag1_name, "Value": tag1_val}, + {"Key": tag2_name, "Value": tag2_val}, + {"Key": tag3_name, "Value": json.dumps(["entry1", "entry2"])}, + ] + ) instance2.create_tags(Tags=[{"Key": tag1_name, "Value": tag1_val}]) instance2.create_tags(Tags=[{"Key": tag2_name, "Value": "wrong value"}]) instance3.create_tags(Tags=[{"Key": tag2_name, "Value": tag2_val}]) @@ -812,6 +819,16 @@ def test_get_instances_filtering_by_tag(): res["Reservations"][0]["Instances"][0]["InstanceId"].should.equal(instance1.id) res["Reservations"][0]["Instances"][1]["InstanceId"].should.equal(instance3.id) + # We should be able to use tags containing special characters + res = client.describe_instances( + Filters=[ + {"Name": f"tag:{tag3_name}", "Values": [json.dumps(["entry1", "entry2"])]} + ] + ) + res["Reservations"].should.have.length_of(1) + res["Reservations"][0]["Instances"].should.have.length_of(1) + res["Reservations"][0]["Instances"][0]["InstanceId"].should.equal(instance1.id) + @mock_ec2 def test_get_instances_filtering_by_tag_value():