From 767de8c33866cccd50103746b307bda9fdc1af07 Mon Sep 17 00:00:00 2001 From: Vasil Sirakov <50580913+VasilSirakov@users.noreply.github.com> Date: Mon, 14 Oct 2024 10:11:25 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20comma-separat?= =?UTF-8?q?ed=20values=20on=20the=20same=20key=20for=20EC2=20tag=20filters?= =?UTF-8?q?=20(#4742)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add support for multiple comma-separated values on a include/exclude tag filter. Signed-off-by: Vasil Sirakov * Added test cases for shouldExcludeInstance with multi-valued tag filters. Signed-off-by: Vasil Sirakov * Fix assertions. Signed-off-by: Vasil Sirakov --------- Signed-off-by: Vasil Sirakov --- providers/aws/resources/aws_ec2.go | 12 +++++++----- providers/aws/resources/aws_ec2_test.go | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/providers/aws/resources/aws_ec2.go b/providers/aws/resources/aws_ec2.go index 3109038f32..e5a209a171 100644 --- a/providers/aws/resources/aws_ec2.go +++ b/providers/aws/resources/aws_ec2.go @@ -774,7 +774,7 @@ func (a *mqlAwsEc2) getEc2Instances(ctx context.Context, svc *ec2.Client, filter for k, v := range filters.Tags { params.Filters = append(params.Filters, ec2types.Filter{ Name: aws.String(fmt.Sprintf("tag:%s", k)), - Values: []string{v}, + Values: strings.Split(v, ","), }) } if len(filters.InstanceIds) > 0 { @@ -1787,10 +1787,12 @@ func shouldExcludeInstance(instance ec2types.Instance, filters connection.Ec2Dis } } for k, v := range filters.ExcludeTags { - for _, iTag := range instance.Tags { - if iTag.Key != nil && *iTag.Key == k && - iTag.Value != nil && *iTag.Value == v { - return true + for _, tagValue := range strings.Split(v, ",") { + for _, iTag := range instance.Tags { + if iTag.Key != nil && *iTag.Key == k && + iTag.Value != nil && *iTag.Value == tagValue { + return true + } } } } diff --git a/providers/aws/resources/aws_ec2_test.go b/providers/aws/resources/aws_ec2_test.go index a8a375d94e..4404b6a64d 100644 --- a/providers/aws/resources/aws_ec2_test.go +++ b/providers/aws/resources/aws_ec2_test.go @@ -75,6 +75,26 @@ func TestShouldExcludeInstance(t *testing.T) { } require.False(t, shouldExcludeInstance(instance, filters)) }) + + t.Run("should exclude instances with matching values for the same tag", func(t *testing.T) { + filters := connection.Ec2DiscoveryFilters{ + ExcludeTags: map[string]string{ + "key-1": "val-1,val-2,val-3", + }, + } + require.True(t, shouldExcludeInstance(instance, filters)) + }) + + t.Run("should not exclude instances when no tag values match", func(t *testing.T) { + filters := connection.Ec2DiscoveryFilters{ + ExcludeTags: map[string]string{ + "key-1": "val-2,val-3", + "key-2": "val-1,val-3", + "key-3": "val-1,val-2", + }, + } + require.False(t, shouldExcludeInstance(instance, filters)) + }) } func TestDetermineApplicableRegions(t *testing.T) {